I am trying to write an efficient Windows 8.1 PowerShell 4.0 script that will catch/trigger on two types of events. I want to be able to catch these events/triggers so I can do something like run a script or start/stop a service or something.
The events I want to catch/trigger on are:
By efficient I mean the script shouldn't have an infinite loop to periodically check the status. I would assume I should be able to write something that will catch events as Windows generates them?
So far I have learned that I can use the Register-WmiEvent
PowerShell cmdlet to subscribe to WMI events.
-query
or -class
when registering for events? The only difference I have seen is that it's obviously easy to filter on events when using -query
(e.g. Register-WmiEvent -query "Select * From Win32_PowerManagementEvent where EventType=10"
).I'll worry about how to catch the specific events I need later. Right now I'm trying to figure out how to catch/trigger events in general.
For the first one (power cable plugged/unplugged), have a look to Win32_PowerManagementEvent class ; you can use :
Register-WmiEvent -Query "select * from Win32_PowerManagementEvent" -MessageData "Event Power by JPB" -SourceIdentifier "EVTPOW1"
Wait-Event -SourceIdentifier "EVTPOW1"
Or
Register-WmiEvent -Query "select * from Win32_PowerManagementEvent" -SourceIdentifier "EVTPOW2" -Action {Write-Host "blurp"; [console]::Beep(500,500)}
In the second case you put in your script block the code you need.