Register WmiEvent - PowerShell
Overview
Register-WmiEvent registers a PowerShell script to be executed when a specified Windows Management Instrumentation (WMI) event is raised. This allows for automated event handling and simplifies event subscription management.
Syntax
Register-WmiEvent [-Listener {ListenerName}] [-SourceName <string>] [[-Namespace <string>]|[-Class <string>|[-Query <string|CIMQuery>]]] [-Filter <string|CIMFilter>] [-Action <ScriptBlock>] [-MaxEvents <Int32>] [-ThrowOnError] [-AsJob] [-CimSession <CimSession>] [-ErrorAction <ActionPreference>] [-Force]
Options/Flags
- -Listener: Specifies the name of the event listener to create or use. Defaults to “PowerShellListener”.
- -SourceName: The name of the WMI event source to monitor.
- -Namespace: The WMI namespace where the event is located.
- -Class: The WMI class that generates the event.
- -Query: A WQL query to filter the events.
- -Filter: A WMI event filter to apply.
- -Action: A script block to execute when the event is raised.
- -MaxEvents: The maximum number of events to store in the listener. Defaults to 100.
- -ThrowOnError: Indicates whether to throw an error if the event registration fails.
- -AsJob: Runs the command as a background job.
- -CimSession: Specifies a CIM session to use for the operation.
- -ErrorAction: Specifies the action to take if an error occurs.
- -Force: Overwrites an existing event listener with the same name.
Examples
Example 1: Register an event listener for the “Win32_LogonSession” event:
Register-WmiEvent -Listener MyListener -SourceName Win32_LogonSession
Example 2: Register an event listener with a filter:
$filter = "EventCode = 592"
Register-WmiEvent -Listener MyListener -SourceName Win32_LogonSession -Filter $filter
Example 3: Register an event listener with an action script:
$action = {
Write-EventLog -LogName "MyEventLog" -Source "MyListener" -EntryType "Information" -Message "Event occurred: $($Event.EventCode)"
}
Register-WmiEvent -Listener MyListener -SourceName Win32_LogonSession -Action $action
Common Issues
- Event registration fails: Verify that the specified WMI event source and class exist.
- No events are raised: Ensure that the WMI provider is enabled and the event filter is correctly configured.
- Script execution errors: Check the syntax of the action script and ensure that it has sufficient permissions to perform the desired actions.
Integration
Register-WmiEvent can be used in conjunction with other PowerShell commands to automate event handling tasks. For example, it can be combined with Start-Job to run the action script in a background job, or with Get-WmiEvent to retrieve and process event data.
Related Commands
- Get-WmiEvent
- Unregister-WmiEvent
- WMI Event Subscription