Nigel Boulton's Blog
10Sep/1111

Wake-on-LAN using a PowerShell Script

I currently have a home lab based on Simon Gallagher's excellent vTARDIS. This is an HP ProLiant ML115 which runs 8 virtual ESXi hosts arranged into a cluster which in turn run 30 Linux virtual machines. As you can imagine, this takes quite a while to start up! For this reason, I wanted a way to start the physical host programmatically (either on a scheduled basis or remotely via my home automation interface), in preparation for working on it or doing some learning. So a PowerShell script was obviously the answer! Within the lab itself I have a PowerCLI script which automatically powers up the various components in the correct order (but that's another story...).

The script I developed is shown below. I decided to share it via my blog as a) it might be useful to someone and b) it demonstrates the use of some handy PowerShell 2 features, such as advanced functions, parameter sets, parameter validation and comment-based Help, along with other good stuff like regular expressions, error handling and writing to the Windows event log. In the distant past I used an ActiveX control called UltraWOL (from UltraJones software, who don't seem to be around anymore) and called it from VBScript scripts to facilitate Wake-on-LAN, but I wanted to find a nice 'PowerShell only' way of implementing it.

The script can be used in two ways: it can be provided with a CSV file which maps 'known' machines to their MAC addresses, and then used to wake up one of these machines by providing just the computer name as a parameter, or alternatively, simply by specifying a MAC address using the 'MACAddress' parameter, to have a Wake-on-LAN magic packet containing that MAC address sent. In either case, results are reported to standard output and also recorded in the Application event log.

The script is shown below, but for your convenience you can download a copy here (MD5 checksum: 0533313E71C42816217F948247C17F9E) to save you copying and pasting (and all the potential problems associated with doing that) should you want to make use of it. Below the listing is a brief outline of the operation of the script.

<#
.NOTES
	================================================================================
	Filename:	Wake-Machine.ps1

	Author:		Nigel Boulton, http://www.nigelboulton.co.uk

	Version:	1.00

	Date:		10 Sep 2011

	Mod dates:	

	Notes:		See http://www.nigelboulton.co.uk/2011/09/
							wake-on-lan-using-a-powershell-script/
				for further details of this script
	================================================================================
.SYNOPSIS
	Wakes up a machine using Wake-on-LAN
.DESCRIPTION
	If the ComputerName parameter is given and is the name of a known machine (specified
	in the CSV file 'MACLookup.csv', stored in the same folder as this script), sends a
	Wake-on-LAN magic packet containing the MAC address of that machine. The ComputerName
	parameter is the default, so if omitted the script will expect any argument given to
	be the name of a known machine

	The format for the CSV file is as follows. Header information as shown is required in
	this file:

	ComputerName,MACAddress
	pc1,00-16-da-2b-6f-b8

	If the alternative MACAddress parameter is given and is a valid MAC address, sends a
	Wake-on-LAN magic packet containing that MAC address. In this case the MACLookup.csv
	file is not used and is not required to be present

	Results are reported to standard output and also recorded in the Application event log
.EXAMPLE
    Wake-Machine.ps1 -ComputerName PC1

	Description
	-----------
	Sends a Wake-on-LAN magic packet for the known machine 'PC1'
.EXAMPLE
    Wake-Machine.ps1 PC1

	Description
	-----------
	Sends a Wake-on-LAN magic packet for the known machine 'PC1'
.EXAMPLE
	Wake-Machine.ps1 -MACAddress 00-16-DA-2B-6F-B8

	Description
	-----------
	Sends a Wake-on-LAN magic packet containing the MAC address 00-16-DA-2B-6F-B8
.LINK

http://www.nigelboulton.co.uk/2011/09/wake-on-lan-using-a-powershell-script/

#>
[CmdletBinding(DefaultParameterSetName='ComputerName')]
param(
 [Parameter(Mandatory=$true,
      HelpMessage="Enter a known machine name. See Help for this script for further information",
      Position=0,
      ParameterSetName='ComputerName')]
    [ValidateNotNullOrEmpty()]
 [string]$ComputerName,            

 [Parameter(Position=0,
      ParameterSetName='MACAddress')]
 [ValidatePattern('^([0-9a-fA-F]{2}[:-]{0,1}){5}[0-9a-fA-F]{2}$')]
 [string]$MACAddress
)            

function Send-MagicPacket {
 param(
 [Parameter(Mandatory=$true,
      HelpMessage="Enter a valid MAC address")]
 [ValidatePattern('^([0-9a-fA-F]{2}[:-]{0,1}){5}[0-9a-fA-F]{2}$')]
 [string]$MAC
 )
 <#
	.NOTES
		================================================================================
		Purpose: 		To send a Wake-on-LAN magic packet with a specified MAC address
		Assumptions:
		Effects:
		Inputs:
		 $MAC:			MAC address to include in packet
		Calls:
		Returns:		

		Notes:			Based on http://thepowershellguy.com/blogs/posh/archive/
										2007/04/01/powershell-wake-on-lan-script.aspx
		================================================================================
	.SYNOPSIS
		Sends a Wake-on-LAN magic packet containing a specified MAC address
	.DESCRIPTION
	    Sends a Wake-on-LAN magic packet containing a specified MAC address. The MAC
		address is specified by the MAC parameter. The octets of the MAC address may
		be separated by dashes '-', colons ':' or nothing
	.EXAMPLE
		Send-MagicPacket -MAC 00-16-DA-2B-6F-B8

		Description
		-----------
		Sends a Wake-on-LAN magic packet containing the MAC address 00-16-DA-2B-6F-B8
	.EXAMPLE
		Send-MagicPacket -MAC 00:16:DA:2B:6F:B8

		Description
		-----------
		Sends a Wake-on-LAN magic packet containing the MAC address 00-16-DA-2B-6F-B8
	.EXAMPLE
		Send-MagicPacket -MAC 0016DA2B6FB8

		Description
		-----------
		Sends a Wake-on-LAN magic packet containing the MAC address 00-16-DA-2B-6F-B8
	.LINK

http://www.nigelboulton.co.uk/2011/09/wake-on-lan-using-a-powershell-script/

	#>            

 # Use regex to strip out separators (: or -) if present and split string every second character
 # Piping to Where-Object {$_} avoids empty elements between each pair of characters
 $MACArray = ($MAC -replace '[-:]', [String]::Empty) -split '(.{2})' | Where-Object {$_}            

 $MACByteArray = $MACArray | ForEach-Object {[Byte]('0x' + $_)}
 $UDPClient = New-Object System.Net.Sockets.UdpClient
 $UDPClient.Connect(([System.Net.IPAddress]::Broadcast),4000)
 $Packet = [Byte[]](,0xFF * 6)
 $Packet += $MACByteArray * 16
 Write-Debug "Magic packet contents: $([bitconverter]::ToString($Packet))"
 [void]$UDPClient.Send($Packet, $Packet.Length)
 Write-Debug "Wake-on-LAN magic packet of $($Packet.Length) bytes sent to $($MAC.ToUpper())"
}            

#***********************************************************************************
# Start of script
#Requires -Version 2
Set-StrictMode -Version 2            

# User configurable values
$MACLookupFilePath = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) MACLookup.csv # Location and name of MAC address lookup file            

