1 情境
这个只是讲述该代码的适用场景以及缘由,可跳过
一般关闭/打开wifi是通过netsh 禁用/打开网络适配器来实现的,但是通过这种方法,在netsh wlan show interface 后会呈现这个结果
Netsh WLAN show interfaces
There is 1 interface on the system:
Name : WiFi
State : disconnected
Radio status : Hardware On
Software Off
上述禁用适配器的方法会导致 hardware on/off 并不会 造成 software off/on,因此为了使得sotware 层面上的切换wifi,才有了下面的代码。
2 代码
[CmdletBinding()]
Param (
[Parameter(Mandatory=$true)][ValidateSet('Off', 'On')][string]$WlanStatus
)
# 确保 WLAN 服务正在运行
If ((Get-Service wlansvc).Status -eq 'Stopped') { Start-Service wlansvc }
# 加载 Windows Runtime 组件
Add-Type -AssemblyName System.Runtime.WindowsRuntime
$asTaskGeneric = ([System.WindowsRuntimeSystemExtensions].GetMethods() |
? { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' })[0]
Function Await($WinRtTask, $ResultType) {
$asTask = $asTaskGeneric.MakeGenericMethod($ResultType)
$netTask = $asTask.Invoke($null, @($WinRtTask))
$netTask.Wait(-1) | Out-Null
$netTask.Result
}
# 加载必要的 WinRT 类型
[Windows.Devices.Radios.Radio,Windows.System.Devices,ContentType=WindowsRuntime] | Out-Null
[Windows.Devices.Radios.RadioAccessStatus,Windows.System.Devices,ContentType=WindowsRuntime] | Out-Null
# 请求访问权限
Await ([Windows.Devices.Radios.Radio]::RequestAccessAsync()) ([Windows.Devices.Radios.RadioAccessStatus]) | Out-Null
# 获取所有无线电设备
$radios = Await ([Windows.Devices.Radios.Radio]::GetRadiosAsync()) ([System.Collections.Generic.IReadOnlyList[Windows.Devices.Radios.Radio]])
# 获取 WLAN 无线电
$wlan = $radios | ? { $_.Kind -eq 'Wifi' }
Await ($wlan.SetStateAsync($WlanStatus)) ([Windows.Devices.Radios.RadioAccessStatus]) | Out-Null
3 保存为test.ps1, 以管理员身份打开powershell,运行 powershell -ExecutionPolicy bypass -File "存放路径\test.ps1" -WlanStatus On/Off, 后面的On是打开wifi,Off是关闭wifi
4 解释
前三行建立脚本接受的参数。在正式开始之前,我们要确保wlansvc服务正在运行,如果没有就启动它。然后加载System.Runtime.WindowsRuntime程序集,这样就可以使用WindowsRuntimeSystemExtensions。 然后定义一个函数Await,我们将多次使用该函数从异步WinRT任务中获取适当类型的结果。在该函数声明之后,我们从WinRT元数据中加载两个必要的类型。 其余的就是使用Radio WinRT类来查找和配置wlan无线电。
5 关于
关于设置powershell为计划程序的内容可以参考别的博客,但是保存为ps1格式 以及调用代码:
powershell -ExecutionPolicy bypass -File "存放路径\test.ps1" -WlanStatus On/Off,是一样的