I wanted to create a PowerShell script to toggle between two audio outputs (Headset and Speakers) instead of having to do several clicks in the system tray.
I started with this project: Powershell-Default-Audio-Device-Changer
I learned that the Registry path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Render\*"
contains all output audio devices ("render"). Each of these have a "DeviceState" property. If "DeviceState" = 1, the audio device is available to use. Some entries have "Level:0", "Level:1" properties. For some reason Windows seems to increment these as you toggle audio devices. Windows timestamps the "Level:0" value and looks for the latest timestamp. Reddit discussion
So I want to return the device ID for the maximum "Level:0" value. Unfortunately I'm a PowerShell novice and - despite hours of effort - cannot figure out how to get this done.
This is what I have now. It returns all available audio output devices and refuses to provide only the device with maximum "Level:0". How do I get the "Where-Object" to work?
Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Render\*" |
Where-Object {
(Get-ItemPropertyValue $_.PSPath DeviceState) -eq 1
} |
Where-Object {
(Get-ItemPropertyValue -Path $_.PSPath -Name "Level:0") -eq ($_ | Measure-Object -Property Level:0 -Maximum).Maximum
} |
Format-List
Also... trying to debug this in VSCode. It seems like any Watch that creates an error requires me to restart PowerShell terminal... ugh. Anyone else have an issue like this?
CodePudding user response:
Does this help?
Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Render\*"
| where DeviceState -eq 1 | sort Level:0 | select -ExpandProperty PSChildName -Last 1