Script Logging Made Easy

by Nov 14, 2017

Beginning in PowerShell 5, you can use Start-Transcript in any host to log all the output created by your script. Here is how you can easily add logging capabilities to any script:

# add this: ############################ $logFile = "$PSScriptRoot\mylog.txt" Start-Transcript -Path $logFile -Append #########################################  "Hello" ($a = Get-Service) "I received $($a.Count) services." Write-Host "Watch out: direct output will not be logged!" # end logging ########################### Stop-Transcript ######################################### 

Simply add the code in the comment blocks to the start and end of your script. The log file will be created in the same folder the script resides in. Since $logFile uses $PSScriptRoot (the current folder of your script), always make sure you save the script and run it as a script. Else, $PSScriptRoot would be empty.

Just make sure your script outputs all the information you want to see in your logfile. By placing assignments into parenthesis, for example, PowerShell will not just assign the values but also echo them to the output.

One caveat: any input and output will be logged, except for messages written directly to the host using Write-Host. Such messages are always visible only to the user on screen.

Twitter This Tip! ReTweet this Tip!