<#
.SYNOPSIS
Powershell script to send wake command to computer on the network.
Needs MAC address to send the command
.PARAMETER macAddress
Address of the server: eg: 1A:2B:3C:4D:5E:6F
.EXAMPLE
WakeOnLan -macAddress "1A:2B:3C:4D:5E:6F"
.NOTES
# References:
# https://www.pdq.com/blog/wake-on-lan-wol-magic-packet-powershell/
# https://stackoverflow.com/a/72853503/18169
#>
param
(
[parameter(Mandatory=$true)]
[string]$macAddress
)
function sendWakeCommandWithUdpClient
{
[byte[]]$MacByteArray = $macAddress -split "[:-]" | ForEach-Object { [Byte] "0x$_"}
[Byte[]] $MagicPacket = (,0xFF * 6) + ($MacByteArray * 16)
$UdpClient = New-Object System.Net.Sockets.UdpClient
$UdpClient.Connect(([System.Net.IPAddress]::Broadcast),7)
#returns the number of bytes sent
$UdpClient.Send($MagicPacket,$MagicPacket.Length) | Out-Null
$UdpClient.Close()
}
function sendWakeCommandWithEndPoint
{
$mac = $macAddress;
[System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() | Where-Object { $_.NetworkInterfaceType -ne [System.Net.NetworkInformation.NetworkInterfaceType]::Loopback -and $_.OperationalStatus -eq [System.Net.NetworkInformation.OperationalStatus]::Up } | ForEach-Object {
$networkInterface = $_
$localIpAddress = ($networkInterface.GetIPProperties().UnicastAddresses | Where-Object { $_.Address.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork })[0].Address
$targetPhysicalAddress = [System.Net.NetworkInformation.PhysicalAddress]::Parse(($mac.ToUpper() -replace '[^0-9A-F]',''))
$targetPhysicalAddressBytes = $targetPhysicalAddress.GetAddressBytes()
$packet = [byte[]](,0xFF * 102)
6..101 | Foreach-Object { $packet[$_] = $targetPhysicalAddressBytes[($_ % 6)] }
$localEndpoint = [System.Net.IPEndPoint]::new($localIpAddress, 0)
$targetEndpoint = [System.Net.IPEndPoint]::new([System.Net.IPAddress]::Broadcast, 9)
$client = [System.Net.Sockets.UdpClient]::new($localEndpoint)
try { $client.Send($packet, $packet.Length, $targetEndpoint) | Out-Null } finally { $client.Dispose() }
}
}
# Method 1
sendWakeCommandWithUdpClient
# Method 2
sendWakeCommandWithEndPoint