0

Will this code produce only the last line of the System eventlog file associated with event ID number 4201? I just don't get it. Help please!

Code:

     get-eventlog system | where-object {$_.eventID -eq 4201}

2 Answers 2

5

Lets break it apart

  • get-eventlog - Calls the Get-EventLog commandlet
  • system - Passes as the first parameter the word "system" this causes the System Event log to be choosen
  • | - Pipe the output of the previous commandlet as the input to the next commandlet
  • where-object - Filters the input commandlet based on a filter expression
  • { - The start of the expression
  • $_ - A variable that represents the current row being evaluated in the result set
  • .eventID - Selects the EventID property from the variable.
  • -eq - test that the left hand side is equal to the right hand side
  • 4201 - the number 4201 to signify the event id we want to test.
  • } - the end of the expression that is used to filter

As you see there is no part that only selects the most recent record. Thankfully because Get-EventLog returns the objects in order of newest to oldest we only need to add a Select-Object to the query.

get-eventlog system | where-object {$_.eventID -eq 4201} | Select-Object -First 1
  • Select-Object - Filter out the result set based on some parameters
  • -First - Select only the first X items where X is defined by the next property
  • 1 - The number 1 to signify we only want the first result.

If our list was not in order we would need to add a Sort-Object to it too

get-eventlog system | where-object {$_.eventID -eq 4201} | Sort-Object -Descending TimeGenerated | Select-Object -First 1
  • Sort-Object - Sort the result based on some parameters
  • -Descending - Sort from largest to smallest
  • TimeGenerated - Use the TimeGenerated property to sort

Note: you could drop the -Descending and change -First 1 to -Last 1 to also get the same results.

Sign up to request clarification or add additional context in comments.

Comments

1

It will output all of the event log entries that have that EventID.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.