Photo by luis gomes on Pexels.com

Issue :

We all write lengthy scripts and schedule them but we forget the crucial part of logging. Without logging, we will not have any visibility if script ran without any error.

Fix

This code will help you to enable any of your script to do logging. Copy below text or download it from below link :

# This is the folder, where you want to write logs
cd $home\desktop
# Convert today's date to string
$date = (Get-Date).ToString('yyyy-MM-dd')
# Constructing complete file name with path.
$logFile = "$home\desktop\Log_" + $date + ".txt"
# Path of the actual script and sending warning and error to logfile.
.\yourscript.ps1 3>&1 2>&1 | Out-file -filePath $logFile
https://github.com/jhasaurab/learntechfuture/blob/master/Logging_script.ps1

You might be wondering about 3>&1 2>&1, These are the combination of streams and redirection, which helps to you to redirect warning, error etc to a file. Please use below reference table to create the combination as you need.

Reference

Streams

Stream #Description
1Success Stream
2Error Stream
3Warning Stream
4Verbose Stream
5Debug Stream
6Information Stream
*All Streams

Operators

OperatorDescriptionSyntax
>Send specified stream to a file.n>
>>Append specified stream to a file.n>>
>&1Redirects the specified stream to the Success stream.n>&1

Thank you for reading, I hope it was helpful.