Search code examples
azurevirtual-machineip-addresssubscription

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?


Solution

  • 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
        ...
    }