PowerShell 2.0: One Cmdlet at a Time 93 Register-ObjectEvent

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

What can I do with it?

Subscribe to an event on a local or remote computer generated by a .NET Framework object and carry out actions based on the event.

Example:

Register for an event to check for new processes, use the ManagementEventWatcher .NET object to form the basis of the object to monitor and save information including the date and time out to a log file.

$query = New-Object System.Management.WqlEventQuery “__InstanceCreationEvent”, (New-Object TimeSpan 0,0,1), “TargetInstance isa ‘Win32_Process’” $processWatcher = New-Object System.Management.ManagementEventWatcher $query Register-ObjectEvent -inputObject $processWatcher -eventName “EventArrived” -Action {“A new process started at " + (Get-Date) | Out-File c:\log.txt -Append}

After running the above commands 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