
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 |
---|---|
1 | Success Stream |
2 | Error Stream |
3 | Warning Stream |
4 | Verbose Stream |
5 | Debug Stream |
6 | Information Stream |
* | All Streams |
Operators
Operator | Description | Syntax |
---|---|---|
> | Send specified stream to a file. | n> |
>> | Append specified stream to a file. | n>> |
>&1 | Redirects the specified stream to the Success stream. | n>&1 |
Thank you for reading, I hope it was helpful.