Mag*_*Tun 2 powershell bluetooth windows-10
我从这里得到了这段代码,它根据收到的参数启动或停止蓝牙服务。
bluetooth.ps1 -BluetoothStatus On
Run Code Online (Sandbox Code Playgroud)
或者
bluetooth.ps1 -BluetoothStatus Off
Run Code Online (Sandbox Code Playgroud)
我想修改它,以便我可以使用简单的 ahk 键绑定在不带参数的情况下调用它:
#b::
Run, C:\Users\user\Desktop\bluetooth.ps1
return
Run Code Online (Sandbox Code Playgroud)
然后,脚本应该“自行”检查蓝牙是否打开或关闭,并执行必要的操作来更改状态:如果打开,则应停止蓝牙;如果打开,则应停止蓝牙。如果关闭它应该启动它。
[CmdletBinding()] Param (
[Parameter(Mandatory=$true)][ValidateSet('Off', 'On')][string]$BluetoothStatus
)
If ((Get-Service bthserv).Status -eq 'Stopped') { Start-Service bthserv }
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
}
[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]])
$bluetooth = $radios | ? { $_.Kind -eq 'Bluetooth' }
[Windows.Devices.Radios.RadioState,Windows.System.Devices,ContentType=WindowsRuntime] | Out-Null
Await ($bluetooth.SetStateAsync($BluetoothStatus)) ([Windows.Devices.Radios.RadioAccessStatus]) | Out-Null
Run Code Online (Sandbox Code Playgroud)
小智 5
神奇之处在于最后几行代码:
$bluetooth = $radios | ? { $_.Kind -eq 'Bluetooth' }
[Windows.Devices.Radios.RadioState,Windows.System.Devices,ContentType=WindowsRuntime]
Await ($bluetooth.SetStateAsync($BluetoothStatus)) ([Windows.Devices.Radios.RadioAccessStatus])
Run Code Online (Sandbox Code Playgroud)
变量 $bluetooth 保存蓝牙无线电的当前状态:
PS C:\> $bluetooth
Kind Name State
---- ---- -----
Bluetooth Bluetooth On
Run Code Online (Sandbox Code Playgroud)
因此,在我们再次调用 Await 并传入参数 $BluetoothStatus(该参数设置为“Off”或“On”)之前,我们可以对该值使用条件。
if ($bluetooth.state -eq 'On') {$BluetoothStatus = 'Off'} else {$BluetoothStatus = 'On'}
Run Code Online (Sandbox Code Playgroud)
现在我们可以删除参数行:
[Parameter(Mandatory=$true)][ValidateSet('Off', 'On')][string]$BluetoothStatus
Run Code Online (Sandbox Code Playgroud)
每次我们调用脚本时,它都应该反转当前状态。
归档时间: |
|
查看次数: |
1584 次 |
最近记录: |