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.
#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)
echo $val1 $val2
if ($val1 -eq 'Fail')
"Wrong Input passed so it was logged as error" + $val1 | out-file -Filepath $logfile -append
$_.Exception.Message | out-file -Filepath $logfile -append
#Calling Logger function and passing parameters
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.