2011-08-05

Find duplicate MAC addresses #2

In the previous post about finding duplicate MAC addresses in a vSphere cluster we basically used a PowerCLI one-liner (http://adminthoughtcollection.blogspot.com/2011/05/find-duplicate-mac-addresses.html). That was straight forward but you had to dig through a long list of output and basically had to do the search & find manually.

Today's script makes use of a PowerShell hash table. It's output contains only the duplicate MAC addresses and the conflicting VMs.

Basically all MAC addresses get written into the hash table. But before writing them into it a lookup is performed. If the current MAC address has been written to the hash table before it must obviously be a duplicate.

# Get all VMs and their MAC addresses
$VMdata = Get-VM | Get-NetworkAdapter | select MacAddress,Parent

# Initialize the lookup hash table
$VMlookup = @{}

# Loop through all VMs one-by-one
ForEach ($SingleVM in $VMdata)
{
    # If the MAC address is already in the lookup hash table it is a duplicate
    if ($VMlookup.ContainsKey($SingleVM.MacAddress))
    {

        $VMOneNet = (Get-VM $($VMlookup.$($SingleVM.MacAddress)) | Get-NetworkAdapter | Where {$_.MacAddress -eq $SingleVM.MacAddress}).NetworkName
$VMTwoNet = (Get-VM $SingleVM.Parent | Get-NetworkAdapter | Where {$_.MacAddress -eq $SingleVM.MacAddress}).NetworkName        
        Write-Host "$($SingleVM.MacAddress)" -NoNewLine -ForegroundColor Green
        Write-Host " is a duplicate in:"

        Write-Host " * $($VMlookup.$($SingleVM.MacAddress)) [$VMOneNet]" -ForegroundColor Yellow
        Write-Host "and in:"
        Write-Host " * $($SingleVM.Parent) [$VMTwoNet]" -ForegroundColor Yellow
Write-Host
    }
    # Otherwise it is (still) a unique MAC
    else
    {
        $VMlookup.Add($SingleVM.MacAddress, $SingleVM.Parent)
    }
}



Update 2011-08-15: script now also displays the network of the NIC with the conflicting MAC address

No comments:

Post a Comment