如何在 Windows 上使用 PowerShell 脚本连接和断开蓝牙设备?

All*_*497 7 windows powershell bluetooth

我有一台非常慢且相对便宜的计算机。当我打开它时,我打开了我的蓝牙鼠标。鼠标正常工作几秒钟,然后连接断开。如果我然后重新连接鼠标,它会正常工作,直到我再次将其关闭。

我的目标是:我想编写一个 PowerShell 脚本来自动重新连接鼠标,但我不知道它在 PowerShell 中如何与蓝牙配合使用。有人可以帮我吗?

Ber*_*ops 11

尝试这样的事情,请注意需要提升权限:

$device = Get-PnpDevice | Where-Object {$_.Class -eq "Bluetooth" -and $_.FriendlyName -eq "FriendlyDeviceName"}
Disable-PnpDevice -InstanceId $device.InstanceId -Confirm:$false
Start-Sleep -Seconds 10
Enable-PnpDevice -InstanceId $device.InstanceId -Confirm:$false
Run Code Online (Sandbox Code Playgroud)

此脚本禁用设备并在 10 秒后再次启用它。


小智 5

尝试这个 Powershell 脚本,它会禁用蓝牙外围设备并取消配对()。非常感谢xzion14!

$Source = @"
   [DllImport("BluetoothAPIs.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
   [return: MarshalAs(UnmanagedType.U4)]
   static extern UInt32 BluetoothRemoveDevice(IntPtr pAddress);
   public static UInt32 Unpair(UInt64 BTAddress) {
      GCHandle pinnedAddr = GCHandle.Alloc(BTAddress, GCHandleType.Pinned);
      IntPtr pAddress     = pinnedAddr.AddrOfPinnedObject();
      UInt32 result       = BluetoothRemoveDevice(pAddress);
      pinnedAddr.Free();
      return result;
   }
"@
Function Get-BTDevice {
    Get-PnpDevice -class Bluetooth |
      ?{$_.HardwareID -match 'DEV_'} |
         select Status, Class, FriendlyName, HardwareID,
            # Extract device address from HardwareID
            @{N='Address';E={[uInt64]('0x{0}' -f $_.HardwareID[0].Substring(12))}}
}
################## Execution Begins Here ################
$BTDevices = @(Get-BTDevice) # Force array if null or single item
$BTR = Add-Type -MemberDefinition $Source -Name "BTRemover"  -Namespace "BStuff" -PassThru
Do {
   If ($BTDevices.Count) {
      "`n******** Bluetooth Devices ********`n" | Write-Host
      For ($i=0; $i -lt $BTDevices.Count; $i++) {
         ('{0,5} - {1}' -f ($i+1), $BTDevices[$i].FriendlyName) | Write-Host
      }
      $selected = Read-Host "`nSelect a device to remove (0 to Exit)"
      If ([int]$selected -in 1..$BTDevices.Count) {
         'Removing device: {0}' -f $BTDevices[$Selected-1].FriendlyName | Write-Host
         $Result = $BTR::Unpair($BTDevices[$Selected-1].Address)
         If (!$Result) {"Device removed successfully." | Write-Host}
         Else {"Sorry, an error occured." | Write-Host}
      }
   }
   Else {
      "`n********* No devices foundd ********" | Write-Host
   }
} While (($BTDevices = @(Get-BTDevice)) -and [int]$selected)
Run Code Online (Sandbox Code Playgroud)