30

Is there a way, through powershell, or any other tools to connect and disconnect a paired Bluetooth device? Basically press the Connect/Disconnect button in Bluetooth & other devices, except from command line of whatever sort (Powershell, bat using some command line tools, code in C#, C++, etc.):

Bluetooth & other devices

I found this answer but it involves unpairing and pairing again, which won't work because my headphones need to be in pairing mode to accept new pairing. I'd rather not simulate keypresses and mouse clicks via AutoIt or some other software like that.

2
  • 6
    LOL, my exact problem. The sony headset handling multi device usecase too poorly and windows having cluncy interface for connect/disconnect.
    – user232548
    May 13, 2020 at 9:59
  • The most reliable and fast solution for me was to use AutoHotkey script from this topic. Particularly, from this answer. Feb 17, 2023 at 8:10

9 Answers 9

29

I wrote C++ code to do it using Win32 Bluetooth API's BluetoothSetServiceState, but it's actually enough to use Bluetooth Command Line Tools.

As it turns out, once all services in use by a device get disabled, device gets released and disconnected by Windows automatically. In my case these are voice and music, as per the screenshot, and most headphones will work the same way.
Voice is actually the hands free service (HFP) and music is just an audio sink (A2DP). Service identifiers will be necessary and they can be discovered through the usage of btdiscovery command from the package above, or via the list of Bluetooth services. HFP voice is 111e, A2DP music is 110b.

Per btcom command line help:

Usage:

btcom {-c|-r} {-bBluetoothAddress | -nFriendlyName} [-s{sp|dun|GUID|UUID}]

 -c  Create association between COM port and a remote service (Enable non-COM service).
 -r  Remove association between COM port and a remote service (Disable non-COM service).
 -s  Remote service to use (Default is Serial Port Service)
 -b  Bluetooth address of remote device in (XX:XX:XX:XX:XX:XX) format. 
 -n  Friendly name of remote device.

To disconnect the device, issue the following (only works when run as administrator in my case, using Windows 10 1809 (17763.437)):

"C:\Program Files (x86)\Bluetooth Command Line Tools\bin\btcom" -n "WH-1000XM3" -r -s111e
"C:\Program Files (x86)\Bluetooth Command Line Tools\bin\btcom" -n "WH-1000XM3" -r -s110b

To connect again, issue the same with -c instead of -r. This works for other devices, not just headphones, as long as all services/profiles connected to by Windows get disabled/enabled.

Note: using -n <friendly name> is much slower than using -b <address> due to performing Bluetooth discovery.

10
10

win 10 shortcuts https://www.windowscentral.com/best-windows-10-keyboard-shortcuts

win-key + K opens the sidebar menu and instantly searches for bluetooth devices. then click on your already paired device and connect.

2
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
    – Mureinik
    Dec 23, 2021 at 15:23
  • Wow...I really never new about that shortcut....I was about script or code something to do the reconnecting for me...lol..
    – Mesh
    Aug 8, 2022 at 8:29
7

In case the solution from @MarcinJ with Bluetooth Command Line Tools is too slow for you, especially in case you want to pair the device meanwhile an incoming call try creating a windows shortcut:
(Right click > New > Shortcut)

%windir%\explorer.exe ms-settings-connectabledevices:devicediscovery

It will pop up a display and audio panel right on the screen, which is one click away from connect.
And nice BT icon for the shortcut can be found for example on C:\Windows\System32\fsquirt.exe.

2
  • 4
    For Win11, this and Win-K only bring up the "Cast Display" side-menu, unfortunately, no longer does this include bluetooth devices. Instead explorer.exe ms-settings:bluetooth brings up the correct bluetooth-connection window.
    – r2evans
    May 5, 2022 at 13:35
  • THis is in no way faster. It' slower than the slowest you can do the btcom script which is by searching by friendly name because it still has to perform the bluetooth discovery.
    – Swish
    Oct 20, 2022 at 11:24
4

Maybe Get-PnPDevice, Disable-PnPDevice and Enable-PnPDevice will do the trick for you. I havent been able to test it out though.

Example:

$DeviceName = "YourDevice"
$BTDevice =  Get-PnpDevice | Where-Object {$_.FriendlyName -eq $DeviceName -and $_.class -eq "Bluetooth"} 

Disable-PnpDevice -InstanceId $BTDevice.DeviceID -Confirm:$false

Enable-PnpDevice -InstanceId $BTDevice.DeviceID -Confirm:$false

Change the $DeviceName variable to the name of your BT device.

Get-PnPDevice Enable-PnPDevice Disable-PnPDevice

4
  • It doesn't, I've stumbled upon Disable-PnPDevice myself too. Depending on what gets disabled (as there are multiple devices, depending on BT profiles), either nothing happens, bt stack crashes or audio output gets disabled but the device stays connected.
    – MarcinJ
    Apr 19, 2019 at 20:56
  • 2
    Solved it, in case you're interested.
    – MarcinJ
    Apr 19, 2019 at 22:49
  • coolness. Glad you worked it out. I was still digging at this myself. I don't much mess with device in this manner. So, interesting little digging event.
    – postanote
    Apr 19, 2019 at 23:14
  • I have managed to make this answer work for me, please check my answer
    – PolarBear
    Mar 19, 2022 at 16:01
2

Using inspiration from https://github.com/stanleyguevara/win10-bluetooth-headphones I've revised that script so I can connect/disconnect multiple devices from a single shortcut click (or a keyboard shortcut bound to the shortcu.

disconnect shortcut properties dialog

My fork is here: https://github.com/nickboldt/win10-bluetooth-headphones

2

The AutoHotkey script brought up by Pavel is most inspiring, yet compilation requires AutoHotkey. I ported the code to powershell, lest the code requires AutoHotkey:

Param(
                [Parameter(Mandatory=$False,Position=1)]
                [string]$dnp
)

if($dnp -eq "/?") {
        Write-Host "usage: $($MyInvocation.InvocationName) [device name]"
        exit
}

if(!$dnp) {
    $dnp="WH-1000XM4"
}

$devices = Get-ChildItem -Path HKLM:\SYSTEM\ControlSet001\Services\BTHPORT\Parameters\Devices
foreach($device in $devices) {
    $address=$device.pschildname.ToUpper()
    $name=$device.GetValue("Name")
    if($name -ne $null) {
        $printableName = ($name -notmatch 0 | ForEach{[char]$_}) -join ""
        if($printableName -eq $dnp) {
            $ma=$address
        }
    }
}

$gui="1"
if(!$ma) {
    Write-Host "Device $dnp not found.`r`nStop."
    if($gui -eq "1") {[System.Windows.Forms.MessageBox]::Show("Device $dnp not found.","Error")}
    exit
}

Write-Verbose "Working with the device $dnp and with the address $ma."

$id=get-random
Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential)]
public struct BLUETOOTH_DEVICE_INFO$id {
    public UInt32 dwSize;
    public UInt64 Address;
    public UInt64 ulClassofDevice;
    public bool fConnected;
    public bool fRemembered;
    public bool fAuthenticated;
    public decimal stLastSeen; //decimal is just as long as SystemTime
    public decimal stLastUsed; //decimal is just as long as SystemTime
    public string szName;
}

namespace bluco {
    public class Program$id {
        [DllImport("bthprops.cpl", CharSet = CharSet.Auto, SetLastError = true)]
        static extern uint BluetoothSetServiceState(IntPtr hRadio, ref BLUETOOTH_DEVICE_INFO$id DeviceInfo, ref Guid guid, int ServiceFlags);

        public static void Main() {
            BLUETOOTH_DEVICE_INFO$id mdi = new BLUETOOTH_DEVICE_INFO$id {
                // a 0x424, 1060 error is produced if the below address is wrong, that number seems to indicate ERROR_SERVICE_DOES_NOT_EXIST
                Address = Convert.ToUInt64("$ma", 16),
                szName = "WH-1000XM5",
                // 72 is the size ofBLUETOOTH_DEVICE_INFO$id without the string szName
                // according to the specification, the string szName has at most 248 wchars
                dwSize = (uint) (72 + 4*248)
            };

            Guid mUUID = new Guid("0000111e-0000-1000-8000-00805f9b34fb"); // https://www.bluetooth.com/specifications/assigned-numbers/service-discovery/
            uint hr0 = BluetoothSetServiceState(IntPtr.Zero, ref mdi, ref mUUID, 1);
            mUUID = new Guid("0000110b-0000-1000-8000-00805f9b34fb"); // https://www.bluetooth.com/specifications/assigned-numbers/service-discovery/
            uint hr1 = BluetoothSetServiceState(IntPtr.Zero, ref mdi, ref mUUID, 1);
            if(hr0 == 0 && hr1 == 0) {
                Console.WriteLine("Bluetooth connect.");
                #pragma warning disable 162
                if("$gui"=="1") System.Windows.Forms.MessageBox.Show("Bluetooth connect.","Connect");
                #pragma warning restore 162
            }
            if(hr0 != 0 || hr1 != 0) {
                mUUID = new Guid("0000111e-0000-1000-8000-00805f9b34fb");
                hr0 = BluetoothSetServiceState(IntPtr.Zero, ref mdi, ref mUUID, 0);
                // a 0x424, 1060 error is produced if the below address is wrong, that number seems to indicate ERROR_SERVICE_DOES_NOT_EXIST
                mUUID = new Guid("0000110b-0000-1000-8000-00805f9b34fb");
                hr1 = BluetoothSetServiceState(IntPtr.Zero, ref mdi, ref mUUID, 0);
                if(hr0 == 0 && hr1 == 0) {
                    Console.WriteLine("Bluetooth disconnect.");
                    #pragma warning disable 162
                    if("$gui"=="1") System.Windows.Forms.MessageBox.Show("Bluetooth disconnect.","Disconnect");
                    #pragma warning restore 162
                }
            }
        }
    }
}
"@ -Language CSharp -ReferencedAssemblies System.Windows.Forms

iex "[bluco.Program$id]::Main()"

My Bluetooth headset can now be switched on and off from the command line using powershell.

2
  • Code without explanation is useless.
    – Toto
    Nov 4, 2023 at 19:22
  • 2
    What kind of explanation are you after? My code uses the BluetoothSetServiceState function of the library bthprops.cpl. The AutoHotkey script that is available at github.com/a5sd45a4sd/bluco/blob/main/bluco.ahk uses the same function and the same library, yet it depends on AutoHotkey. I obviate that dependency by porting the AutoHotkey code to powershell.
    – dzmanto
    Nov 6, 2023 at 21:38
1

https://github.com/m2jean/ToothTray is a project implementing connection/disconnection with bluetooth audio devices. From its README.md:

Instead of using Windows bluetooth API, Windows Core Audio API has to be used to connect bluetooth audio. Ultimately it is the driver that connect the bluetooth device to Windows' audio system, and we need to get an interface to the bluetooth audio driver.

After bluetooth audio devices are paired and the drivers are installed, they will appear in Windows as audio endpoint devices, which can be enumerated with EnumAudioEndpoints. Each endpoint has various properties. Their avalibility depends on the type of the endpoint. We can enumerate the properties programmatically, or view them in the details tab of a device from Device Manager.

One useful property is the state of an endpoint, which tells us whether a bluetooth audio device is connected. If it is connected, the state will be DEVICE_STATE_ACTIVE. Otherwise, it will be DEVICE_STATE_UNPLUGGED.

After getting the endpoints, we need to use the device topology API to get an interface to the driver. In Windows Driver Model (WDM), drivers expose the hardware and their functionality with a graph of kernel streaming (KS) components. By navgating through the topology, we can find the KS components that actually controls the connection of a bluetooth audio device.

And it turns out the the KS component we are looking for is always a KS filter directed connected to an audio endpoint (which might have been specified by related WDM audio driver development documents). We can get the filter by getting the connector of the filter from the connector of the endpoint. Then we can use the IKsControl interface of the filter to send KSPROPSETID_BtAudio property request to the driver, which is simlar to IO requests. By sending either KSPROPERTY_ONESHOT_RECONNECT or KSPROPERTY_ONESHOT_DISCONNECT, we ask the driver to connect or disconnect from the bluetooth audio device.

Detailed implementation can be seen in its code.

I forked it and made its core functionalities into CLI version for script use: https://github.com/shunf4/ToothTrayCli

Note the above only applies to bluetooth audio devices.

0

Edited based on OP response.

Looking at the underlying class, that item is not exposed for programmatic access.

Bluetooth​Device.​Close Method

When will Close/Disconnect be implemented? [Windows.Devices.Bluetooth.BluetoothDevice]

When will Close/Disconnect be implemented? Are you planning to have a disconnect? Dispose() doesn't close the connection

849 opened on Jan 9, 2019

There does not appear to be another API doc to say otherwise. So, it looks like you are stuck with SendKeys, AutoIT, etc., at least for now.

2
  • What I meant by "baiscally press the connect/disconnect button" is perform the same thing Windows performs when that button is pressed, except from whatever code, e.g. PowerShell, bat, C#, C++, whatever. Turning off the whole BT radio won't work, there could be other devices connected, I just want to connect to or disconnect from a specific BT device (headphones).
    – MarcinJ
    Apr 19, 2019 at 7:09
  • Solved it, in case you're interested.
    – MarcinJ
    Apr 19, 2019 at 22:49
-1

I have tested the below vbs script successfully in Windows 10. Here I am simulating the keystrokes using the SendKeys command. The number of {TAB}s will be different on your system to reach the bluetooth device name.

Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "ms-settings:bluetooth"
WScript.Sleep 2500 
WshShell.SendKeys "{TAB}"
WshShell.SendKeys "{TAB}"
WshShell.SendKeys "{TAB}"
WshShell.SendKeys "{ENTER}"
WScript.Sleep 500 ' 
WshShell.SendKeys "{TAB}"
WScript.Sleep 500 ' 
WshShell.SendKeys "{ENTER}"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .