PS Script Find Machine or VM by Mac or IP

This powershell script is created for VMware PowerCLI. Its purpose is to find a VM by IP or MAC address. This is often useful when digging through NSX logs.

FindVmByIp

uses VMware Tools to resolve an IP address to virtual machine
Import-Module VMware.PowerCLI
$vCenter = <vCenter FQDN>

Connect-VIServer $vCenter

function findVmByIp {
    Param (
    [string]$SearchIp
    )
    $vms = get-vm
    foreach ($vm in $vms) {
        $ips = $vm.guest.IPAddress
        if (($ips -contains $searchIp) -and ($ips -notlike "")) {
            #Write-Host "Found VM: $vm"
            return $vm.Name
        }
    }
}

findVmByIp -searchIp "10.1.1.10"

FindVmByMac

uses VMware Tools to resolve a MAC address to a virtual machine
Import-Module VMware.PowerCLI
$vCenter = <vCenter FQDN>

Connect-VIServer $vCenter

function findVmByMac {
    Param (
    [string]$searchMac
    )

    $vms = get-vm
    foreach ($vm in $vms) {
        $macs = ($vm | Get-NetworkAdapter).MacAddress

        if (($macs -contains $searchMac) -and ($macs -notlike "")) {
            Write-Host "Found VM: $vm"
            return $vm
        }
    }
}

$vm = findVmByMac -searchMac "00:50:56:aa:bb:cc"

FindMachineByIp

uses DNS to resolve an IP address to a Name
function findMachineByIp {
    Param (
    [string]$SearchIp,
    [boolean]$EnableDNS=$true
    )

    if ($EnableDNS) {
        try {
            $Name = (Resolve-DnsName -Name $SearchIp).NameHost
            Write-Host "Found DNS Record: " $Name
            return $Name
        }
        catch {
            Write-Host "Could not resolve IP"
        }
        $vm = findVmByIp -SearchIp $SearchIp
    } else {
        $vm = findVmByIp -SearchIp $SearchIp
    }
    Write-Host "Found VM: " $vm.Name
    return $vm
}

$vm = findMachineByIp -searchIp "10.1.1.10"
Related Post