The basic usage of PowerEvents includes creating three objects:
- A WMI event filter
- A WMI event consumer
- A binding between the filter and consumer (this initiates the flow of events)
The cmdlets included in the PowerEvents module make performing the above steps quite easy.
Your First PowerEvents Example
Step 1: Create an Event Filter
The first step to working with PowerEvents is to create an event filter. The event filter defines the WMI events that you want to capture, and then respond to, with the "consumer." Remember that until a filter and consumer are bound together using New-WmiFilterToConsumerBinding, no events will be responded to. You must tell WMI which consumer you would like to use with a filter.
Here is an example of creating a WMI event filter that captures all new threads created on a system. Because threads are constantly being created and terminated in the system, this query will return a fair number of events, and will make it easy to test the creation of a consumer.
$MyFilter = New-WmiEventFilter -Query "select * from __InstanceCreationEvent within 5 where TargetInstance ISA 'Win32_Thread'"
Step 2: Create an Event Consumer
The second major piece to PowerEvents is the event consumer. The consumer defines the action that will be taken in response to an event occurrence. Windows provides five WMI consumer classes, which allow for a fair amount of flexibility in your response. For now, we'll focus on using the log file consumer.
$MyConsumer = New-WmiEventConsumer -ConsumerType LogFile -Name ThreadCreated -Text `
"A thread with handle %TargetInstance.Handle% has been created on process with handle %TargetInstance.ProcessHandle%"
In the example above, we create a "LogFile" consumer with a name that is appropriate to its purpose. The -Text parameter is used to define the text that will be written to the log file. The -FileName parameter is used to specify the log file that the text will be written to.
Step 3: Create the Binding Between the Filter and Consumer
Now that we've created an event filter and a consumer for those events, we can bind them together using the New-WmiFilterToConsumerBinding cmdlet.
New-WmiFilterToConsumerBinding -Filter $MyFilter -Consumer $MyConsumer
Once the event binding has been created, the consumer will begin responding to events from the filter.
For more information, please see the PowerEvents documentation and the examples in the \Samples subfolder of the module.