Simple log function

Today I’d like to share a┬ásimple PowerShell log function.

This is one of my first posh scripts I customized. Originally it’s not from me, I just made it prettier and added the color. I know there are functions out there that create great logs for cmtrace.exe, but at the moment I’m happy with this one. This is my personal replacement for Write-Host, it will echo my message to the screen (in color) and will send it to the log file at the same time.

First of all you need 2 variables for path and filename. Put it into the same file as the function itself, otherwise make it global. You could put it into the function as well. My goal was to make it independent from the function and to not use it as a parameter. The usage of the function should be simple.

Here’s the simple Write-Log function:

Here’s how we’ll use it. You could use all the colors that Write-Host accepts. If you omit the parameter, it’ll just print it in white:

Since log files grow bigger with time, here’s the function that splits and archives the log. Change the length value accordingly:

Just run the function at the top of every script:

 

Leave a Comment