You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过PowerShell实现已取消配对蓝牙设备的重新连接

蓝牙配对功能实现方案

可通过你找到的BluetoothAuthenticateDeviceEx系统接口扩展原有脚本,实现通过MAC地址配对处于配对模式的蓝牙设备,完整修改后代码如下:

# 导入蓝牙API定义,新增配对相关接口
$Source = @"
using System;
using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential)]
public struct BLUETOOTH_ADDRESS {
    public UInt64 ullAddress;
}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct BLUETOOTH_DEVICE_INFO {
    public UInt32 dwSize;
    public BLUETOOTH_ADDRESS Address;
    public UInt32 ulClassofDevice;
    public UInt16 fConnected;
    public UInt16 fRemembered;
    public UInt16 fAuthenticated;
    public UInt32 stLastSeen;
    public UInt32 stLastUsed;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 248)]
    public string szName;
}

[DllImport("BluetoothAPIs.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
[return: MarshalAs(UnmanagedType.U4)]
static extern UInt32 BluetoothRemoveDevice(IntPtr pAddress);

[DllImport("BluetoothAPIs.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
[return: MarshalAs(UnmanagedType.U4)]
static extern UInt32 BluetoothAuthenticateDeviceEx(IntPtr hwndParent, IntPtr hRadio, IntPtr pbtbi, IntPtr pbtpin, UInt32 ulServiceMask);

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;
}

public static UInt32 Pair(UInt64 BTAddress) {
    BLUETOOTH_DEVICE_INFO bti = new BLUETOOTH_DEVICE_INFO();
    bti.dwSize = (UInt32)Marshal.SizeOf(typeof(BLUETOOTH_DEVICE_INFO));
    bti.Address.ullAddress = BTAddress;
    
    GCHandle pinnedBti = GCHandle.Alloc(bti, GCHandleType.Pinned);
    IntPtr pBti = pinnedBti.AddrOfPinnedObject();
    
    // 传空PIN则触发系统默认配对弹窗,若设备有固定PIN可在此处传入对应值
    UInt32 result = BluetoothAuthenticateDeviceEx(IntPtr.Zero, IntPtr.Zero, pBti, IntPtr.Zero, 0);
    pinnedBti.Free();
    return result;
}
"@

Function Get-BTDevice {
    Get-PnpDevice -class Bluetooth |
      ?{$_.HardwareID -match 'DEV_'} |
         select Status, Class, FriendlyName, HardwareID,
            @{N='Address';E={[uInt64]('0x{0}' -f $_.HardwareID[0].Substring(12))}}
}

Function Convert-MacToUInt64 {
    param([string]$MacAddress)
    $cleanMac = $MacAddress.Replace(':','').Replace('-','').Trim()
    return [UInt64]::Parse($cleanMac, [System.Globalization.NumberStyles]::HexNumber)
}

################## 执行逻辑开始 ################
$BTDevices = @(Get-BTDevice)
$BTOp = Add-Type -MemberDefinition $Source -Name "BTOperation"  -Namespace "BTools" -PassThru

Do {
    "`n******** 蓝牙设备操作菜单 ********`n" | Write-Host
    "1 - 查看已配对设备并取消配对" | Write-Host
    "2 - 通过MAC地址配对新设备" | Write-Host
    "0 - 退出" | Write-Host
    $selected = Read-Host "`n请选择操作项"
    
    Switch ([int]$selected) {
        1 {
            $BTDevices = @(Get-BTDevice)
            If ($BTDevices.Count) {
                "`n******** 已配对蓝牙设备 ********`n" | Write-Host
                For ($i=0; $i -lt $BTDevices.Count; $i++) {
                    ('{0,5} - {1}' -f ($i+1), $BTDevices[$i].FriendlyName) | Write-Host
                }
                $devSelected = Read-Host "`n选择要取消配对的设备 (0 返回上级菜单)"
                If ([int]$devSelected -in 1..$BTDevices.Count) {
                    '正在取消配对设备: {0}' -f $BTDevices[$devSelected-1].FriendlyName | Write-Host
                    $Result = $BTOp::Unpair($BTDevices[$devSelected-1].Address)
                    If (!$Result) {"设备取消配对成功。" | Write-Host}
                    Else {"操作出错,请重试。" | Write-Host}
                }
            }
            Else {
                "`n********* 未找到已配对蓝牙设备 ********" | Write-Host
            }
            Break
        }
        2 {
            $targetMac = Read-Host "`n请输入要配对的设备MAC地址(支持XX:XX:XX:XX:XX:XX或XX-XX-XX-XX-XX-XX格式)"
            try {
                $macUint = Convert-MacToUInt64 $targetMac
                "正在尝试配对设备,请等待系统配对提示..." | Write-Host
                $Result = $BTOp::Pair($macUint)
                If ($Result -eq 0) {"设备配对成功。" | Write-Host}
                Else {"配对失败,请确认设备处于配对模式且MAC地址正确。" | Write-Host}
            }
            catch {
                "MAC地址格式错误,请重新输入。" | Write-Host
            }
            Break
        }
        0 {
            "退出脚本。" | Write-Host
            Break
        }
        default {
            "输入无效,请重新选择。" | Write-Host
            Break
        }
    }
} While ([int]$selected -ne 0)

使用注意事项

  • 脚本需要以管理员权限运行
  • 配对操作前请确保目标蓝牙设备处于可发现/配对模式
  • 若设备有固定配对PIN码(如常见的0000、1234),可修改代码中BluetoothAuthenticateDeviceEx的PIN参数,跳过系统弹窗直接完成配对
  • 配对失败时优先检查MAC地址输入是否正确、设备是否远离其他蓝牙干扰源

内容的提问来源于stack exchange,提问作者alexxx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 09:54:04