04 August 2011

Find Duplicate VM NIC MAC Addresses Using PowerShell

We were having issues with some VMs and their networking. Unexpected, unexplained things were happening, and eventually someone thought that there might be some duplicate MAC addresses in the mix, causing grief. Some of the VMs had been copied from other vCenters, among other things.

Side note by AC: the unique ID of a vCenter server helps dictate the range of assigned MAC addresses for VMs in that vCenter. Therefore, in order to avoid MAC address duplicates, one should ensure that no vCenters within the same network have the same unique ID.

So, to find if there were any duplicate MAC addresses in use by VM NICs, we whipped up the following:
## Script function: find duplicate MAC addresses, and list the VMs/addresses involved
## Author: vNugglets.com

## get VirtualMachine .NET views where the items is not marked as a Template
$colDevMacAddrInfo = `
Get-View -ViewType VirtualMachine -Property Name,Config.Hardware.Device -Filter @{"Config.Template" = "False"} | %{
$strVMName = $_.Name
$_.Config.Hardware.Device | Where-Object {$_ -is [VMware.Vim.VirtualEthernetCard]} | %{
New-Object -Type PSObject -Property @{VMName = $strVMName; MacAddr = $_.MacAddress}
} ## end foreach-object
} ## end foreach-object

## are all of the MAC addresses unique?
($colDevMacAddrInfo | Select-Object -unique MacAddr).Count -eq $colDevMacAddrInfo.Count

## get the non-unique MAC addresses, returning objects with the count of the duplicates, the duplicate MAC, and the VM names that have the duplicate MAC
$colDevMacAddrInfo | Group-Object MacAddr | Where-Object {$_.count -gt 1} | Select-Object Count,@{n="DuplicateMAC"; e={$_.Name}},@{n="VMNames"; e={($_.Group | %{$_.VMName}) -join ","}}

It uses the Get-View cmdlet with the -Property parameter to ensure minimum memory usage and maximum speed.

Line 14: quick check to determine if there are any duplicate MAC addresses present -- compares the count of unique addresses to the total count of addresses

If there are duplicate MAC addresses, line 17 returns some nice information about the given MAC address, the count of VM NICs that have it, and the names of the VMs involved.

Once one finds the offending VMs, they can use something like the script in the vNugglets post Setting MAC Address for VM NICs using PowerShell to change the necessary MAC addresses and return things to standard working order. Hurray!