Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

README.md

Get-Log

Reads a logfile produced by Write-Log and returns the entries as PowerShell objects, ready for filtering, sorting and grouping.

Table of Content

Version Changes

1.0.0.0
  • First version published on GitHub

Background

Write-Log writes each event as a tab-separated line to a plain text file. That format is easy to tail and grep, but most of the time you actually want to filter by LogLevel, pick out a time window, or count events per category. Get-Log reads the file and returns objects with three properties, TimeStamp, LogLevel and Message, so you can pipe them into the usual suspects, Where-Object, Sort-Object, Group-Object, Select-Object, etc.

Internally it is a thin wrapper around Get-Content | ConvertFrom-Csv -Delimiter "``t" with the appropriate headers, so no external dependencies, just PowerShell builtins.

Parameters

Parameter Mandatory Default Notes
LogPath Yes Path to an existing logfile. Validated with Test-Path.

Examples

Read the full logfile:

    PS C:\> Get-Log -LogPath 'C:\Temp\MyScript.log'

    TimeStamp               LogLevel    Message
    ---------               --------    -------
    2023-01-01 12:00:00.000 Information Script started
    2023-01-01 12:00:01.123 Warning     Disk usage above 80%
    2023-01-01 12:00:01.456 Error       Backup job failed
    2023-01-01 12:00:02.000 Information Step 1 complete

Pick out just the Errors:

    PS C:\> Get-Log -LogPath 'C:\Temp\MyScript.log' | Where-Object LogLevel -eq 'Error'

    TimeStamp               LogLevel Message
    ---------               -------- -------
    2023-01-01 12:00:01.456 Error    Backup job failed

Count events by LogLevel:

    PS C:\> Get-Log -LogPath 'C:\Temp\MyScript.log' | Group-Object LogLevel -NoElement

    Count Name
    ----- ----
        2 Information
        1 Warning
        1 Error

Filter on a time window. Note that TimeStamp is a string in ISO 8601 order, so lexical comparisons work, but cast to [datetime] if you need arithmetic:

    PS C:\> Get-Log -LogPath 'C:\Temp\MyScript.log' |
                Where-Object { [datetime]$_.TimeStamp -gt (Get-Date).AddHours(-1) }