PowerShell 2.0: One Cmdlet at a Time 98 Wait-Event

Continuing the series looking at new cmdlets available in PowerShell 2.0. This time we look at the Wait-Event cmdlet.

What can I do with it?

Pause a running script or session and wait for an event to occur before continuing.

Example:

The built-in PowerShell help has a great example for New-Event. It uses New-Event to create a custom event based on a reaction to another event. Use Wait-Event to make the current session pause until a new process has been opened. Open Windows Calculator to make the event trigger and return the prompt to the user.

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-Event -sourceID “PowerShell.ProcessCreated” -Sender $args[0] -EventArguments $args[1].SourceEventArgs.NewEvent.TargetInstance) } } Wait-Event -SourceIdentifier PowerShell.ProcessCreated

Before opening Windows Calculator:

You will notice that after the opening of Windows Calculator the event is triggered and the prompt is returned to the user.

How could I have done this in PowerShell 1.0?

PowerShell engine events are a new feature in PowerShell 2.0.

1000 things 1% better