Scripting. Powershell, VMware, Windows, Active Directory & Exchange. All that kind of stuff…..
RSS icon Email icon Home icon
  • PowerShell 2.0: One Cmdlet at a Time #92 Register-WmiEvent

    Posted on April 20th, 2010 Jonathan Medd No comments

    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.

    Example:

    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}

    Register-WmiEvent

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

    Register-WMIEvent2

    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

    Leave a reply