PoshCode Logo PowerShell Code Repository

Modified WOL impl. by FrankSpierings 17 months ago (modification of post by FrankSpierings view diff)
diff | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/2115"></script>download | new post

This function can send WOL packages. Note that this a modified version of code already floating online. You need to specify the Mac address as a string. Optionally use -Ports (0,1000) to specify the udp ports. (use -verbose to show which pacakges are being send).

  1. function SendUdpWol {
  2.         #Packet construction reference:
  3.         #- http://wiki.wireshark.org/WakeOnLAN
  4.         #- http://en.wikipedia.org/wiki/Wake-on-LAN
  5.         #
  6.         #This code is a modified version of:
  7.         # - http://thepowershellguy.com/blogs/posh/archive/2007/04/01/powershell-wake-on-lan-script.aspx
  8.        
  9.         param (
  10.                 [parameter(Mandatory=$true)]
  11.                 [ValidateLength(17,17)]
  12.                 [ValidatePattern("[0-9|A-F]{2}:[0-9|A-F]{2}:[0-9|A-F]{2}:[0-9|A-F]{2}:[0-9|A-F]{2}:[0-9|A-F]{2}")]
  13.                 [String]
  14.                 $MacAddress,
  15.                
  16.                 [parameter(Mandatory=$false)]
  17.                 [int[]]
  18.                 $Ports=@(0,7,9)
  19.         )
  20.        
  21.         [int]$MAGICPACKETLENGTH=102 #'Constant' defining total magic packet length.
  22.         [Byte[]]$magicPacket=[Byte[]](,0xFF * $MAGICPACKETLENGTH) #Initialize packet all 0xFF for packet length.
  23.        
  24.         [Byte[]]$byteMac=$MacAddress.Split(":") |% { #Convert the string MacAddress to a byte array (6 bytes).
  25.                 [Byte]("0x" + $_)
  26.         }
  27.        
  28.         #Starting from byte 6 till 101, fill the packet with the MAC address (= 16 times).
  29.         6..($magicPacket.Length - 1) |% {
  30.                 $magicPacket[$_]=$byteMac[($_%6)]              
  31.         }
  32.        
  33.         #Setup the UDP client socket.
  34.         [System.Net.Sockets.UdpClient] $UdpClient = new-Object System.Net.Sockets.UdpClient
  35.         foreach ($port in $Ports) {
  36.                 $UdpClient.Connect(([System.Net.IPAddress]::Broadcast),$port) #Send packet on each defined port.
  37.                 Write-Verbose $("Sending magic packet to {0} port {1}" -f $MacAddress,$port)
  38.                 [Void]$UdpClient.Send($magicPacket,$magicPacket.Length) #Don't return the packet length => [void]
  39.         }
  40.         $UdpClient.Close()
  41. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me