PowerShell Logging Functions

I have been working on automating my organizations Active Directory/Exchange user provisioning, and needed a method to easily log what actions are taken.  To accomplish this, I decided to write a couple PowerShell logging functions that I could integrate into my other functions for creating the user, creating the mailbox, generating approval emails, and assigning groups.  The functions I came up with are Start-Log, Write-Log, and Stop Log.

My goal was to create a log file with some basic information (time, username, and machine calling the function) with Start-Log.  Then, Write-Log will write a line to the file with a timestamp, username, and specified log message.  Finally, Stop-Log will right a tail line with the same information as Start-Log.  Here are the functions:

Start-Log:

Nothing super complex going on here.  Here is the basic flow:

  1. Takes a couple strings as input, one as the path to store the log in, one as the name of the log file
  2. Checks if a file with that name already exists, renaming it with .bak if it does.  If a .bak exists, it will overwrite it.
  3. Creates the log file and adds a header to it using environment variables

Write-Log:

This one is even simpler, just takes a path and a message and writes a line, including a timestamp and username, if the file exists.

Stop-Log:

This one is the same as Write-Log, except it only needs a path and writes a couple tail lines if the file exists.

Here is an example of what the output looks like:

As usual, latest versions can be found on GitHub.

Leave a Reply

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