Modifique um PowerShell que recebe o argumento On/off para iniciar/parar o serviço para um script que verifica se o serviço está ativado (ou desativado) e o interrompe (ou inicia)

Modifique um PowerShell que recebe o argumento On/off para iniciar/parar o serviço para um script que verifica se o serviço está ativado (ou desativado) e o interrompe (ou inicia)

Eu tenho esse código deaqui, que inicia ou interrompe o serviço bluetooth com base no argumento que recebe.

bluetooth.ps1 -BluetoothStatus On

ou

bluetooth.ps1 -BluetoothStatus Off

Gostaria de modificá-lo para poder chamá-lo sem argumentos com uma simples ligação de tecla ahk:

#b::
Run, C:\Users\user\Desktop\bluetooth.ps1 
return 

Então o script deve "por si só" verificar se o bluetooth está ligado ou desligado e fazer o que for necessário para mudar o estado: se estiver ligado, deve pará-lo; se estiver desligado, deve iniciá-lo.

[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

Responder1

A mágica está nas últimas linhas de código:

$bluetooth = $radios | ? { $_.Kind -eq 'Bluetooth' }
[Windows.Devices.Radios.RadioState,Windows.System.Devices,ContentType=WindowsRuntime]
Await ($bluetooth.SetStateAsync($BluetoothStatus)) ([Windows.Devices.Radios.RadioAccessStatus])

A variável $bluetooth contém o estado atual do rádio bluetooth:

PS C:\> $bluetooth

     Kind Name      State
     ---- ----      -----
Bluetooth Bluetooth    On

Portanto, antes da última linha onde chamamos Await novamente e passamos o parâmetro $BluetoothStatus, que está definido como 'Off' ou 'On', podemos usar uma condicional para o valor.

if ($bluetooth.state -eq 'On') {$BluetoothStatus = 'Off'} else {$BluetoothStatus = 'On'}

Agora podemos remover a linha do parâmetro:

[Parameter(Mandatory=$true)][ValidateSet('Off', 'On')][string]$BluetoothStatus

E toda vez que chamamos o script ele deve reverter o estado atual.

Responder2

Aqui está o melhor dos dois mundos.

  • Para ativar/desativar chamadapowershell -Command bluetooth.ps1
  • Para ativar explicitamente a chamadapowershell -Command bluetooth.ps1 -BluetoothStatus On
  • Para desligar explicitamente a chamadapowershell -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

informação relacionada