A simple logging function

This is a very simple logging function that I use in quite a bit of my code. I used to write logging information to a variable, and the wrote the variable to a file at the end of the script, but this doesn’t work well if you abort the script while processing (Ctrl-C) or if the script fails before it finishes due to an unforeseen error.

So, this function was born. Note that it doesn’t have a lot of error checking – you should check to make sure that the log file location is writable BEFORE calling the function (it will create the file if it doesn’t exist, but only if it can write to that location).

I usually call it like this (with a sortable timestamp):

$timeStamp = (Get-Date -Format s).Replace(':', '-')
$LogFile = ".\someLogFileName-$($timeStamp).log"

Note that I’m modifying the ‘sortable’ time/date format to remove the colon since you can’t have a colon in a file name.
As I have it above, it writes the log file to the current directory – but you can specify any valid filespec.

Leave a Reply

Your email address will not be published. Required fields are marked *