When writing larger scripts, logging is a must, so in this post I will share a simple function for logging PowerShell script. PowerShell scripts can easily be written without any kind of help content, documentation, commenting, or logging. Functionally, these scripts will sometimes work just fine, but what happens it failed in some case? You soon find yourself pulling your hair out trying to troubleshoot and debug this script in the most inefficient way possible. So logging the error is the best practice to handle the huge script.
One way to build in some kind of monitoring and troubleshooting assistance is through logging.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#This creates a log file with a date and time stamp $logfile = "C:\EMS\dotnet-helpersErrorLog_$(get-date -format `"yyyyMMdd_hhmmsstt`").txt" #this is our logging function, it must appear above the code where you are trying to use it. function logger($val1 , $val2) { try { echo $val1 $val2 if ($val1 -eq 'Fail') { "Wrong Input passed so it was logged as error" + $val1 | out-file -Filepath $logfile -append } } catch { $_.Exception.Message | out-file -Filepath $logfile -append } } #Calling Logger function and passing parameters logger 'Dotnet-helpers.com','Pass' logger 'Dotnet-helpers.eu','Fail' |
OUTPUT
What do you think?
I hope you have an idea of how to create simple log files for handling the issue. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.