Tag: Windows Events

  • Show Event Logs in PowerShell

    Show Event Logs in PowerShell

    In this post, we will explore how to use PowerShell to view event logs. We will use the Get-EventLog command to accomplish this. Specifically, we will cover the following:
    List Event Types Available
    Get Most Recent Events
    Get Events Between a Date Range

    List Event Types Available

    To list the available event log types on a system using the Get-EventLog command, you can run the following:

    # Get event types PowerShell
    Get-EventLog -List
    Get-EventLog -List

    This will return a list of event log types that are available on the system, such as System, Security, and Application. We can then use the -LogName parameter with Get-EventLog to specify a specific event log type to work with.

    Get Most Recent Events

    To return the most recent Windows events for investigating an error that occurred, you can use the following PowerShell command:

    # Get most recent Windows events PowerShell
    Get-EventLog -LogName System -Newest 100
    

    This command will retrieve the 100 most recent events from the System event log, which is where many critical errors and warnings are logged by Windows and other applications.

    In the next example below I am bringing back the newest 1000 error events, grouping by event name and count of error occurrences. This can give a high-level view of frequent events and recent events on the host.

    # Get most recent application events by count
    Get-EventLog -LogName Application -Newest 1000 -EntryType Error | Group-Object -Property Source -NoElement | Sort-Object -Property Count -Descending

    Get Events Between a Date Range

    Here is a PowerShell script that will get all critical and error events from the Windows event logs between a specified date range. The start and end dates can be passed as parameters to the script:

    param(
        [DateTime]$StartDate,
        [DateTime]$EndDate
    )
    
    # Get all critical and error events from the Windows event logs
    Get-WinEvent -FilterHashtable @{
        LogName = 'System, Application';
        Level = 1, 2;
        StartTime = $StartDate;
        EndTime = $EndDate
    }
    

    To run the script, you can use the following command, replacing START_DATE and END_DATE with the actual start and end dates:

    .\Get-CriticalAndErrorEvents.ps1 -StartDate '2021-01-01' -EndDate '2021-12-31'
    

    This script uses the Get-WinEvent cmdlet to retrieve events from the Windows event logs. It filters the events by log name (System and Application), level (critical and error), and date range (using the start and end date parameters). It then outputs the resulting events to the console.