PowerShell 2.0: One Cmdlet at a Time 92 Register-WmiEvent

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

What can I do with it?

Subscribe to a WMI event on a local or remote computer and carry out actions based on the event.


Register for a WMI which checks every 10 seconds for any new processes which have started, call it Check for New Processes and save information including the date and time out to a log file.

Register-WmiEvent -Query “select * from __instancecreationevent within 10 where targetinstance isa ‘win32_process’” -SourceIdentifier “Check for New Processes” -Action {“A new process started at " + (Get-Date) | Out-File c:\log.txt -Append}

After running the above command and then starting a process the below is automatically written to c:\log.txt after a few seconds.

How could I have done this in PowerShell 1.0?

The Scripting Guys detail how to do this in PowerShell 1.0 in this article by using .NET. The code to achieve it is reproduced below:

$a = 0 $timespan = New-Object System.TimeSpan(0, 0, 1) $scope = New-Object System.Management.ManagementScope(”\\.\root\cimV2") $query = New-Object System.Management.WQLEventQuery ` ("__InstanceDeletionEvent",$timespan, “TargetInstance ISA ‘Win32_Process’” ) $watcher = New-Object System.Management.ManagementEventWatcher($scope,$query) do { $b = $watcher.WaitForNextEvent() $b.TargetInstance.Name } while ($a -ne 1)

1000 things 1% better