Thursday, 27 August 2015

Find Hyper V Virtual Machine by IP Address

Sometimes you need to find a VM by IP address. This could be because of various reasons, maybe the end user of a VM doesn't know what the machine is called in Hyper-V for example

I wrote the function in this script to do just that. simply load the function and call

find-vmip 10.20.30.40

and the VM that has this IP will be returned.


find-vmIP -ip 10.20.30.40

VMName Status IPAddresses

------ ------ -----------

(244) - Marc Turner Lab - DC {Ok} {10.20.30.40, fe80::851a:7585:a4bd:ce93}


function find-vmIP
{
    <#
       .Synopsis
      
       Finds the virtual machine on a Hyper-V server that has the IP address specified
       .Description
       .Example
       find-vmIP -ip 10.20.30.40
        VMName                        Status    IPAddresses
        ------                        ------    ----------- 
        (244) - Marc Turner Lab - DC  {Ok}      {10.20.30.40, fe80::851a:7585:a4bd:ce93}


        AUTHOR: Marc Turner
        LASTEDIT: 26/08/2015
       .Link
        http://www.marcturner.co.uk
    #>
    param($IP)
   
    # Clear variables used previously
    $vms = $null
    $FoundHost = $null
    # if the IP address was specified, carry on, otherwise throw an error
    if ($IP)
    {
        # Get a list of all VM's, pipe it to get network adapter details
        try
        {
            $vms = get-vm | Get-VMNetworkAdapter
        }
        catch
        {
            throw {$_.exception.message}
        }
       
        # if VM's were found carry on, otherwise throw an error (could be being ran on a client without Hyper-V)
        if ($vms)
        {
            # Search through list of VM's and find the match for the IP address, warn user if not found.
            try
            {
                $FoundHost = $vms | where {$_.ipaddresses -like "$IP"} | select vmname,status,ipaddresses
            }
            catch
            {
                throw {$_.exception.message}
            }
           
            if ($FoundHost)
            {
                return $FoundHost
            }
            else
            {
                Write-Warning "VM with the IP address '$IP' Was not found"
            }               
        }
        else
        {
            throw {"No Virtual machines were found on this host"}
        }
    }
    else
    {
        throw {"The IP address to search for was not specified, use find-vmIP -ip 10.20.30.40"}
    }
}