Tuesday, November 22, 2011

Hyper-V WMI powering on VMs and getting MAC addresses

Previously I have written about formatting MAC addresses from Hyper-V WMI into a format to be consumed by another program and about duplicating a Master (or Template) VM into multiple virtual machines.
Today I am going to put that together and produce an output that contains the each VM as a name, mac address pair in an array.
My Master / Template VM has the MAC address set to dynamic, so this property is going to repeat. I am also going to take advantage on the Hyper-V process of booting the VM to assign the MAC address.
From my previous duplication script I have an array of VMs: $arrNewVms
$arrUpdatedVms = @()

write-progress -Id 1 "Discovering MAC addresses" -Status "Executing"
foreach ($vmName in $arrNewVms) {
$vm = Get-WmiObject Msvm_ComputerSystem -Filter "ElementName='$vmName'" -Namespace "root\virtualization" -ComputerName $hypervHost
$Result = $vm.RequestStateChange(2) # start
ProcessWMIJob $Result
$vssd = $vm.getRelated("Msvm_VirtualSystemSettingData") | where {$_.SettingType -eq 3}
$vmLegacyEthernet = $vssd.getRelated("Msvm_EmulatedEthernetPortSettingData")
# $vnic = $vm.GetRelated("Msvm_EmulatedEthernetPort") # this only returns while the VM is running and $mac = $e.PermanentAddress
foreach ($e in $vmLegacyEthernet) {
$mac = $e.Address
$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)
$arrUpdatedVms += ($vmName + "," + $macDash)
$vm.RequestStateChange(3) # stop
write-progress -Id 1 "Discovering MAC addresses" -Completed $TRUE
In this I refer to a helper Function “ProcessWMIJob” this is handy in that it forces me to wait until the Start VM process is completed. If I didn’t use this my VMs would not be started and therefore will not in turn power off – it becomes a bit of a timing issue.
The Function can be found at the beginning of the script here.
Next time, something completely different.

No comments: