Saturday, August 29, 2015

PowerShell - Event Log

You can use the Get-Eventlog cmdlet to access log entries. You can use this cmdlet for two purposes, one is to list the event logs, second you can use it to extract all the events within a specific event log.

-List paramter is used with this cmdlet to list down only event logs.
Get-EventLog -List

If you wanted to get a display of all the entries in the System log, you can just put the log name ('System' in this case) with cmdlet:
Get-EventLog System

But depending on the number of records in the event log, you might get a long scrolling in shell. So its better to use the PowerShell filters. Use Where-Object to pass the information retrieved by Get-Eventlog through the pipeline while allowing only those entries through that meet your criteria. For example the following command will list down all the event in the system events log, that are recorded today.
Get-Eventlog System | Where-Object {($_.TimeWritten).Date -eq (Get-Date).Date}

We also have the -newest parameter. You can simply get only the last x number of events recorded in the log. For example, this command retrieves the last three events written to the System event log:
Get-EventLog System -newest 3

Or you can put the -Format-List parameter for better view:
Get-EventLog System -newest 3 | Format-List

You can use the methods of the .NET framework, to make event entries:
[Diagnostics.EventLog]::WriteEntry("Application","My test event","Information")

To see if this event is successfully recorded, you can check the Event Viewer:

Or you can use the same -newset parameter with cmdlet to view this test event.
Get-EventLog Application -newest 3 | Format-List

No comments:

Post a Comment