PowerShell question with sorting and piping

2873 views powershell

Hello I am using PowerShell Version 5 I am running a command and it is working but the narrowed search is not returning results.

Get-EventLog System -Newest 5 | where {$_.eventID -eq 1074}

So I thought oh I only want to see the last 5 objects that match my filter. It runs but returns no result because in the event log there is no eventID 1074 in the last 5 entries. So I just need to move that parameter to the end. No luck

Get-EventLog System | where {$_.eventID -eq 1074} | -newest 5

-newest : The term '-newest' 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 line:1 char:53 + Get-EventLog System | where {$_.eventID -eq 1074} | -newest 5 + ~~~~~~~ + CategoryInfo : ObjectNotFound: (-newest:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException

So positioning the -newest after the pipe moves the parameter into a position I think where it is not understood.

Any one have some advice to how I can approach thinking about this that will help me out in the future?

answered question

1 Answer


To limit your filtered results to at most 5 events, you must use Select-Object -First 5 in a final pipeline segment:

Get-EventLog System | Where-Object { $_.eventID -eq 1074 } | Select-Object -First 5

-Newest <n> is a parameter that is specific to Get-EventLog, and it unconditionally returns the first <n> entries, irrespective of their content.

There is no common parameter across cmdlets that offers similar functionality, but there's the generic Select-Object cmdlet that allows selecting up to <n> objects from whatever its input is via -First <n>.

posted this

Have an answer?


Please login first before posting an answer.