Reputation: 73
In Windows 10, is there a way to run cmd/powershell commands automatically when PC is connected to a particular device like a dock? (Like connecting a particular device triggers a command)
I want to do something like this-
If [device1 connected] -> Run Command A
If [device1 disconnected] -> Run Command B
If [device2 connected] -> Run Command C
...
Upvotes: 0
Views: 1174
Reputation: 2638
Yes.
https://www.winhelponline.com/blog/trigger-launch-program-script-connecting-to-specific-network/ describes using task scheduler to run a script on an Event Log event: anything that creates a notification in an event log can be used as the trigger.
Find an Event in an Event log: note the Log name and the Event ID.
Give your task a name in the General tab, and then click Triggers and then click New. Select "On an event": select the Log noted above, and enter the Event ID.
https://devblogs.microsoft.com/scripting/use-powershell-to-monitor-and-respond-to-events-on-your-server/ describes using WMI as an permanent event consumer: event consumers can be linked to many Windows Events, including connect/disconnect events, not just Event Log events, but isn't as self-evident.
$consumerPath = Set-WmiInstance -Class ActiveScriptEventConsumer
Upvotes: 3