博多南ウェブサービスのblog

博多南ウェブサービスのサービス紹介

Powershell 7.1 からWindows 10 のBluetooth ON/OFF できました

Powershell 7.1 からWindows 10 のBluetooth ON/OFF できました、の話。

結論

superuser.com にある回答を、以下のように編集。

[CmdletBinding()] Param (
    [Parameter(Mandatory=$true)][ValidateSet('Off', 'On')][string]$BluetoothStatus
)
If ((Get-Service bthserv).Status -eq 'Stopped') { Start-Service bthserv }
# Microsoft.Windows.SDK.NET.Ref を事前にインストールしとく
Add-Type -Path 'C:\Program Files\PackageManagement\NuGet\Packages\Microsoft.Windows.SDK.NET.Ref.10.0.19041.15\lib\Microsoft.Windows.SDK.NET.dll'
$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
}
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.AdditionalTypeData[[Collections.IEnumerable].TypeHandle] | ? { $_.Kind -eq 'Bluetooth' }
Await ($bluetooth.SetStateAsync($BluetoothStatus)) ([Windows.Devices.Radios.RadioAccessStatus]) | Out-Null

詳細

なぜうまくいくかはあまりわかりません。
ので、参考にしたWeb ページをどうぞ。