Reputation: 41
Currently trying get a report, preferable a spreadsheet, of all of the VMs in all of my Subscriptions along with their VNets. Similar to how it is presented in portal in the Virtual Machine main page but copying and pasting comes out very sloppy and unstructured.
I explored trying with PowerShell by iterating through all VMs, then pulling the VM name and RG to pull the Nic, then from the Nic get the subnet which contains the Vnet as well. However, I am unsure if this logic is completely sound. The below PS prints the VM name, VM Resource Group, VM Nic name, Nic subnet, and Nic VM. Does this make sense?
$vms = Get-AzureRmVM
Echo "VM Name,VM Resource Group,VM NIC Name,VM Subnet,VM VNet"
foreach ($vm in $vms){
$thisvmName = $vm.Name
$thisvmRG = $vm.ResourceGroupName
$thisvmNicName = $vm.NetworkProfile.NetworkInterfaces.Id.Split("/")[8]
$thisvmNic = Get-AzureRmNetworkInterface -Name $thisvmNicName -ResourceGroupName $thisvmRg
$thisvmNicIPConfig = Get-AzureRmNetworkInterfaceIpConfig -NetworkInterface $thisvmNic
$thisvmNicSubnet = $thisvmNicIpConfig.Subnet.Id.Split("/")[10]
$thisvmNicVNet = $thisvmNicIPConfig.Subnet.Id.Split("/")[8]
echo "$thisvmName,$thisvmRG,$thisvmNicName,$thisvmNicSubnet,$thisvmNicVNet"
}
If there is a completely easier path to getting a spreadsheet of all my VMs in all Subscriptions that I can sort by VNet I am open to it since this is seems pretty excessive. Also, if I can get a count of VMs (not NICS) in VNets that may work for my minimum end goal as well.. Any help would be appreciated!
Upvotes: 4
Views: 824
Reputation: 25001
You could do something like the following:
$vms = Get-AzureRmVM
$output = foreach ($vm in $vms){
$thisvmName = $vm.Name
$thisvmRG = $vm.ResourceGroupName
$thisvmNicName = $vm.NetworkProfile.NetworkInterfaces.Id.Split("/")[8]
$thisvmNic = Get-AzureRmNetworkInterface -Name $thisvmNicName -ResourceGroupName $thisvmRg
$thisvmNicIPConfig = Get-AzureRmNetworkInterfaceIpConfig -NetworkInterface $thisvmNic
$thisvmNicSubnet = $thisvmNicIpConfig.Subnet.Id.Split("/")[10]
$thisvmNicVNet = $thisvmNicIPConfig.Subnet.Id.Split("/")[8]
[pscustombject]@{
'VM Name'= $thisvmName
'VM Resource Group'= $thisvmRG
'VM NIC Name'= $thisvmNicName
'VM Subnet'= $thisvmNicSubnet
'VM VNet' = $thisvmNicVNet
}
$output | Export-Csv -Path C:\CSV.csv -NoTypeInformation
This does assume that you are happy with the data you have stored in your variables. The only changes are creating a custom object on each loop iteration that adds property names and associated values. Those objects are stored in an array ($output
), which is exported to CSV at the end. You don't technically need all the variables as you can calculate the values within the hash table.
Upvotes: 1