Share via


How to list VMs by the virtual network they are connected to

This is from an internal question I replied to. This is a simply script given as a starting point that can be extended.

----------------------------------------------------------------------------------------------------------------------------------

I have a host that has 4 physical network cards, 3 of which are mapped to virtual switches that are External.

 

I would like to, programmatically,

 

(1) get these 3 virtual network adapters for the given host

PS C:\ > $virtnets = Get-VirtualNetwork -VMHost myhost

PS C:\ > $virtnets.Count

5

PS C:\ > $virtnets | ft name

Name

----

BLAH

3BLAH3

PRODUCTION

Broadcom - Virtual Network

Test1

(2) figure out how many VMs are connected to each of them

$vmhost = Get-VMHost | where {$_.Name -match "myhost"}

$vmhost.VMs.Count

43

   PS C:\> $count = 1

PS C:\> foreach($vm in $vmhost.VMs){foreach($vnic in $vm.VirtualNetworkAdapters) {if($virtnets -eq $vnic.virtualnetwork){Write-Host ("VM: " + $vm.Name + ", NIC: " + $vnic.VirtualNetwork + ", Count: " + $Count++)}}}

VM: 32w2k8r2, NIC: Test1, Count: 1

VM: hectorl3, NIC: Test1, Count: 2

VM: VI3Servers, NIC: Test1, Count: 3

VM: vi3servers01, NIC: Test1, Count: 4

VM: vi3vc2501, NIC: Broadcom - Virtual Network, Count: 5

VM: VirtuozzoVM01, NIC: Test1, Count: 6

VM: VirtuozzoVM02, NIC: Test1, Count: 7

VM: VM_fromblank, NIC: Test1, Count: 8

VM: VM1_DUPMAC, NIC: Broadcom - Virtual Network, Count: 9

VM: VM1_DUPMAC, NIC: Broadcom - Virtual Network, Count: 10

VM: VMM2008R2RTM, NIC: Test1, Count: 11

VM: VMM2008R2TEST, NIC: Test1, Count: 12

VM: vmm2008test, NIC: Test1, Count: 13

VM: VMNIC, NIC: 3BLAH3, Count: 14

VM: VMNIC, NIC: BLAH, Count: 15

VM: VMNIC, NIC: PRODUCTION, Count: 16

PS C:\>