%20%D0%BB%D0%B8%20%D1%81%D0%BB%D1%83%D0%B6%D0%B1%D0%B0%2C%20%D0%B8%20%D0%BE%D1%81%D1%82%D0%B0%D0%BD%D0%B0%D0%B2%D0%BB%D0%B8%D0%B2%D0%B0%D0%B5%D1%82%20%D0%B5%D0%B5%20(%D0%B8%D0%BB%D0%B8%20%D0%B7%D0%B0%D0%BF%D1%83%D1%81%D0%BA%D0%B0%D0%B5%D1%82).png)
У меня есть этот код отздесь, которые запускают или останавливают службу Bluetooth в зависимости от полученного аргумента.
bluetooth.ps1 -BluetoothStatus On
или
bluetooth.ps1 -BluetoothStatus Off
Я хотел бы изменить его так, чтобы его можно было вызывать без аргументов с помощью простой привязки клавиши ahk:
#b::
Run, C:\Users\user\Desktop\bluetooth.ps1
return
Затем скрипт должен «сам по себе» проверить, включен или выключен Bluetooth, и сделать все необходимое для изменения состояния: если включен, он должен остановить его; если выключен, он должен запустить его.
[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
решение1
Вся магия кроется в последних нескольких строках кода:
$bluetooth = $radios | ? { $_.Kind -eq 'Bluetooth' }
[Windows.Devices.Radios.RadioState,Windows.System.Devices,ContentType=WindowsRuntime]
Await ($bluetooth.SetStateAsync($BluetoothStatus)) ([Windows.Devices.Radios.RadioAccessStatus])
Переменная $bluetooth хранит текущее состояние радиомодуля Bluetooth:
PS C:\> $bluetooth
Kind Name State
---- ---- -----
Bluetooth Bluetooth On
Поэтому перед последней строкой, где мы снова вызываем Await и передаем параметр $BluetoothStatus, который устанавливается в значение «Выкл.» или «Вкл.», мы можем использовать условное выражение для значения.
if ($bluetooth.state -eq 'On') {$BluetoothStatus = 'Off'} else {$BluetoothStatus = 'On'}
Теперь мы можем удалить строку параметров:
[Parameter(Mandatory=$true)][ValidateSet('Off', 'On')][string]$BluetoothStatus
И каждый раз, когда мы вызываем скрипт, он должен менять текущее состояние на противоположное.
решение2
Вот лучшее из обоих миров.
- Для включения/выключения вызова
powershell -Command bluetooth.ps1
- Чтобы включить явный вызов
powershell -Command bluetooth.ps1 -BluetoothStatus On
- Чтобы явно отключить вызов
powershell -Command bluetooth.ps1 -BluetoothStatus Off
[CmdletBinding()] Param (
[Parameter()][ValidateSet('On', 'Off')][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
if (!$BluetoothStatus) { if ($bluetooth.state -eq 'On') { $BluetoothStatus = 'Off' } else { $BluetoothStatus = 'On' } }
Await ($bluetooth.SetStateAsync($BluetoothStatus)) ([Windows.Devices.Radios.RadioAccessStatus]) | Out-Null