Responding to New Event Log Entries (Part 2)

by Dec 14, 2018

Here is another file system task that sounds worse than it actually is. Let’s say you need to remove all folders below a given level in a folder structure. Here is how:

# set the event log name you want to subscribe to
# (use Get-EventLog -AsString for a list of available event log names)
$Name = 'Application'

# get an instance
$Log = [System.Diagnostics.EventLog]$Name

# determine what to do when an event occurs
$Action = {
    # get the original event entry that triggered the event
    $entry = $event.SourceEventArgs.Entry

    # log all events
    Write-Host "Received from $($entry.Source): $($entry.Message)"

    # do something based on a specific event
    if ($entry.EventId -eq 1 -and $entry.Source -eq 'WinLogon') 
        Write-Host "Test event was received!" -ForegroundColor Red


# subscribe to its "EntryWritten" event
$job = Register-ObjectEvent -InputObject $log -EventName EntryWritten -SourceIdentifier 'NewEventHandler' -Action $Action 

# now whenever an event is written to the log, $Action is executed
# use a loop to keep PowerShell busy. You can abort via CTRL+C

Write-Host "Listening to events" -NoNewline

        Wait-Event -SourceIdentifier NewEventHandler -Timeout 1
        Write-Host "." -NoNewline

    } while ($true)
    # this executes when CTRL+C is pressed
    Unregister-Event -SourceIdentifier NewEventHandler
    Remove-Job -Name NewEventHandler
    Write-Host ""
    Write-Host "Event handler stopped."

While the event handler is active, PowerShell outputs “dots” every second, indicating it is listening. Now open a second PowerShell window, and run this:

Write-EventLog -LogName Application -Source WinLogon -EntryType Information -Message test -EventId 1 

Whenever a new Application event log entry is written, the event handler echos the event details. If the event has an EventID equals 1 and a source of “WinLogon”, like in our test event entry, a red message is output as well.

To end the event handler, press CTRL+C. The code automatically cleans up and removes the event handler from memory.

This all works by using Wait-Event: this cmdlet can wait for a specific event to occur, and while it waits, PowerShell continues to process the event handler. When you specify a timeout (in seconds), the cmdlet returns control to your script. In our example, control is returned every second, enabling the script to output a progress indicator like the dots.

If the user presses CTRL+C, the script won’t stop immediately. Instead, it first executes the finally block and makes sure the event handler is cleaned up and removed.

Twitter This Tip! ReTweet this Tip!