Tuesday, 22 March 2016

Get all IPs, Mac Addresses, and Network Adapter names for each VM

Recently I had to write a PowerCLI script to gather all of the MAC address, IP Address, and Network adapter information from all VMs in a cluster.  While not super difficult, it proved a bit challenging as I couldn't just use get-networkadapter as that only returns Network Adapter name and MAC address, but not IP information, and conversly the vm.guest.net object returns MAC address and IP information, but not Network Adapter Name.  With a ton of nested loops (which takes forever to run) I was able to gather the info and export it to a CSV

$vms = get-vm | sort Name
foreach($vm in $vms)
{

$VMx = get-view $VM.ID
$HW = $VMx.guest.net
$adapters = get-networkadapter -VM $vm
foreach($dev in $hw)
{
foreach($ip in $dev.ipaddress)
{
foreach($adapter in $adapters)
{
$out += $dev | select @{N="Name";E={$vm.name}}, @{N="AdapterName";E={$adapter.Name}},@{N="IP Address";E={$ip}}, @{N="MAC";E={$dev.macaddress}} | WHERE {$dev.macaddress -eq $adapter.macaddress}

}
}
}
}

$out | export-csv .\VM_MAC_IP.csv -notypeinformation


No comments:

Post a comment