,

Quick and Easy Logging In PowerShell

No matter the programming language, having clear logging is always useful when running into issues later on down the road. PowerShell makes creating logs quick and easy with the Start-Transcript cmdlet. The way this cmdlet works in PowerShell is that it transcribes every command that is run through the script to a text file at the designated path. This is the general format that I use with this cmdlet:

1$LogName = "log-$(Get-Date -Format MMdd).log"

Start-Transcript -Append -Path $PSScriptRoot\Logs\$LogName

try {
Write-Host 'Do something for the logging'
"[INFO] - Did Something"
} catch {
"[ERROR] - Something Went Wrong"
}

Stop-Transcript

You can choose any format that you want with the naming of the log as long as the name ends in .log that way File Explorer knows that it is a text file. To make the log file easier to search through after the script runs I utilize a Try\Catch. With the Try\Catch, I can added searchable keywords within the log file such as Info, Error, and Warning. This makes it where someone that doesn’t know PowerShell can look through the log files and know what was going on through the script.

You then need to end the script with the Stop-Transcript cmdlet in order for PowerShell to know that the logging is done. Now that the script has done its logging, lets see what the log file looks like afterwards.

Image of the log file showing the script information
Log File Without Errors

In this image we can see all of the system information. This information can be reduced with the -UseMinimalHeader parameter. This shows what the console output was as well as the [INFO] message that we put in the Try\Catch. When there is an error within the script the log file will show the Try\Catch message that we specified, as well as the error information that get outputted to the console.

Conclusion

Using this cmdlet can help you quickly and easily create log files within your script and save you time in the long run. If you want to learn more about this cmdlet, check out the Microsoft Documentation.

  1. ↩︎