Search code examples
powershellevent-log

How to register an event for 'get-eventlog'?


I need to watch for specific errors in my Windows 7 event log - is there is a one-liner to do this ?

So: for example - I am watching out for 'disk' errors; so I can get the latest events by doing something like:

get-eventlog system  -source "disk" -after ([datetime]::Today)

(This is the answer from another Post in fact: Get-EventLog - easily filter by 'today'? )

But obviously I have to keep running this to keep on top of any alerts.


Solution

  • There is no one-liner. But instead of polling the EventLog, you could use the System.Diagnostic.EventLog class and register to the EntryWritten event using the Register-ObjectEvent cmdlet.

    Here an example where I register to the application log and just output the message in the callback:

    $eventLog = New-Object System.Diagnostics.EventLog "application"
    $eventLog.EnableRaisingEvents = $true
    $job = Register-ObjectEvent -InputObject $eventLog -EventName "EntryWritten" -Action { Write-Host ($eventArgs.Entry.Message) } 
    Receive-Job $job
    

    You can now test the callback using:

    $eventLog.Source = "test"
    $eventLog.WriteEntry("test")
    

    Which will output test to the console.