Simple PowerShell Script Logging

Here’s a very simple logging mechanism I’ve used before.

Disclaimer: I’m sure someone, somewhere has written a better one – if so please leave a link the comments.

Overview:  I wanted a simple logging function that would both display to the screen, and also write to disk.  I also wanted to be able to set the display color on output.

The logging function is simple and writes to disk and to the screen.


Note: To make the above example easy and simple, I put the log function at the top.
In Powershell, functions must always come before the code that calls them.
An easy way to get around this is to wrap your code in a function and call that function at the very bottom of the ps1 file
Like this:

Note that the $logFile line was intentionally left on top, since it needs to be available globally.

I have a video that covers the above scripts, as well as Start-Transcript and Stop-Transcript

6 thoughts on “Simple PowerShell Script Logging

  1. SIr, I am new in power shell and download one script which copy one folder to multiple computer on network running fine and given the out on command Line good
    can I save the output in csv or txt file.

    1. yes, you can send the output to a variable then output it to the screen with write-host and on another line you can dump it to a file with $var | out-file (filename and other flags as needed)
      another option is start-transcript which records a log of all screen activity.
      use get-help start-transcript and get-help out-file for more info on these.

  2. Bug alert: The $message parameter definition does not restrict it to be string. If, for example, $message is a hashtable then the log file content will be different from what will be on the screen.
    Fix: either declare $message as string or pipe it to a local string and use the local string.

  3. Do you have any Powershell snippet that can post log entries to AWS Cloudwatch logs using Write-CWLLogEvent cmdlet?

Leave a Reply