Question

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:

  • power cable plugged/unplugged (battery charging/discharging)
  • hardware (like the Surface Pro 2 Type Cover 2) is connected/disconnected

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.

  1. I assume this is the most efficient way of doing it so I don't have to continuously poll and instead react to an event?
  2. And if so, is it better to use -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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top