一键切换蓝牙:如何将脚本固定到Win10任务栏或整合进PS1?
解决蓝牙一键切换的两个方案
一、将脚本固定到Windows 10任务栏
Windows 10默认不支持直接将.ps1或.bat文件固定到任务栏,需通过快捷方式中转实现:
- 右键桌面空白处 → 新建 → 快捷方式
- 根据使用的脚本类型填写目标:
- 如果用整合后的PowerShell脚本:
(替换成你实际的脚本存放路径)powershell.exe -ExecutionPolicy Bypass -WindowStyle Hidden -File "D:\Scripts\toggleBluetooth.ps1" - 如果继续用原来的
.bat脚本:cmd.exe /c "D:\Scripts\toggleBluetooth.bat"
- 如果用整合后的PowerShell脚本:
- 给快捷方式命名(比如「蓝牙一键切换」),点击完成
- 右键快捷方式 → 属性 → 更改图标 → 点击「浏览」,输入
%SystemRoot%\system32\shell32.dll,选择蓝牙相关图标(比如第139号),确定 - 右键该快捷方式,选择「固定到任务栏」即可
二、整合为单个PowerShell脚本实现一键切换
无需依赖.bat脚本,直接修改原Bluetooth.ps1,让它自动检测当前蓝牙状态并切换:
[CmdletBinding()] Param ( # 可选参数,不填则自动切换状态 [ValidateSet('Off', 'On')][string]$BluetoothStatus ) # 确保蓝牙服务已启动 If ((Get-Service bthserv).Status -eq 'Stopped') { Start-Service bthserv } Add-Type -AssemblyName System.Runtime.WindowsRuntime $asTaskGeneric = ([System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' })[0] Function Await($WinRtTask, $ResultType) { $asTask = $asTaskGeneric.MakeGenericMethod($ResultType) $netTask = $asTask.Invoke($null, @($WinRtTask)) $netTask.Wait(-1) | Out-Null $netTask.Result } # 加载Windows Runtime类型 [Windows.Devices.Radios.Radio, Windows.System.Devices, ContentType=WindowsRuntime] | Out-Null [Windows.Devices.Radios.RadioAccessStatus, Windows.System.Devices, ContentType=WindowsRuntime] | Out-Null [Windows.Devices.Radios.RadioState, Windows.System.Devices, ContentType=WindowsRuntime] | Out-Null # 请求蓝牙访问权限 Await ([Windows.Devices.Radios.Radio]::RequestAccessAsync()) ([Windows.Devices.Radios.RadioAccessStatus]) | Out-Null # 获取所有无线电设备,筛选出蓝牙设备 $radios = Await ([Windows.Devices.Radios.Radio]::GetRadiosAsync()) ([System.Collections.Generic.IReadOnlyList[Windows.Devices.Radios.Radio]]) $bluetooth = $radios | Where-Object { $_.Kind -eq 'Bluetooth' } # 如果未指定状态,自动切换相反状态 if (-not $BluetoothStatus) { $BluetoothStatus = if ($bluetooth.State -eq 'On') { 'Off' } else { 'On' } } # 设置蓝牙状态 Await ($bluetooth.SetStateAsync($BluetoothStatus)) ([Windows.Devices.Radios.RadioAccessStatus]) | Out-Null
脚本说明:
- 保留原脚本的参数控制:手动指定
-BluetoothStatus On/Off时,依然可以直接控制开关 - 不填参数时,自动检测当前蓝牙状态,切换为相反状态(开→关,关→开)
- 通过带
-WindowStyle Hidden的快捷方式启动时,无窗口弹出
内容的提问来源于stack exchange,提问作者slvdr510
相关产品推荐
相关产品推荐

