PowerCLI – Find mac in a haystack

find a vms mac in two minutes with this really useful one-liner

 Get-VM | Get-NetworkAdapter ´
 | Where-Object {$_.MacAddress -eq "00:50:56:xx:xx:xx:"} | Select MacAddress,NetworkName,Name,Parent,ConnectionState 

Ok, it’s a bit slow to run, this function by Robert van den Nieuwendijk is much faster

 

[code language=”powershell”]
function Get-VmByMacAddress {
<# .SYNOPSIS Retrieves the virtual machines with a certain MAC address on a vSphere server. .DESCRIPTION Retrieves the virtual machines with a certain MAC address on a vSphere server. .PARAMETER MacAddress Specify the MAC address of the virtual machines to search for. .EXAMPLE Get-VmByMacAddress -MacAddress 00:0c:29:1d:5c:ec,00:0c:29:af:41:5c Retrieves the virtual machines with MAC addresses 00:0c:29:1d:5c:ec and 00:0c:29:af:41:5c. .EXAMPLE "00:0c:29:1d:5c:ec","00:0c:29:af:41:5c" | Get-VmByMacAddress Retrieves the virtual machines with MAC addresses 00:0c:29:1d:5c:ec and 00:0c:29:af:41:5c. .COMPONENT VMware vSphere PowerCLI .NOTES Author: Robert van den Nieuwendijk Date: 18-07-2011 Version: 1.0 #>

[CmdletBinding()]
param(
[parameter(Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true)]
[string[]] $MacAddress
)

begin {
# $Regex contains the regular expression of a valid MAC address
$Regex = "^[0-9A-Fa-f][0-9A-Fa-f]:[0-9A-Fa-f][0-9A-Fa-f]:[0-9A-Fa-f][0-9A-Fa-f]:[0-9A-Fa-f][0-9A-Fa-f]:[0-9A-Fa-f][0-9A-Fa-f]:[0-9A-Fa-f][0-9A-Fa-f]$"

# Get all the virtual machines
$VMsView = Get-View -ViewType VirtualMachine -Property Name,Guest.Net
}

process {
ForEach ($Mac in $MacAddress) {
# Check if the MAC Address has a valid format
if ($Mac -notmatch $Regex) {
Write-Error "$Mac is not a valid MAC address. The MAC address should be in the format 99:99:99:99:99:99."
}
else {
# Get all the virtual machines
$VMsView | `
ForEach-Object {
$VMview = $_
$VMView.Guest.Net | Where-Object {
# Filter the virtual machines on Mac address
$_.MacAddress -eq $Mac
} | `
Select-Object -property @{N="VM";E={$VMView.Name}},
MacAddress,
IpAddress,
Connected
}
}
}
}
}
[/code]

Register it as a function

  C:\vSpherePowerCLI\Scripts> .  C:\vSpherePowerCLI\functions\Get-VmByMacAddress.ps1

Then run

  Get-VmByMacAddress -MacAddress 00:50:56:db:0c:c8 | fl

 

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.