Functions/GenXdev.Windows/Send-WakeOnLan.ps1

<##############################################################################
Part of PowerShell module : GenXdev.Windows
Original cmdlet filename : Send-WakeOnLan.ps1
Original author : René Vaessen / GenXdev
Version : 3.25.2026
################################################################################
Copyright (c) René Vaessen / GenXdev
 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
 
    http://www.apache.org/licenses/LICENSE-2.0
 
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
################################################################################>

function Send-WakeOnLan {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]$MacAddress,

        [string]$BroadcastAddress = "255.255.255.255",
        
        [int]$Port = 9
    )

    process {
        # Clean up the MAC address formatting (remove colons, dashes, and spaces)
        $cleanMac = $MacAddress -replace '[^0-9a-fA-F]'
        
        if ($cleanMac.Length -ne 12) {
            Microsoft.PowerShell.Utility\Write-Error "Invalid MAC address length. Must be 12 hexadecimal characters."
            return
        }

        # Convert the MAC address into a byte array
        $macBytes = for ($i = 0; $i -lt 12; $i += 2) {
            [Convert]::ToByte($cleanMac.Substring($i, 2), 16)
        }

        # Construct the Magic Packet: 6 bytes of 0xFF + (MAC address * 16)
        $packet = [byte[]](,0xFF * 6)
        0..15 | Microsoft.PowerShell.Core\ForEach-Object { $packet += $macBytes }

        # Send the UDP broadcast
        try {
            $udpClient = [System.Net.Sockets.UdpClient]::new()
            $udpClient.Connect($BroadcastAddress, $Port)
            [void]$udpClient.Send($packet, $packet.Length)
            Microsoft.PowerShell.Utility\Write-Host "Magic packet successfully sent to $MacAddress" -ForegroundColor Green
        }
        catch {
            Microsoft.PowerShell.Utility\Write-Error "Failed to send WoL packet: $_"
        }
        finally {
            if ($udpClient) { $udpClient.Close() }
        }
    }
}