Powershell – Log file creator

Have you ever had a Powershell script that needs to log information?  Me too!

I’m currently involved in a large Powershell project and was fed up of writing the same old thing over and over.  So here’s my first foray into re-usable Powershell code – a logger!

By default, the logger will append the current date to the logname as well as give the logname the .log extension and place it in ‘append’ mode however all of the defaults can be turned off through switches.  It will also create the log location if it does not already exist.

There is also a switch to auto-write the current date and time to the log as well as change the file extensions to .err or .dat and if you need more it’s easy enough to edit the code.

Here’s a couple of  examples of it in action, though it’s fully documented with comment based help:

#Add a log start time
Write-Log -message "Start processing at: " -LogName test -LogLocation C:\Powershell\Logs -LogDateTime
#Write a log named LogData with the message contained in the variable $MyError at the default location of C:\Powershell\Logs and give the log the extension of .err, also do not append the date to the name of the log
write-log -message $MyError -LogName "Log Errors" -LogExtension .err -DoNotAddDateToLogName
#Overwrite the specified log with a message showing the date and time the log was overwritten
Write-Log -message "Overwritten at: " -LogName test -LogLocation \\Server1\Share\Logs -Overwrite -LogDateTime

I’ll be using this a lot in my latest project and can see this coming in handy for many other scripts in the future.

The function is called: Write-Log and you can find it here on github in my ‘Tools’ folder.

Be the first to comment

Leave a Reply