Search code examples
windowspowershellevent-logpowershell-3.0

How to set up Powershell where-object for filtering EventLog


In interactive mode, this works:

Get-Eventlog -log application -after ((get-date).addMinutes(-360)) -EntryType Error

Now I want to filter out certain messages, the following didn't filter the desired word:

Get-Eventlog -log application -after ((get-date).addMinutes(-360)) -EntryType Error | where-object  {$_.$Message -notlike "*Monitis*"}

Also, how do I put in multiple conditions on the where-object?

In my script, I'm getting errors on the -and statement:

$getEventLog = Get-Eventlog -log application -after ((get-date).addMinutes($minutes*-1)) -EntryType Error 
# list of events to exclude 
$getEventLogFiltered = $getEventLog | where-object {$_.Message -notlike "Monitis*" 
                                       -and $_.Message -notlike "*MQQueueDepthMonitor.exe*"
                                       }
$tableFragment = $getEventLogFiltered | ConvertTo-Html -fragment

Error:

-and : The term '-and' is not recognized as the name of a cmdlet, function, script file, or operable program. Check
the spelling of the name, or if a path was included, verify that the path is correct and try again.
At D:\scripts\EventLogExtract2.ps1:24 char:40
+                                        -and $_.Message -notlike "*MQQueueDepthMo ...
+                                        ~~~~

Solution

  • In your 2nd code snippet remove the dollar sign right before "Message". Reads like the following. If you're using PowerShell ISE, you'll see that "Message" should be in black instead of red.

    Get-Eventlog -log application -after ((get-date).addMinutes(-360)) -EntryType Error | where-object  {$_.Message -notlike "*Monitis*"}
    

    For the 3rd code snippet, I placed a grave accent before starting a newline in the Where-Object filter. This tells PowerShell you're continuing a line instead of beginning a new one. Also, in PowerShell ISE, the comparison operators (-and & -notlike) turn from blue and black to grey.

    $getEventLog = Get-Eventlog -log application -after ((get-date).addMinutes($minutes*-1)) -EntryType Error 
    # list of events to exclude 
    $getEventLogFiltered = $getEventLog | where-object {$_.Message -notlike "Monitis*" `
                                           -and $_.Message -notlike "*MQQueueDepthMonitor.exe*"
                                           }
    $tableFragment = $getEventLogFiltered | ConvertTo-Html -fragment