Skip to content

Instantly share code, notes, and snippets.

@hazre
Last active August 11, 2024 22:35
Show Gist options
  • Select an option

  • Save hazre/be4f97cc5b12316219919789997e028d to your computer and use it in GitHub Desktop.

Select an option

Save hazre/be4f97cc5b12316219919789997e028d to your computer and use it in GitHub Desktop.
Virtual Desktop Audio Switcher PowerShell script, because VD doesn't seem to do it properly by itself. You can add it to Task Scheduler to start it on boot.
# Install the AudioDeviceCmdlets module if not already installed
if (-not (Get-Module -ListAvailable -Name AudioDeviceCmdlets)) {
Install-Module -Name AudioDeviceCmdlets -Force -Scope CurrentUser
}
Import-Module AudioDeviceCmdlets
# Define the audio devices to switch to when connected
$connectedInputDevice = "Your Connected Input Device Name"
$connectedOutputDevice = "Your Connected Output Device Name"
# Define the audio devices to switch back to when disconnected
$disconnectedInputDevice = "Your Disconnected Input Device Name"
$disconnectedOutputDevice = "Your Disconnected Output Device Name"
$Connected = $false
while ($true) {
$Running = Get-Process -Name "VirtualDesktop.Server" -ErrorAction SilentlyContinue
if (!$Running -and $Connected) {
Write-Output "User Not Connected"
# Switch back to disconnected audio devices
Set-AudioDevice -ID (Get-AudioDevice -List | Where-Object Name -eq $disconnectedInputDevice).ID
Set-AudioDevice -ID (Get-AudioDevice -List | Where-Object Name -eq $disconnectedOutputDevice).ID
Write-Output "Switched to disconnected audio devices"
$Connected = $false
} elseif ($Running -and !$Connected) {
Write-Output "User Connected"
# Switch to connected audio devices
Set-AudioDevice -ID (Get-AudioDevice -List | Where-Object Name -eq $connectedInputDevice).ID
Set-AudioDevice -ID (Get-AudioDevice -List | Where-Object Name -eq $connectedOutputDevice).ID
Write-Output "Switched to connected audio devices"
# Automatically launches SteamVR (comment out the line below if you don't want that)
& "C:\Program Files (x86)\Steam\steam.exe" steam://rungameid/250820
$Connected = $true
}
Start-Sleep -Seconds 5
}
@hazre
Copy link
Author

hazre commented Aug 6, 2024

If you want to start it in background (hidden), run with Powershell.exe -WindowStyle Hidden -Command VD_Audio_Switcher.ps1.

For Task Scheduler, make sure to add it to program/script section, not arguments or else it won't be hidden:
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment