PowerShell Eventing QuickStart

PowerShell Team


The second CTP of PowerShell V2 (CTP2) introduces another new feature called PowerShell Eventing. PowerShell Eventing lets you respond to the asynchronous notifications that many objects support. We didn’t get a chance to fully document these cmdlets in the CTP2, though, so here’s a quick start and primer to help you explore the feature.

Discovering Events

Before playing with PowerShell eventing, you’ll probably want to find an object that supports events. But how do you know what an object supports? You will most commonly discover this through API documentation (“To receive notifications, subscribe to the <Foo> event,”) but Get-Member has also been enhanced to show the events supported by an object:

PS >$timer = New-Object Timers.Timer
PS >$timer | Get-Member -Type Event

   TypeName: System.Timers.Timer

Name     MemberType Definition
—-     ———- ———-
Disposed Event      System.EventHandler Disposed(System.Object, System.EventArgs)
Elapsed  Event      System.Timers.ElapsedEventHandler Elapsed(System.Object, System.Timers.ElapsedEventArgs)

Subscribing to Events

Once you’ve determined the event name you are interested in, the Register-ObjectEvent cmdlet registers your event subscription in the system. The SourceIdentifier parameter helps identify events generated by this object, and lets you manage its event subscription:

PS >Register-ObjectEvent $timer Elapsed -SourceIdentifier Timer.Elapsed

In addition to the Register-ObjectEvent cmdlet, additional cmdlets let you register for WMI events and PowerShell engine events. 

The Get-PsEventSubscriber cmdlet shows us all event subscribers in the session:

PS >Get-PSEventSubscriber

SubscriptionId   : 4
SourceObject     : System.Timers.Timer
EventName        : Elapsed
SourceIdentifier : Timer.Elapsed
Action           :
HandlerDelegate  :
SupportEvent     : False
ForwardEvent     : False

Polling for Events

The simplest way to manage events is to simply subscribe to them, and occasionally check the event queue. When you are done with the event, remove it from the queue. The Get-PsEvent and Remove-PsEvent cmdlets let you do that:

PS >Get-PsEvent
PS >$timer.Interval = 2000
PS >$timer.Autoreset = $false
PS >$timer.Enabled = $true
PS >Get-PsEvent
PS >Get-PsEvent

EventIdentifier  : 11
Sender           : System.Timers.Timer
SourceEventArgs  : System.Timers.ElapsedEventArgs
SourceArgs       : {System.Timers.Timer, System.Timers.ElapsedEventArgs}
SourceIdentifier : Timer.Elapsed
TimeGenerated    : 6/10/2008 3:33:39 PM
MessageData      :
ForwardEvent     : False

PS >Remove-PsEvent *
PS >Get-PsEvent

Most objects pack their interesting data in a class derived from “EventArgs.” To make working with these as easy as possible, the SourceEventArgs property is a shortcut to the first parameter in the event handler that derives from EventArgs. The SourceArgs parameter gives you full access to the event handler parameters, letting you deal with events that don’t follow the basic “Object sender, EventArgs e” pattern.

Waiting for Events

Polling for an event is tedious, since you usually want to wait until the event is raised before you do something. The Wait-PsEvent cmdlet lets you do that. Unlike synchronous objects on methods (i.e.: Process.WaitForExit(),) this cmdlet lets you press Control-C to halt the wait:

PS >$timer.Interval = 2000
PS >$timer.Autoreset = $false
PS >$timer.Enabled = $true; Wait-PsEvent Timer.Elapsed

<2 seconds pass>

EventIdentifier  : 12
Sender           : System.Timers.Timer
SourceEventArgs  : System.Timers.ElapsedEventArgs
SourceArgs       : {System.Timers.Timer, System.Timers.ElapsedEventArgs}
SourceIdentifier : Timer.Elapsed
TimeGenerated    : 6/10/2008 3:24:18 PM
MessageData      :
ForwardEvent     : False

Once you’ve finished working with the event, remove it from the queue.

Asynchronous Processing of Events

While waiting for an event is helpful, you usually don’t want to block your script or shell session just waiting for the event to fire. To support this, the Register-*Event cmdlets support an -Action scriptblock. PowerShell will invoke that scriptblock in the background when your event arrives. These actions invoke in their own module — they can get and set $GLOBAL variables, but regular variable modifications happen in their own isolated environment.

function DoEvery
   param([int] $seconds,[ScriptBlock] $action )

   $timer = New-Object System.Timers.Timer
   $timer.Interval = $seconds * 1000
   $timer.Enabled = $true
   Register-ObjectEvent $timer “Elapsed” -SourceIdentifier “Timer.Elapsed” -Action $action

DoEvery 2 { [Console]::Beep(300, 100) }

## Eventually
Unregister-PsEvent “Timer.Elapsed”

(Warning: The $args parameter in event actions has changed since CTP2 based on usability feedback. Such is the risk and reward of pre-release software!)

However, doing two things at once means multithreading. And multithreading? Thar be dragons! To prevent you from having to deal with multi-threading issues, PowerShell tightly controls the execution of these script blocks. When it’s time to process an action, it suspends the current script or pipeline, executes the action, and then resumes where it left off. It only processes one action at a time.

One great use of asynchronous actions is engine events, and the Register-PsEvent cmdlet:

## Now in your profile
$maximumHistoryCount = 1kb

## Register for the engine shutdown event
Register-PsEvent ([System.Management.Automation.PsEngineEvent]::Exiting) -Action {
   Get-History -Count $maximumHistoryCount | ? { $_.CommandLine -ne “exit” } |
       Export-CliXml (Join-Path (Split-Path $profile) “commandHistory.clixml”)

## Load our previous history
$historyFile = (Join-Path (Split-Path $profile) “commandHistory.clixml”)
if(Test-Path $historyFile)
   Import-CliXml $historyFile | Add-History

Support Events

Ultimately, almost any event can be written in terms of Register-ObjectEvent. PowerShell is all about task-based abstractions, though, so event forwarding lets you (and ISVs) map complex event domains (such as WMI queries) to much simpler ones. The -SupportEvent parameter to the event registration cmdlets help there, as its event registrations don’t show in the default views:

## Enable process creation events
function Enable-ProcessCreationEvent
   $query = New-Object System.Management.WqlEventQuery “__InstanceCreationEvent”, `
       (New-Object TimeSpan 0,0,1), `
       “TargetInstance isa ‘Win32_Process'”
   $processWatcher = New-Object System.Management.ManagementEventWatcher $query

   $identifier = “WMI.ProcessCreated”
   Register-ObjectEvent $processWatcher “EventArrived” -SupportEvent $identifier -Action {
       [void] (New-PsEvent “PowerShell.ProcessCreated” -Sender $args[0] -EventArguments $args[1].SourceEventArgs.NewEvent.TargetInstance)

## Disable process creation events
function Disable-ProcessCreationEvent
   Unregister-PsEvent -Force -SourceIdentifier “WMI.ProcessCreated”

## Register for the custom “PowerShell.ProcessCreated” engine event
Register-PsEvent “PowerShell.ProcessCreated” -Action {
   $processName = $args[1].SourceArgs[0].Name.Split(“.”)[0]
   (New-Object -COM Sapi.SPVoice).Speak(“Welcome to $processName”)

## Eventually
Unregister-PsEvent PowerShell.ProcessCreated

(Warning: The $args parameter in event actions has changed since CTP2 based on usability feedback. Such is the risk and reward of pre-release software!)

Event Forwarding

When registering for an event on a remote machine, you can specify the “-Forward” parameter if you want to deliver the event to the client session connected to the remote machine. Here’s an example:

$remoteComputer = “REMOTE_COMPUTER”
$session = New-PsSession $remoteComputer

Unregister-Event WMI.Service.Stopped -ErrorAction SilentlyContinue

## Register for an event that fires when a service stops on the remote computer
## Set this to forward to the client machine.
Invoke-Command $session {

    ## The WMI query to detect a stopping service
    $query = @”
        SELECT *
        FROM __InstanceModificationEvent
        WITHIN 2
        WHERE TargetInstance ISA ‘Win32_Service’
        AND TargetInstance.Name = ‘WSearch’
        AND TargetInstance.State = ‘Stopped’

    ## Register for the WMI event
    Register-WmiEvent -Query $query “WMI.Service.Stopped” -Forward

## Register for notifications from remote computers with the event name
## WMI.Service.Stopped. We’ll LOCALLY show the event log of the computer
## that generated it.
$null = Register-EngineEvent WMI.Service.Stopped `
    -Action { Show-EventLog $event.ComputerName }

## Stop the service
Invoke-Command $session { Stop-Service WSearch }

## Play in the shell
1..10 | % { Write-Host “Sleeping…”; Start-Sleep 1 }

Read-Host “Is it fixed?”

## Fix the service by restarting it.
Invoke-Command $session { Start-Service WSearch }

Remove-PsSession $session

Hope this helps getting started.

Lee Holmes [MSFT]
Windows PowerShell Development
Microsoft Corporation


Discussion is closed.

Feedback usabilla icon