0

我对 PowerShell 非常陌生,我们有客户要求他们将在 Excel 表中与下面的列共享 Azure VM 详细信息。

Excel 工作表值

我们必须使用 Powershell 脚本从所有订阅和资源组中获取 VM 状态详细信息。

输出:

在此处输入图像描述

我可以使用以下代码执行单个 RSG 和 VM 值

$SubscriptionName = Get-AzSubscription -SubscriptionId $subscriptionId
$RG = "rgp-use2-prd-bioportalbiopeople1"
$RSGName = Get-AzResourceGroup -Name $RG
$VMs = Get-AzVM -Name "vmbppapiv1prd02" 
$VMState = (Get-AzVM -Name $VM -ResourceGroupName $RG -Status).Statuses
$vmOutput = $VMs | ForEach-Object {
    [PSCustomObject]@{
        "Resource Group Name" = $RSGName.ResourceGroupName
        "Subscription Name" = $SubscriptionName.Name
        "VM Name" = $_.Name
        "VM Type" = $_.StorageProfile.osDisk.osType
        "VM Statss" = ($VMState | where code -Like 'PowerState/*')[0].DisplayStatus
        
      }
}

$vmOutput | Format-Table -AutoSize 
$vmOutput | export-csv C:\Projects\data.csv

4

1 回答 1

0

我自己无法对此进行测试,但您必须创建嵌套循环来获取所有订阅和资源组的详细信息。

像这样的东西:

$subscriptions = Get-AzSubscription -TenantId "aaaa-aaaa-aaaa-aaaa"  # enter the tenant ID here
$VMs = Get-AzVM -Name "vmbppapiv1prd02"

$vmOutput = foreach ($vm in $VMs) {
    foreach ($subscription in $subscriptions) {
        Set-AzContext -SubscriptionId $subscription.Id
        (Get-AzResourceGroup).ResourceGroupName | ForEach-Object {
            $vmState = (Get-AzVM -Name $vm.Name -ResourceGroupName $_ -Status).Statuses
            [PSCustomObject]@{
                "Resource Group Name" = $_
                "Subscription Name"   = $Subscription.Name
                "VM Name"             = $vm.Name
                "VM Type"             = $vm.StorageProfile.osDisk.osType
                "VM Status"           = ($vmState | where code -Like 'PowerState/*')[0].DisplayStatus
            }
        }
    }
}

$vmOutput | Format-Table -AutoSize 
$vmOutput | Export-Csv -Path 'C:\Projects\data.csv' -NoTypeInformation
于 2020-11-17T13:17:16.920 回答