Skip to content

Instantly share code, notes, and snippets.

@u01jmg3
Created May 17, 2020 09:52
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save u01jmg3/0305dee156158f5c987056c4ff0df94e to your computer and use it in GitHub Desktop.
Save u01jmg3/0305dee156158f5c987056c4ff0df94e to your computer and use it in GitHub Desktop.
Windows Powershell Script to Toggle Bluetooth On or 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
@u01jmg3
Copy link
Author

u01jmg3 commented May 17, 2020

powershell -Command C:\My` Scripts\bluetooth.ps1

powershell -Command C:\My` Scripts\bluetooth.ps1 -BluetoothStatus On
powershell -Command C:\My` Scripts\bluetooth.ps1 -BluetoothStatus Off

@DamagedDingo
Copy link

Works perfectly.
Thanks!

@FyeCobain
Copy link

Great. Thanks! 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment