简体   繁体   中英

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

I have been able to export out VM Names and IP Addresses from within a single azure subscription using the following script.

$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"

However I have tried using the below to export the same data from an azure account that has multiple subscriptions but all I get is a blank CSV file.

$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"

Can anyone assist?

I think you need to move Get-AzVm right after the Select-AzSubscription? because right now you only get vms once (in default subscription)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM