Pairing Bluetooth devices using PowerShell for Fun and Profit
Feb 02, 2022
I switch between work and personal laptops nearly every day. But my wireless keyboard doesn't support multiple devices. So every time I switch devices, I need to un-pair then re-pair the keyboard to the new device. Otherwise, it just doesn't connect.
On Windows, this re-pairing process takes ~10 mouse clicks, or roughly 30 seconds. After months of doing this nearly every day, it’s become a bit tiresome... so I decided to automate it.
Pairing Bluetooth devices via the terminal
With some help from Google and Stackoverflow, I found a Windows tool called Bluetooth Command Line Tools. It lets you discover, pair, and connect Bluetooth devices using terminal commands.
After installing it, you can search for nearby Bluetooth devices (their names and Mac addresses) by running the btdiscovery
command in Command Prompt or PowerShell. The command takes several seconds to run so don't panic if it's slow.
Scripting in PowerShell
Then I created a little PowerShell script called keyboard.ps1
:
# Replace this device name with your own device's name
$DeviceName = "Magic Keyboard with Numeric Keypad"
"Unpairing device: $DeviceName"
btpair -u -n $DeviceName
"Pairing device: $DeviceName"
"Note: you may need to click on a Windows prompt and accept the PIN"
btpair -p -n $DeviceName
Copy your device's name from the btdiscovery
output and put it in the $DeviceName
variable.
Save the script to your desktop.
Right click the file > Run with PowerShell
to run it:
BTW: you could do the exact same thing by using the btpair
commands in a Batch script. I just wanted to learn a bit of PowerShell.
Pairing by MAC address instead of device name
If you (or others nearby) have devices that share the same name, you can avoid conflicts by using the device's MAC address instead.
In the script, replace the "-n"
flag with a "-b"
flag, followed by the device's MAC address.
However, your mileage may vary: the commands didn't work for me when I used a MAC address. I’m not sure why.
It's not perfect
Now I just run this script whenever I switch devices. It's not perfect: the script takes 5 to 10 seconds to run, and I have to do a couple clicks to confirm Windows 10's Bluetooth PIN prompt before pairing. Heck, there’s probably an open source equivalent of Logitech Flow for smoothly transitioning between devices.
But by going this route, I got to learn some basic PowerShell and can now feel an iota of pride every time I run the script and sit there for 10 seconds, watching it run :)