Search code examples
windowspowershellbatch-file

Powershell toggle bluetooth with a click


I made up my research and I got this on another question here.

I'm using this powershell command to toggle Bluetooth:

Bluetooth.ps1

[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

It works but It's not want I liked to do. I keep on my research and found this file that checks Bluetooth status and then toggles it.

toggleBluetooth.bat

@echo off
FOR /F "skip=2 tokens=2,*" %%A IN ('reg.exe query "HKLM\SYSTEM\CurrentControlSet\Services\bthserv\Parameters\BluetoothControlPanelTasks" /v "state"') DO set "VAR=%%B"

if %VAR%==0x1 (goto ON)

Powershell.exe -executionpolicy Bypass -windowstyle hidden -File ".\Bluetooth.ps1" -BluetoothStatus On
goto end

:ON
Powershell.exe -executionpolicy Bypass -windowstyle hidden -File ".\Bluetooth.ps1" -BluetoothStatus Off

:end

I created a shortcut and use it on my desktop. Is it any way I can pin it to windows 10 taskbar nor other way of doing all that in the ps1 file?


Solution

  • you cant pin .bat files to the taskbar directly but you can pin .exe files(like cmd.exe itself) so just: right click -> New -> Shortcut -> paste the following code:

    cmd /c start /min cmd /c cd /d "c:\example path\"^& call bluetooth.bat
    

    then just drag the newly created shortcut to the taskbar,change the icon etc..