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

我有一台非常慢、相对便宜的电脑,当我打开它时,我打开了我的蓝牙鼠标,鼠标工作正常几秒钟,然后连接断开,如果我然后重新连接鼠标,它就像它应该的那样工作,直到我再次关闭它。

我有一台非常慢、相对便宜的电脑,当我打开它时,我打开了我的蓝牙鼠标,鼠标工作正常几秒钟,然后连接断开,如果我然后重新连接鼠标,它就像它应该的那样工作,直到我再次关闭它。

我的目标是:我想写一个 PowerShell 脚本,将自动重新连接鼠标,但我不知道它是如何与蓝牙在 PowerShell 中。

15

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

$device = Get-PnpDevice -class Bluetooth -friendlyname "FriendlyDeviceName"
Disable-PnpDevice -InstanceId $device.InstanceId -Confirm:$false
Start-Sleep -Seconds 10
Enable-PnpDevice -InstanceId $device.InstanceId -Confirm:$false

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

1

试试这个 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)

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(419)
PHP将数组中的项目与同一行中的另一个普通项目相加
上一篇
雪花-如何在其名称中引用具有特殊字符的指定表的内部阶段(list of stage names)
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(85条)