Search code examples
powershellpowershell-4.0get-eventlogget-wmiobjectget-winevent

Add Filter to Get-EventLog (server side), returning only newest N records


Is there any way to filter event log entries using PowerShell before retrieving them?

i.e.

Instead of:

[string[]]$IgnoredSources = 'SomeValue','SomeOtherValue'
Get-Eventlog -LogName $MyLog -ComputerName $MyComputer `
| ?{$IgnoredSources -notcontains $_.Source} `
| Sort-Object TimeGenerated -Descending `
| Select-Object -First 10

Something like:

Get-Eventlog -LogName $MyLog -ComputerName $MyComputer `
-Filter {(Source -ne 'SomeValue') -and (Source -ne 'SomeOtherValue')} `
-Newest 10 

More info

I'm aware that I can add a where-object statement to filter the results pulled back; but that's less efficient than filtering on the server side, and means that commands such as -Newest 100 won't necessarily return 100 results once filtered (i.e. I'd have to pull back the entire event log to ensure that I'd get the latest

I'm also aware that for dates this is possible via the -After and -Before attributes, and that it's possible to provide a list of -Username's and -Source's to limit to those. However if I want to exclude 1 source, or filter on a range of event ids, there seems to be no way at present.

I've looked into using Get-WmiObject instead of Get-EventLog, but whilst this allows the filtering to take place server side, I couldn't determine a way to limit the number of results returned (i.e. returned to my machine before sorting then using select-object's -first to then filter down the results).

Get-WmiObject Win32_NTLogEvent -ComputerName $MyComputer `
-filter "(logfile='$MyLog') and (sourcename != 'SomeValue') and (sourcename != 'SomeOtherValue') " `
| Sort-Object TimeGenerated -Descending `
| Select-Object -First 10

Solution

  • How about Get-WinEvent? Something like this:

    Get-WinEvent -ComputerName $MyComputer -MaxEvents 100 -FilterHashtable @{
        LogName=$MyLog;
        ID=$MyID;
        <# etc. #>
    }