PowerShell Eventing with WMI and CIM
Let’s continue our exploration of using events in PowerShell. Using objects like the FileSystemWatcher can be invaluable, but we’re just scratching the surface. WMI and CIM have an eventing infrastructure that we can tap into. It isn’t necessarily obvious and requires some sophisticated scripting. I also wouldn’t expect it to replace a third-party management product, but it can be helpful for smaller organizations or troubleshooting.
The concept is the same as what we’ve looked at previously. We watch for WMI/CIM-related events to fire and then take action or raise an event we can view with Get-Event
. There are dedicated Win32 classes we can use, although, in practice, we are limited to watching processes. Or we can use the generic event objects and subscribe to granular events with classes like Win32_Service.
The generic event classes are __InstanceCreationEvent
, __InstanceModificationEvent
, and __InstanceDeletionEvent
. That is a double underscore at the start of the name. We can watch for events EventArrived
and Stopped
. Although in practice, EventArrived
is what we’ll be using. We use these classes in a WMI query as we would any of the Win32 classes.
$query = "Select * from __InstanceCreationEvent"