PowerShell Tool Logging
Logging is writing a record of what a script did into a file. A log file keeps that record after the script ends, so problems can be checked later.
Add-Content appends without erasing
Each Add-Content line lands at the end of the file. Reading the file back shows both lines in order.
Add-Content -Path (Join-Path $PSScriptRoot "app.log") -Value "step 1 done"
Add-Content -Path (Join-Path $PSScriptRoot "app.log") -Value "step 2 done"
Get-Content -Path (Join-Path $PSScriptRoot "app.log")A logging function labels every line
The function adds the INFO label to each message. Every line in the file then carries its kind.
function Write-LogEntry {
param([string]$Message)
Add-Content -Path (Join-Path $PSScriptRoot "app.log") -Value ("INFO: " + $Message)
}
Write-LogEntry -Message "started"
Write-LogEntry -Message "finished"
Get-Content -Path (Join-Path $PSScriptRoot "app.log")A transcript records the whole session
Start-Transcript begins the record and Stop-Transcript ends it. Both commands are sent to Out-Null, so only the work and the check print.
Start-Transcript -Path (Join-Path $PSScriptRoot "session.txt") | Out-Null
"work done"
Stop-Transcript | Out-Null
Test-Path -Path (Join-Path $PSScriptRoot "session.txt")Example
function Write-LogEntry {
param([string]$Level = "INFO", [string]$Message)
Add-Content -Path (Join-Path $PSScriptRoot "app.log") -Value ($Level + ": " + $Message)
}
Write-LogEntry -Message "job started"
Write-LogEntry -Level "ERROR" -Message "file missing"
Write-LogEntry -Message "job finished"
Get-Content -Path (Join-Path $PSScriptRoot "app.log")Key points
- Log file: a plain text file where a script adds one line per event.
- Use Add-Content to add a line at the end of a log file. Older lines stay.
- Use a fixed label at the start of each line, like INFO or ERROR, so lines can be told apart by kind.
- Use Get-Content to read a log file back.
- Transcript: a full record of a session, started with Start-Transcript and stopped with Stop-Transcript.
In this example, a logging function takes a level and a message and appends a labelled line for each event. The job logs its start, an error, and its finish, and reading the file back shows all three lines.
Note
Log files hold plain lines you control. A transcript records the whole session instead.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which command adds a line to a file without erasing older lines?