-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathInvoke-WakeOnLan.ps1
69 lines (60 loc) · 1.83 KB
/
Invoke-WakeOnLan.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
function Invoke-WakeOnLan
{
param
(
# one or more MACAddresses
[Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
# mac address must be a following this regex pattern:
[ValidatePattern('^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$')]
[string[]]
$MacAddress
)
begin
{
# instantiate a UDP client:
$UDPclient = [System.Net.Sockets.UdpClient]::new()
}
process
{
foreach($_ in $MacAddress)
{
try {
$currentMacAddress = $_
# get byte array from mac address:
$mac = $currentMacAddress -split '[:-]' |
# convert the hex number into byte:
ForEach-Object {
[System.Convert]::ToByte($_, 16)
}
#region compose the "magic packet"
# create a byte array with 102 bytes initialized to 255 each:
$packet = [byte[]](,0xFF * 102)
# leave the first 6 bytes untouched, and
# repeat the target mac address bytes in bytes 7 through 102:
6..101 | Foreach-Object {
# $_ is indexing in the byte array,
# $_ % 6 produces repeating indices between 0 and 5
# (modulo operator)
$packet[$_] = $mac[($_ % 6)]
}
#endregion
# connect to port 400 on broadcast address:
$UDPclient.Connect(([System.Net.IPAddress]::Broadcast),4000)
# send the magic packet to the broadcast address:
$null = $UDPclient.Send($packet, $packet.Length)
Write-Verbose "sent magic packet to $currentMacAddress..."
}
catch
{
Write-Warning "Unable to send ${mac}: $_"
}
}
}
end
{
# release the UDF client and free its memory:
$UDPclient.Close()
$UDPclient.Dispose()
}
}
Invoke-WakeOnLan -MacAddress 30-85-A9-EC-2A-85 -Verbose