PoshCode Archive  Artifact Content

Artifact fce4faacce6a08b794f7f450cb075434f05e4446db458a3fa390a905860f166b:

  • File Write-Log.ps1 — part of check-in [4e58443b98] at 2018-06-10 13:12:33 on branch trunk — Logging function for Powershell v2. Needed to address current Powershell logging limitations. See a discussion about said limitations here: http://jdhitsolutions.com/blog/2011/03/powershell-automatic-logging/#comment-2899 . (user: Andy Arismendi size: 4782)

# encoding: utf-8
# api: powershell
# title: Write-Log
# description: Logging function for Powershell v2. Needed to address current Powershell logging limitations. See a discussion about said limitations here: http://jdhitsolutions.com/blog/2011/03/powershell-automatic-logging/#comment-2899 .
# version: 0.1
# type: function
# author: Andy Arismendi
# license: CC0
# function: Write-Log
# x-poshcode-id: 2575
# x-derived-from-id: 2813
# x-archived: 2017-01-23T20:46:19
# x-published: 2012-03-22T10:10:00
#
# Logs to file and prints messages to the console and optionally logs to the system event logs. Note – admin rights are required when specifying the EventLogName parameter because the SourceExists method requires admin rights because it checks rights on the Security log. This limitation seems silly to me and if you think so as well get Microsoft to fix it by voting here: https://connect.microsoft.com/VisualStudio/feedback/details/293617/eventlog-sourceexists-always-fails-for-non-administrators#tabs .
# Feel free to add features as necessary.
#
function Write-Log {

	#region Parameters
	
		[cmdletbinding()]
		Param(
			[Parameter(ValueFromPipeline=$true,Mandatory=$true)] [ValidateNotNullOrEmpty()]
			[string] $Message,

			[Parameter()] [ValidateSet(“Error”, “Warn”, “Info”)]
			[string] $Level = “Info”,
			
			[Parameter()]
			[Switch] $NoConsoleOut,
			
			[Parameter()]
			[String] $ConsoleForeground = 'White',
			
			[Parameter()] [ValidateRange(1,30)]
			[Int16] $Indent = 0,

			[Parameter()]
			[IO.FileInfo] $Path = ”$env:temp\PowerShellLog.txt”,
			
			[Parameter()]
			[Switch] $Clobber,
			
			[Parameter()]
			[String] $EventLogName,
			
			[Parameter()]
			[String] $EventSource,
			
			[Parameter()]
			[Int32] $EventID = 1
			
		)
		
	#endregion

	Begin {}

	Process {
		try {			
			$msg = '{0}{1} : {2} : {3}' -f (" " * $Indent), (Get-Date -Format “yyyy-MM-dd HH:mm:ss”), $Level.ToUpper(), $Message
			
			if ($NoConsoleOut -eq $false) {
				switch ($Level) {
					'Error' { Write-Error $Message }
					'Warn' { Write-Warning $Message }
					'Info' { Write-Host ('{0}{1}' -f (" " * $Indent), $Message) -ForegroundColor $ConsoleForeground}
				}
			}

			if ($Clobber) {
				$msg | Out-File -FilePath $Path -Force
			} else {
				$msg | Out-File -FilePath $Path -Append
			}
			
			if ($EventLogName) {
			
				if (-not $EventSource) {
					$EventSource = ([IO.FileInfo] $MyInvocation.ScriptName).Name
				}
			
				if(-not [Diagnostics.EventLog]::SourceExists($EventSource)) { 
					[Diagnostics.EventLog]::CreateEventSource($EventSource, $EventLogName) 
		        } 

				$log = New-Object System.Diagnostics.EventLog  
			    $log.set_log($EventLogName)  
			    $log.set_source($EventSource) 
				
				switch ($Level) {
					“Error” { $log.WriteEntry($Message, 'Error', $EventID) }
					“Warn”  { $log.WriteEntry($Message, 'Warning', $EventID) }
					“Info”  { $log.WriteEntry($Message, 'Information', $EventID) }
				}
			}

		} catch {
			throw “Failed to create log entry in: ‘$Path’. The error was: ‘$_’.”
		}
	}

	End {}

	<#
		.SYNOPSIS
			Writes logging information to screen and log file simultaneously.

		.DESCRIPTION
			Writes logging information to screen and log file simultaneously. Supports multiple log levels.

		.PARAMETER Message
			The message to be logged.

		.PARAMETER Level
			The type of message to be logged.
			
		.PARAMETER NoConsoleOut
			Specifies to not display the message to the console.
			
		.PARAMETER ConsoleForeground
			Specifies what color the text should be be displayed on the console. Ignored when switch 'NoConsoleOut' is specified.
		
		.PARAMETER Indent
			The number of spaces to indent the line in the log file.

		.PARAMETER Path
			The log file path.
		
		.PARAMETER Clobber
			Existing log file is deleted when this is specified.
		
		.PARAMETER EventLogName
			The name of the system event log, e.g. 'Application'.
		
		.PARAMETER EventSource
			The name to appear as the source attribute for the system event log entry. This is ignored unless 'EventLogName' is specified.
		
		.PARAMETER EventID
			The ID to appear as the event ID attribute for the system event log entry. This is ignored unless 'EventLogName' is specified.

		.EXAMPLE
			PS C:\> Write-Log -Message "It's all good!" -Path C:\MyLog.log -Clobber -EventLogName 'Application'

		.EXAMPLE
			PS C:\> Write-Log -Message "Oops, not so good!" -Level Error -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "My Script"

		.INPUTS
			System.String

		.OUTPUTS
			No output.
			
		.NOTES
			Revision History:
				2011-03-10 : Andy Arismendi - Created.
	#>
}