A better logging method

Recently, I was asked to make some changes to lots of users in Active Directory. For output, they wanted a log of everything that was changed and a log of where changes failed. Of course, I wanted a third log with verbose output of everything that was happening so, if need be, I could go back and fix anything.

Another thing I wanted to do was not write 5 times a second. Rather than slow down the process of making changes to users, I wanted to collect strings for the logs and write out every time I collected X number of strings.

To do this, I created a new Type using C# code. I’ve been reading Windows PowerShell for Developers (Dougals Finke) which has been an eye-opener to say the least.

Here is the code I came up with…

This type compiles a “Logger” object which has a few properties and a few methods.

Logger Properties

Type Name Description
Int count the count of strings currently collected
Int MaxLines Number of lines (strings) to collect before being forced to write to the file.
Sting LogFile the logfile to write to (including path).

Logger Methods

Name Description
Logger (Constructor) Sets default values for the object
Add Adds a string to the object. All strings will be stored until either a “flush” command is called or the ‘maxLines’ limit is reached.
AppendLog Appends the collection of strings to the specified log file
Flush Writes all currently collected strings to the log file.
SetLogFile Sets the logfile to be written to.
SetMaxLines Sets the maximum number of lines to store until being forced to write to the log file.

Example usage


As a result of this, I was able to add this type to the script I was creating and create 3 logger objects:

Logging to any one log was easy, just use the example above. If I wanted to log to all the logs, like setting the start point for the running of the script I would do something like this:

The $logPrefix was a scriptblock I specified earlier on as

This way each line wold have a date/time header.

Leave a Reply