首页 > 解决方案 > Azure Powershell 脚本

问题描述

我编写了一个 PowerShell 脚本来打印带有非托管磁盘的 VM 名称,但是它给了我一个错误。感谢对此的任何帮助-

$location=Read-Host -Prompt 'Input location for VMs'
$azuresubscription=Read-Host -Prompt 'Input Subscription Id'

$rmvms=Get-AzurermVM
# Add info about VM's from the Resource Manager to the array 
foreach ($vm in $rmvms) 
{     
    # Get status (does not seem to be a property of $vm, so need to call Get-AzurevmVM for each rmVM) 
    $vmstatus = Get-AzurermVM -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName -Status  | where Location -like $location

    # Add values to the array: 
    $vmarray += New-Object PSObject -Property @{` 
        # Subscription=$Subscription.SubscriptionName; ` 
        Subscription=$azuresubscription.SubscriptionName; `
        AzureMode="Resource_Manager"; ` 
        Name=$vm.Name; PowerState=(get-culture).TextInfo.ToTitleCase(($vmstatus.statuses)[1].code.split("/")[1]); ` 
        Size=$vm.HardwareProfile.VirtualMachineSize} 
}

foreach ($vm in $vmarray)
{
    $vmdiskstatus = (Get-AzurermVM -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName).StorageProfile.OsDisk.ManagedDisk
    if (!$vmdiskstatus) {Write-Host $vm.Name}
}

错误信息:

($vmarray 导致空数组) -

无法索引到空数组。

预期输出 - $vmarray 应该有一个虚拟机,因为eastus 中有一个正在运行的实例(这就是我用作 $location 的值)

标签: azurepowershell

解决方案


根据维克多席尔瓦的要求,将我的评论添加为答案,这里是:

您需要$vmarray在进入循环之前定义 as 数组以向其中添加对象。然后,在那个循环之后,即使是空的,也foreach ($vm in $vmarray) 确实有一个要索引的数组:

$location=Read-Host -Prompt 'Input location for VMs'
$azuresubscription=Read-Host -Prompt 'Input Subscription Id'

$rmvms=Get-AzurermVM

###################################################
# create an array variable to collect the result(s)
###################################################
$vmarray = @()

# Add info about VM's from the Resource Manager to the array 
foreach ($vm in $rmvms) 
{     
    # rest of your code
}

推荐阅读