如何在Windows Powerhell中连接和删除蓝牙

时间:2018-12-06 00:07:49

标签: powershell bluetooth

所以我有一台速度非常慢且相对便宜的计算机,每当打开它时,我都会打开蓝牙鼠标,并且它可以正常工作几秒钟,然后它会断开连接,因此我必须断开连接然后重新连接它,它将正常工作,直到我再次将其关闭。我有一个程序可以将.ps1文件转换为.exe文件,我想制作一个程序为我做,但是我不知道如何在Powershell中使用蓝牙。有人有主意吗?

2 个答案:

答案 0 :(得分:0)

尝试类似的方法,请注意,需要提升的权限:

$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

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

答案 1 :(得分:0)

尝试使用此Powershell脚本,它将禁用和取消配对蓝牙外围设备 (source)。 非常感谢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)