Powershell: Wake up on Lan – redux

In this revision, I’ve added support for IP based wake ups. However, the IP needs to be in the local ARP table.

param (
    [parameter(Position=0,
        Mandatory = $true,
        ParameterSetName="bymac",
        HelpMessage="Wake up a machine by known mac address.")]
    [string]
    $targetMac,
    [parameter(Position=0,
        mandatory = $true,
        ParameterSetName="byip",
        HelpMessage="Wake up a machine by last known IP address.")]
    [Net.IPAddress]
    $targetIP,
    [parameter(Position=1)]
    $network = [net.ipaddress]::Broadcast,
    [parameter(Position=2)]
    $subnet = [net.ipaddress]::Broadcast
)

try {
    if($network.gettype().equals([string])) {
        $network = [net.ipaddress]::Parse($network);
    }
    if($subnet.gettype().equals([string])) {
        $subnet = [net.ipaddress]::Parse($subnet);
    }
    
    $broadcast = new-object net.ipaddress (([system.net.ipaddress]::parse("255.255.255.255").address -bxor $subnet.address -bor $network.address))
    
    try {
        $targetIP = [net.ipaddress]::Parse($targetMac.toupper()).tostring() # | Out-Null;
        
        
    } catch {
        #$_;
        try {
            [Net.NetworkInformation.PhysicalAddress]::Parse($targetMac.toupper()) | Out-Null;
        } catch {
            #$_;
        }
    }
    if($targetIP) {
        try {
            $nmac = (arp -a $targetIP | ? {$_ -imatch $targetIP}).split(" ") | ? {$_.trim().length -gt 0;} | %{ $_.trim(); };
            $targetMac = $nmac[1];
        }catch{
            throw "IP address is unknown.";
        }
    }
    
    $mac = [Net.NetworkInformation.PhysicalAddress]::Parse($targetMac.toupper().replace(".",""))
    
    $u = New-Object net.sockets.udpclient
    $ep = New-Object net.ipendpoint $broadcast, 0
    $ep2 = New-Object net.ipendpoint $broadcast, 7
    $ep3 = New-Object net.ipendpoint $broadcast, 9

    $payload = [byte[]]@(255,255,255,255,255,255);
    $payload += ($mac.GetAddressBytes()*16)

    for($i = 0; $i -lt 10; $i++) {
        $u.Send($payload, $payload.Length, $ep) | Out-Null
        $u.Send($payload, $payload.Length, $ep2) | Out-Null
        $u.Send($payload, $payload.Length, $ep3) | Out-Null
        "$(date) - WOL payload $($i+1)/10 sent to $targetMac on $broadcast/$subnet" | Write-Debug;
        sleep -Milliseconds 10;
    }
} catch {
    $_ | Write-Error;
}

Comments

2 responses to “Powershell: Wake up on Lan – redux”

Leave your response
  1. Nick says:

    This script looks good. Would you mind adding comments to it to describe its logic? Also, it doesn’t appear to like having colons in MAC addresses even though colons is pretty standard. Thanks for sharing your script!

  2. […] Nick asked, “This script looks good. Would you mind adding comments to it to describe its logic? Also, it doesn’t appear to like having colons in MAC addresses even though colons is pretty standard. Thanks for sharing your script!” (link). […]