# Initialise variables
$ComputerDisplayName = $Null ; $Msg = $Null            

# Register event log source if required (requires admin rights)
if (!(Test-Path HKLM:\SYSTEM\CurrentControlSet\Services\Eventlog\Application\$($MyInvocation.MyCommand.Name))) {
 Try {
  New-EventLog -LogName Application -Source $MyInvocation.MyCommand.Name -ErrorAction Stop
 }
 Catch {
  Write-Host "WARNING: Unable to register event log source. You must run this script at least once as an administrator to do this" -ForegroundColor Red -BackgroundColor Black
 }
}            

if ($PsCmdlet.ParameterSetName -eq 'ComputerName') { # Computer name specified            

 # Import CSV file of MAC addresses for known machines into a hash table.
 # This makes it easy to check whether a given machine exists in this list,
 # and retrieve its MAC address if so
 $MACLookup = @{}
 Import-CSV -Path $MACLookupFilePath | ForEach-Object {$MACLookup[$_.ComputerName] = $_.MACAddress}            

 # Find MAC address for machine in hash table (this is case insensitive)
 if ($MACLookup.ContainsKey($ComputerName) -eq $True) {
  $MACAddress = $MACLookup.Get_Item($ComputerName)
  $ComputerDisplayName = "($($ComputerName.ToUpper()))"
  # Validate MAC address
  if ($MACAddress -notmatch '^([0-9a-fA-F]{2}[:-]{0,1}){5}[0-9a-fA-F]{2}$') {
   $Msg = "ERROR: Invalid MAC address specified: '$MACAddress'. Verify the MAC address for the computer '$ComputerName' in the CSV file '$MACLookupFilePath'"
   Write-Host $Msg -ForegroundColor Red -BackgroundColor Black
   Try {
    Write-EventLog -LogName Application -Source $MyInvocation.MyCommand.Name -EventID 1001 -EntryType Error -Message $Msg -Category 0
   }
   Catch {
    Write-Host "WARNING: Unable to write to event log. You must run this script at least once as an administrator to register the event log source" -ForegroundColor Red -BackgroundColor Black
   }
   Throw "Invalid MAC address"
  }
 } else {
  $Msg = "ERROR: Unrecognised computer name: '$($ComputerName.ToUpper())'. Add the computer name and MAC address to the CSV file '$MACLookupFilePath'"
  Write-Host $Msg -ForegroundColor Red -BackgroundColor Black
  Try {
   Write-EventLog -LogName Application -Source $MyInvocation.MyCommand.Name -EventID 1001 -EntryType Error -Message $Msg -Category 0
  }
  Catch {
   Write-Host "WARNING: Unable to write to event log. You must run this script at least once as an administrator to register the event log source" -ForegroundColor Red -BackgroundColor Black
  }
  Throw "Unrecognised computer name"
 }
}            

