0

I am trying to develop my automation script. Therefore, I need to know how to turn off and on Bluetooth in Powershell and Bash.

  • 1
    What is the base OS? Windows? Linux? Windows+WSL? Other? And what version? – xenoid Sep 04 '20 at 06:43
  • 1
    What did you search for? ['powershell turn off bluetooth'](https://duckduckgo.com/?q=%27powershell+turn+off+bluetooth%27&t=h_&ia=web) Sites like SU and SO has rules. [How to ask](https://superuser.com/questions/how-to-ask) --- [Proper Topic](https://stackoverflow.com/help/on-topic) Note: Never just copy/paste and run code, no matter who/where you get it from unless you understand what it is really doing or accept all consequences of using it. – postanote Sep 04 '20 at 16:34

1 Answers1

0

Assuming this is a Windows 10 thing. This is a duplicate question. Make sure you read the complete Q&A as it's talking to legacy WinRT, but the approach would be along similar lines.

Turn on/off Bluetooth radio/adapter from cmd/powershell in Windows 10

[CmdletBinding()] Param (
    [Parameter(Mandatory=$true)][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() | ? { $_.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.Devices.Radios.Radio,Windows.System.Devices,ContentType=WindowsRuntime] | Out-Null
[Windows.Devices.Radios.RadioAccessStatus,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 | ? { $_.Kind -eq 'Bluetooth' }
[Windows.Devices.Radios.RadioState,Windows.System.Devices,ContentType=WindowsRuntime] | Out-Null
Await ($bluetooth.SetStateAsync($BluetoothStatus)) ([Windows.Devices.Radios.RadioAccessStatus]) | Out-Null
postanote
  • 4,589
  • 2
  • 7
  • 7