Reading Event Logs (Part 1)

by Dec 4, 2020

In Windows, there are a number of event logs like “System” and “Application”, and in Windows PowerShell, it is simple to retrieve event entries from these logs using Get-EventLog. This one-liner returns the latest five error events from your System event log:

 
PS> Get-EventLog -LogName System -EntryType Error -Newest 5 | Out-GridView 
 

In PowerShell 7 and better, the cmdlet Get-EventLog no longer exists. It was replaced by Get-WinEvent which uses a different syntax and expects the query in the form of a hash table:

Get-WinEvent -FilterHashtable @{
  LogName = 'System'
  Level = 2
  } -MaxEvents 5

The “Level” key is a numeric value, and the lower the value the more critical the event. The ID number 2 represents “Error” entries. The ID number 3 would represent “Warning” entries. To see both errors and warnings, submit an array:

Get-WinEvent -FilterHashtable @{
  LogName = 'System'
  Level = 2,3
  } -MaxEvents 5

Even if you are using Windows PowerShell and do not plan to transition to PowerShell 7 anytime soon, now is the time to get used to Get-WinEvent and deprecate Get-EventLog because the new Get-WinEvent is available since PowerShell 3 and ensures that your code will seamlessly work in future PowerShell versions as well.

In addition, Get-WinEvent can access not only the few classic Windows event logs but also all of the application-specific events. Also, the results delivered by Get-WinEvent are more complete than those received from Get-EventLog: the latter occasionally returns results with messages like “the description for event xyz could not be found”. Get-WinEvent always returns the complete message.


Twitter This Tip! ReTweet this Tip!