Send-MagicPacket -MAC $MACAddress
$Msg = ("Wake-on-LAN magic packet sent to $($MACAddress.ToUpper()) $ComputerDisplayName").Trim()
Write-Output $Msg
Try {
 Write-EventLog -LogName Application -Source $MyInvocation.MyCommand.Name -EventID 1000 -EntryType Information -Message $Msg -Category 0
}
Catch {
 Write-Host "WARNING: Unable to write to event log. You must run this script at least once as an administrator to register the event log source" -ForegroundColor Red -BackgroundColor Black
}

The first section of the script is the comment-based Help which can be displayed by typing Get-Help .\Wake-Machine.ps1 in a PowerShell console in the usual way (I'd advise that you do this to help understand the operation of the script before attempting to implement it).

Following that are the definitions for the two possible parameters. Note their parameter set names - these are called 'ComputerName' and 'MACAddress' respectively. You will notice that the default parameter set has been set as 'ComputerName'. This means that if the parameter name is omitted, the script will expect any argument given to be the name of a known machine in the CSV file.

The CSV file must be called 'MACLookup.csv' and stored in the same folder as this script. The format for the CSV file is as follows - header information as shown below is required in the file. A sample CSV file is included with the downloadable script:

ComputerName,MACAddress
pc1,00-16-da-2b-6f-b8

If the 'MACAddress' parameter is given, a regular expression is then used with parameter validation (ValidatePattern) to verify that it is a valid MAC address. The octets of the MAC address may be separated by dashes '-', colons ':' or nothing.

Coming on to the main body of the script you will notice that I use

Set-StrictMode -Version 2

This is a good practice which ensures that you don't get caught out by mis-typed variable names. I use this in all my scripts. For more information see this TechNet document.

The next significant operation is registering an event log source for the script in the Windows Application event log, if that hasn't already been done. This requires you to be an administrator, so it will be necessary to run the script once as an administrator if you will normally run it as a non-admin. If you don't do this, the script will continue without writing the result to the event log.

The next section is only executed if the 'ComputerName' parameter set is in operation: the MACLookup.csv file is read into a hash table, then this is queried to see whether the computer name specified by the parameter exists, and the corresponding MAC address is retrieved if so, and then validated by the same regular expression as before. If not, the script writes this fact to the event log and throws an error.

Finally, the 'Send-MagicPacket' function is called to send the Wake-on-LAN magic packet and the result is reported to standard output and the event log.

The Send-MagicPacket function is of course at the heart of the script functionality. It is based on a great post by The PowerShell Guy that you can find here (thanks /\/\o\/\/). I tweaked it slightly because I thought it would be more flexible to be able to specify the octets of the MAC address separated by either dashes, colons or nothing. I also added some comment-based Help so that you can easily copy and paste this function into other scripts or a PowerShell module, to make use of it elsewhere. You will notice that you can use the PowerShell common parameter 'Debug' to troubleshoot creation and sending of the magic packet if necessary. See Jeffery Hicks (The Lonely Administrator)'s excellent post here for more information on how and why you might do that.

I hope this script is of use to you (or perhaps the techniques within it)  – please leave a comment to let me know if so.

Post to Twitter

Comments (11) Trackbacks (0)
  1. I humbly (that should be in all caps…) have a suggestion for extending this work. Add a function to wake a subnet by directly reading a MS DHCP server for the MACs, and use remoting to pass the packets through a known (and always awake) “proxy” computer on the requested subnet. Our campus network is such that we can’t pass WoL packets beyond the local subnet. (3rd party plugins to SCCM to perform this are about $5/PC in quantity…) Thank you for sharing your work with the community.

    • Thanks for your comment Joe. That would be a nice enhancement! Although it would be a fun project, unfortunately I don’t have time to do that at the moment – but have you thought about posting it on Freelancer.com? At $5/PC for an SCCM plugin, that could work out a lot cheaper if you have a lot of machines!

  2. The idea from Joe is a very aspiring adea but beyond my knowledge. If you do manage to getting around to adding the funtion to send WOL packets across vlans i would be in debted to you. By the way, the script you created is a very nice piece of work.

  3. What a nice and neatly written script! Could one ask for an option to use a file as argument? This file is of course formatted the same as MACLookup.csv, it is however not necessarily the same file (e.g., somefile.csv could be a subset of MACLookup.csv).

    • Thanks for your comment Michael. It’s been some time since you posted it – can you let me know if you still need the ability to specify the file as a parameter? If so I will add it.

  4. In teh interest of Full Disclosure, I am a Powershell N00B !!

    This is an excellent use of PS – we have a web-based WoL system which is a pain to use, far faster to open a DOS box and type “wake ” and have the parameters parsed to your script.

  5. Nigel,

    I’d love to see the file parameter added to this code!

  6. This script is great, but it looks like I dont’ know how to use it. So I edited the csv file with computer names mapping to their corresponding MAC. I run the script and it looks like the magic pocket was sent, but PCs now waky waky. Anything I might bee missing besides PC set to wake up?

  7. Thanks, we were looking at PS Exec with a wake on lan utility, but PowerShell is a nice way to do it!

  8. This a very well written script. I’ve been messing around for a week or so to create a good WOL PS script but I didn’t have any luck. I decided to check the web for a script and found dozens that don’t work. Thank you for sharing your great work!


Leave a comment

No trackbacks yet.

Switch to our mobile site