Skip to content

Instantly share code, notes, and snippets.

@alimbada
Last active April 8, 2025 11:15
Show Gist options
  • Save alimbada/cc782c98ab85ab16781489db9bbdf56c to your computer and use it in GitHub Desktop.
Save alimbada/cc782c98ab85ab16781489db9bbdf56c to your computer and use it in GitHub Desktop.
Send commands for switching HDMI input to an LG (webOS) TV when WMI events are triggered by KVM switch (connect/disconnect)
#Requires AutoHotkey v2.0
#SingleInstance
Run "powershell -NoExit C:\Users\Ammaar.Limbada\Register-KvmEvents.ps1", , "Hide"
Persistent
Register-WmiEvent -Query "SELECT * FROM __InstanceCreationEvent WITHIN 1 WHERE TargetInstance ISA 'win32_PNPEntity' AND TargetInstance.DeviceID like 'USB\\VID_045B&PID_0209%'" -SourceIdentifier KVMConnected -Action { lgtv --name MyTV --ssl setInput HDMI_4 }
Register-WmiEvent -Query "SELECT * FROM __InstanceDeletionEvent WITHIN 1 WHERE TargetInstance ISA 'win32_PNPEntity' AND TargetInstance.DeviceID like 'USB\\VID_045B&PID_0209%'" -SourceIdentifier KVMDisonnected -Action { lgtv --name MyTV --ssl setInput HDMI_3 }
@alimbada
Copy link
Author

alimbada commented Jul 12, 2024

This requires https://github.com/klattimer/LGWebOSRemote to send the commands to the LG webOS TV.

If you know the name of your device you can obtain the DeviceID can be obtained by running:

Get-WmiObject win32_PNPEntity | where { $_.Name -eq "Generic USB Hub" }

$_.Caption may be used instead of $_.Name

You can also get all USB devices with InstanceIDs (which seem to be identical to DeviceID?) by running:

Get-PnpDevice -PresentOnly | Where-Object { $_.Class -eq 'USB' } | Format-Table -AutoSize

@alimbada
Copy link
Author

alimbada commented Jul 17, 2024

⚠This only works for as long as the console it is run from remains open, which is not ideal

There are ways to make the event subscription permanent

Further reading:

https://learn-powershell.net/2013/08/14/powershell-and-events-permanent-wmi-event-subscriptions/
https://learn.microsoft.com/en-us/windows/win32/wmisdk/commandlineeventconsumer

As a workaround you can set up the provided AutoHotkey script to run on login. It creates a hidden console window.

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