Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

README.md

Write-Log

A simple logging function to incorporate in to scripts and automations. Appends a tab-separated, ISO 8601 timestamped line to a logfile. Pairs with Get-Log for reading the output back.

Table of Content

Version Changes

1.0.0.0
  • First version published on GitHub

Background

When writing scripts and automations, it is often useful to leave behind a small structured log, both for troubleshooting and for auditing. Write-Log is deliberately minimal, it writes a single line per call in a format that is trivial to read in a text editor and equally trivial to parse back into objects with Get-Log.

The function does not create or rotate the logfile, the target file must already exist (the -LogPath parameter is validated with Test-Path). Create the file once at the start of your script (ie. with New-Item) and then pipe or pass messages to Write-Log throughout.

Log Format

Each call appends one line to the logfile with three tab-separated fields:

<TimeStamp><TAB><LogLevel><TAB><Message>

Where:

  • TimeStamp, in the format yyyy-MM-dd HH:mm:ss.fff (ISO 8601 with millisecond precision).
  • LogLevel, one of Information, Warning, Error.
  • Message, the string passed to the -Message parameter.

Parameters

Parameter Mandatory Default Notes
Message Yes Accepts pipeline input. The text written to the log.
LogPath Yes Path to an existing file. Validated with Test-Path.
LogLevel No Information Validated set: Information, Warning, Error.

Examples

Create a logfile, and write a single Information event:

    PS C:\> New-Item -Path 'C:\Temp\MyScript.log' -ItemType File -Force | Out-Null
    PS C:\> Write-Log -Message 'Script started' -LogPath 'C:\Temp\MyScript.log'

Write a Warning and an Error:

    PS C:\> Write-Log -Message 'Disk usage above 80%' -LogPath 'C:\Temp\MyScript.log' -LogLevel Warning
    PS C:\> Write-Log -Message 'Backup job failed'    -LogPath 'C:\Temp\MyScript.log' -LogLevel Error

Pipe a sequence of messages into the log:

    PS C:\> 'Step 1 complete','Step 2 complete','Step 3 complete' |
                Write-Log -LogPath 'C:\Temp\MyScript.log'

Resulting logfile:

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
2023-01-01 12:00:02.010	Information	Step 2 complete
2023-01-01 12:00:02.020	Information	Step 3 complete

Read the events back as objects with Get-Log:

    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