如何从多个 Azure 订阅中导出虚拟机名称和 IP 地址

How to export Virtual Machine Names and IP Addresses from within multiple azure subscriptions

我已经能够使用以下脚本从单个 azure 订阅中导出 VM 名称和 IP 地址。

$report = @()
$vms = get-azvm
$nics = get-aznetworkinterface | ?{ $_.VirtualMachine -NE $null}

foreach($nic in $nics)
{
    $info = "" | Select VmName, ResourceGroupName, HostName, IpAddress
    $vm = $vms | ? -Property Id -eq $nic.VirtualMachine.id
    $info.VMName = $vm.Name
    $info.ResourceGroupName = $vm.ResourceGroupName
    $info.IpAddress = $nic.IpConfigurations.PrivateIpAddress
    $info.HostName = $vm.OSProfile.ComputerName
    $report+=$info
}
$report | Export-Csv -Path "c:\Azure\VMIPs.csv"

不过,我尝试使用以下方法从具有多个订阅的 azure 帐户导出相同的数据,但我得到的只是一个空白的 CSV 文件。

$report = @()
$vms = get-azvm
$azureSubs = get-azsubscription
$azureSubs.foreach{
    Select-AzSubscription $_ # << change active subscription
$nics = get-aznetworkinterface | ?{ $_.VirtualMachine -NE $null}

foreach($nic in $nics)
{
    $info = "" | Select VmName, ResourceGroupName, HostName, IpAddress
    $vm = $vms | ? -Property Id -eq $nic.VirtualMachine.id
    $info.VMName = $vm.Name
    $info.ResourceGroupName = $vm.ResourceGroupName
    $info.IpAddress = $nic.IpConfigurations.PrivateIpAddress
    $info.HostName = $vm.OSProfile.ComputerName
    $report+=$info
    }
}
$report | Export-Csv -Path "c:\Azure\VMIPs.csv"

有人可以帮忙吗?

我认为您需要在 Select-AzSubscription 之后立即移动 Get-AzVm?因为现在你只能获得一次虚拟机(在默认订阅中)

$azureSubs.foreach{
    Select-AzSubscription $_ # << change active subscription
    $nics = get-aznetworkinterface | ?{ $_.VirtualMachine -NE $null}
    $vms = get-azvm
    ...
}