PowerShell question with sorting and piping

82 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST 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>.

2
On

here's a likely faster way to get the info you seem to want. it uses Get-WinEvent instead of Get-EventLog and also uses the -FilterHashtable parameter to let the event system do some of the filtering.

#requires -RunAsAdministrator

$FilterHash = @{
    Logname = 'System'
    ID = 1074
    StartTime = (Get-Date).AddDays(-20)
    }
Get-WinEvent -FilterHashtable $FilterHash -MaxEvents 20

this is usually noticeably faster than using Get-EventLog. [grin]

here's an article on the ideas ...

Use FilterHashTable to Filter Event Log with PowerShell – Hey, Scripting Guy! Blog
https://blogs.technet.microsoft.com/heyscriptingguy/2014/06/03/use-filterhashtable-to-filter-event-log-with-powershell/