Generating log output using Windows PowerShell

I previously wrote a post in regards to streaming output to a log file synchronously in Windows PowerShell, which was required for a specific reason to lock the file during the script invocation and event message generation.

I have since created an advanced function to provide the ability to generate event messages to the console and/or a log file where the action is to append to a specified log file.

Firstly, we will specify the parameters for the advanced function:

LogFile -specify the location to create or append to an existing log file. If no log file is specified events are generated in the current Windows PowerShell session only. The parent directory name of the location is validated to determine if the location exists.

Message – specify a description of the event message.

Level –  specify the severity of the event message, valid set of values are Info, Warning and Error. By default, the severity level of ‘Info’ is used.

Based on the level parameter value we will use a conditional statement to generate the event message text. The message generates a timestamp in the SortableDateTimePattern format.

Now, we will be invoking the script block which generates the event message. Firstly, conditional logic determines if a log file has been specified and if so does the file exist and if not create the file.

Now we will output the event message to both the log file specified and to the current Windows PowerShell console session. If no log file has been specified the event message will be generated in the console session only.

Below, is an example of the event generation produced by the advanced function when a log file is not specified.

Write-LogOutput

 

The Windows PowerShell function can be downloaded from https://github.com/dean1609/PowerShell/blob/master/Functions/Write-Log.ps1

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s