Home > PowerShell > Finding duplicate MAC addresses on VM clusters

Finding duplicate MAC addresses on VM clusters

A little known fact is that you can use the group filter in PowerShell to very easily find duplicates in a set of objects based on a given object property. I had reason to use this today as our IT team was trying to validate their  virtual machines to ensure there were no conflicts due to duplication of the virtual MAC addresses. As they have a large set of machines this would require a script and PowerShell was perfect for the task.

If you’re working with the System Centre Virtual Machine Manager (SCVMM) you first need to add the required snap-in to manage it in PowerShell:

Add-PSSnapin Microsoft.SystemCenter.VirtualMachineManager

Once you’ve done this you can get duplicate MAC addresses (known as the “Physical Address” in SCVMM) like this:

Get-VirtualNetworkAdapter -All -vmmserver $servername | group -Property PhysicalAddress | ? {$_.Count -gt 1} | % {$_.Group} | Select-Object Name, VirtualNetwork, PhysicalAddress

The code above is quite simple. I’ll break it down by each pipeline section:

  • Use the Get-VirtualNetworkAdapter cmdlet from the snap-in to request all virtual network adapaters from a given server.
  • Group this set by the “PhysicalAddress” property, which will return an array of Count (number of instances), Name (the value of the property you grouped on) and Group (the actual object instances containing this value).
  • Filter the grouping results for any entries which are duplicated (i.e. Count is greater than one).
  • Loop through the results to return all the instances from the “Group” property.
  • Finally we use the Select-Object cmdlet to select only the properties of the original objects we care about in this case the name, virtual network, and the virtual MAC address.

It is worth noting that the “% {$_.Group}” pipeline section shows another very nice feature of PowerShell: if you return multiple sets of objects which are of the same type, it re-concatenates all the sets back into a single set.

There we go – one neat and simple way to get duplicate objects from any set of data based on the values of a given property. Of course, you could also replace the “$_.Count -gt 1” with “$_.Count -eq 1” to retrieve only the unique entries!

Thanks and hope this is of some help to you all!

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: