Wake on lan using powershell

Powershell has a strong .NET Framework integration. Because of this, you can do some pretty cool things with it. As .NET provides an UDP-Cliet, we can use it to make a simple wake on lan script using powershell.

Calculating the broadcast address

In order to send the magic packet to wake the remote host, you’ll need the broadcast address of your network. If you do not already know it, you can calculate it using a local ip address (or network address) and the subnet mask.

In order to use this function, simply pass in an address of your local network and the corresponding subnet mask.

Retrieving the mac address

If you do not know the mac address of the target computer, you can use arp to retrieve it. But this method requires, that you had at least one connection to the host (a ping should be enough).

Now simply provide the target’s ip address to this function (and optionally a delimiter) and it will return the proper mac address, as long as an arp entry exists.

Creating the magic packet

In order to wake up a pc we need to create the magic packet. The magic packet consists of 6 repetitions of the bytes 0xFF and 16 repetitions of complete mac address.

Now to create a magic packet, you simply call the above function with the desired mac address.

Sending the magic packet

Finally we have everything we need to wake the pc. In order to send the magic packet, we use .NET’s UdpClient.

Now you just need to provide the created magic packet, the broadcast address and the UDP Port to send the packet to. This is usually port 7 or 9.

Conclusion

Implementing a wake on lan script using powershell is quite easy. But you should not rely on the above method on retrieving the mac address of the host. As the arp cache could be purged, it’s recommended to store the mac address rather than trying to always retrieve it.  And splitting the actual wake-up code into mutliple functions might be a bit over-the-top.

The attached example code contains, after the function definitions, a small snippet which makes use of all the functions above. It tries to wake up the host 192.168.1.11 with the subnet mask 255.255.255.0.

Example Code

References

Leave a Reply

Your email address will not be published.

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