如何使用PowerShell发送网络唤醒魔包?

问题描述 投票:0回答:1

我想使用 PowerShell 发送 WOL 魔术包,而不依赖于任何第三方工具。

powershell wake-on-lan
1个回答
11
投票

这是正在运行的 PowerShell one-liner 我用来发送 WakeOnLan 数据包:

'01-23-45-67-89-AB' | Set-Variable 'mac'; [System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() | Where-Object { $_.NetworkInterfaceType -ne [System.Net.NetworkInformation.NetworkInterfaceType]::Loopback -and $_.OperationalStatus -eq [System.Net.NetworkInformation.OperationalStatus]::Up } | ForEach-Object { $targetPhysicalAddressBytes = [System.Net.NetworkInformation.PhysicalAddress]::Parse(($mac.ToUpper() -replace '[^0-9A-F]','')).GetAddressBytes(); $packet = [byte[]](,0xFF * 102); 6..101 | Foreach-Object { $packet[$_] = $targetPhysicalAddressBytes[($_ % 6)] }; $client = [System.Net.Sockets.UdpClient]::new([System.Net.IPEndPoint]::new(($_.GetIPProperties().UnicastAddresses | Where-Object { $_.Address.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork })[0].Address, 0)); try { $client.Send($packet, $packet.Length,[System.Net.IPEndPoint]::new([System.Net.IPAddress]::Broadcast, 9)) | Out-Null } finally { $client.Dispose() } }

这是一个更易读的版本: $mac = '01-23-45-67-89-AB'; [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() } }

支持所有常见的 
MAC 地址格式

,大小写无关,例如:

    0123456789aB
  • 01-23-45-67-89-aB
  • 01:23:45:67:89:aB
  • 0123.4567.89aB
  • 
    
  • 适用于
powershell.exe

(.NET Framework) 和

pwsh.exe
(.NET/.Net Core)。
大致基于 

使用 C# 在 LAN 上唤醒

的代码。

© www.soinside.com 2019 - 2024. All rights reserved.