Dela via


Wake On LAN (WOL) – PowerShell style

Working on another project and I needed a way to wake up an offline server from within my PS script.  I found this genius blog post and converted it to a script.

Genius blog post - The PowerShell Guy : PowerShell Wake-on-lan script

I saved the below text as send-wol.ps1 for re-usability.  This code came from The PowerShell Guy blog, I cannot claim credit !!!!  I just made it a script.  Mainly, I combined two snippets from his post and added the args reference.

 $mac = [byte[]]($args[0].split('-') |% {[int]"0x$_"}) 
  
 $UDPclient = new-Object System.Net.Sockets.UdpClient
 $UDPclient.Connect(([System.Net.IPAddress]::Broadcast),4000)
 $packet = [byte[]](,0xFF * 102)
 6..101 |% { $packet[$_] = $mac[($_%6)]}
 $UDPclient.Send($packet, $packet.Length)

So how would you run it?  I would proactively open a command prompt and get the mac addresses from your arp table and save them to a file.  You can get at the table by running “arp –a” and locating the IP address for the node you are concerned about.  Later if you want to wake the host up, just open PowerShell, and run the script as follows:

image

Other ways to get the arp address for an offline machine?  If your network devices have SNMP enabled you may be able to leverage vendor tools to retrieve arp data from there.  If you have an inventory too such as System Center Configuration Manager, it would also store that data.

Comments

  • Anonymous
    April 23, 2009
    One more way to remotely wake up a server over Internet is a service "Wake-On-LAN Online"  - http://www.wakeonlan.me. It can be used with any device connected to the Internet and allows simple wake up PC just with a link to the pahe of the site with necessary MAC and IP address. Furthermore the wake up can be scheduled for certain time and date and the site will wake up the PC automatically in that time.

  • Anonymous
    January 25, 2012
    Using the genius blog you referenced as a starting point, I tweaked your $Mac = statement to be able to parse the 3 most common MAC formats... $args[0] -match "^(..)-(..)-(..)-(..)-(..)-(..)$|^(..):(..):(..):(..):(..):(..)$|^(..)(..)(..)(..)(..)(..)$" | Out-Null Switch ($matches.Keys) { {$_ -contains 1}{$mac = [byte[]]($matches[1..6] | % {[int]"0x$"})} {$ -contains 7}{$mac = [byte[]]($matches[7..12] | % {[int]"0x$"})} {$ -contains 13}{$mac = [byte[]]($matches[13..18] | % {[int]"0x$_"})} }

  • Anonymous
    February 19, 2012
    The comment has been removed