Script to Validate Virtual Switch

Do you need a script to validate that a virtual switch is configured correctly? Using WMI you can get the virtual switches like this:

$VSwitches = Get-WMIObject -namespace "root\virtualization" -class "Msvm_VirtualSwitch"

You can get the adapters like this:

$Adapter = Get-WMIObject Win32_NetworkAdapter | Where {$_.NetconnectionID –eq “name”}

You can map adapters to ethernet ports like this:

$ExternalNIC  = Get-WMIObject -namespace "root\virtualization" -query "SELECT * FROM Msvm_ExternalEthernetPort WHERE DeviceID='$($Adapter.GUID)'"

With these you can confirm that a switch with the same name exists.  You can validate properties of the physical adapter (IP, etc…). 

However, to tie these two pieces together, you can use the script below, which is a modification of Ben Armstrong’s script from https://blogs.msdn.com/b/virtual_pc_guy/archive/2009/02/24/script-determining-virtual-switch-type-under-hyper-v.aspx, using  “Associators.”

$HyperVServer = "VMHost1"

$VSwitches = Get-WMIObject -namespace "root\virtualization" -class "Msvm_VirtualSwitch" -ComputerName $HyperVServer

foreach($VirtualSwitch in $VSwitches){

   $query = "Associators of {$VirtualSwitch} where ResultClass=CIM_SwitchPort"

   $switchPorts = gwmi -namespace "root\virtualization" -Query $query -computername $HyperVServer

   # A VM only switch with no VMs connected will return null

   if ($switchPorts -ne $null){

        # Iterate over each switch port

        foreach ($switchPort in @($switchPorts)){

            # Get the Msvm_SwitchLANEndpoint associated with the switch port

            $query = "Associators of {$switchPort} where ResultClass=Msvm_SwitchLANEndpoint"

            $SwitchLANEndpoint = gwmi -namespace "root\virtualization" -Query $query -computername $HyperVServer

            # If there is no active connection on the switch port the results will be null

            if ($SwitchLANEndpoint -ne $null){

                # Get the CIM_EthernetPort for the Msvm_SwitchLANEndpoint

                $query = "Associators of {$SwitchLANEndpoint} where ResultClass=CIM_EthernetPort"

                $EthernetPort = gwmi -namespace "root\virtualization" -Query $query -computername $HyperVServer

                # Check to see if the associated Ethernet port is an external port

                if ($EthernetPort.__CLASS -eq "Msvm_ExternalEthernetPort"){

                   $VirtualSwitch.ElementName

                   $EthernetPort.ElementName

                }

            }

        }

    }

}

Feel free to add to this (unsupported, as-is) script, it is the wiki way.