Monday, November 14, 2011

Hyper-V WMI MAC address to a different format

Here is a simple one that I don’t want to lose.

In my previous post I had mentioned how to get the MAC address that is assigned to the vNIC of a VM.

Get the VM, then find the associated vNIC (and make sure the VM is running):

$vm = Get-WmiObject Msvm_ComputerSystem -Filter "ElementName='$vmName'" -Namespace "root\virtualization" -ComputerName $HyperVHost

$vnicEmulated = $vm.GetRelated("Msvm_EmulatedEthernetPort")

$vnicSynthetic = $vm.GetRelated("Msvm_SyntheticEthernetPort")

In the comments of my previous post Ben Armstrong made the following suggestion (which works kind of nice):

$vssd = $vm.getRelated("Msvm_VirtualSystemSettingData") | where {$_.SettingType -eq 3}
    $vmLegacyEthernet = $vssd.getRelated("Msvm_EmulatedEthernetPortSettingData")

The MAC address is the “PermanentAddress” property of the $vnic and the “Address” property of the $vmLegacyEthernet – so pay attention to the property you are fetching.

A quick way to pluck it out is just to loop through the collection like this:

foreach ($e in $vnic) {
    $mac = $e.PermanentAddress
}

This gives you a MAC address that looks like this:  00155D680A14

This is all fine and dandy if the reason you need the MAC can deal with that format.  And mine can’t.  I must have it defined with dashes.

I went searching for fancy REGEX ways to handle this and could not come up with anything.  But some nice validators for MAC addresses.  The best in the Splunk forums.

So, here is my less sophisticated but useful part:

$macDash = $mac.Substring(0,2) + "-" + $mac.Substring(2,2) + "-" + $mac.Substring(4,2) + "-" + $mac.Substring(6,2) + "-" + $mac.Substring(8,2) + "-" + $mac.Substring(10,2)

This gives me the following result:  00-15-5D-68-0A-14

Just add that into the foreach loop above and move on.

No comments: