Logging with powershell

Building a script is one thing, but building a script to automate a process is an entirely different challenge. You simply aren’t there to monitor the script to look for issues when a task runs automatically. There are a million ways to handle logging, you can do this after each task in a script. But what happens when you really need some logic and intelligence in your logging? Adding that block of code every time to write something to a log is a bit silly.

When I know I need lots of logging and error handling I usually build a function similar to the below function. This lets you pass the data you need to be displayed, but also displays static data that needs to be updated each time the function runs.

Here is what the logs output looks like:

You might ask why I have an elapsed time section of the log, well this is a great way to optimize your code. Obviously the above example only takes 1.5 seconds, but in a more elaborate script this can let you find calls or code that is running slowly. If your task is time sensitive this can be very helpful.

This is a very simple example of how to build a logging function, you can also add my mailer function to this logging function to build an alerting mechanism.

0 comments… add one

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.