Created
January 23, 2015 22:30
-
-
Save tibmeister/f4336c6e97b6b5706001 to your computer and use it in GitHub Desktop.
Powershell Logging Module that incorporates logging to a file and to the Windows Event log in a structured manner. When using it from code it acts like a file stream when it really isn't.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
.SYNOPSIS | |
This module is to provide common functionality for logging within scripts | |
.DESCRIPTION | |
This module is to provide common functionality for logging within scripts. This provides a consistent framework to be used | |
universally across all PowerShell scripting platforms. | |
.NOTES | |
Version: v1.2 | |
Author: Jody Whitlock | |
Date: January 23, 2015 | |
LastModified: January 23, 2015 | |
Purpose/Change: Initial module development | |
#> | |
$global:CurrentOpenLog = '' | |
[string]$global:EventLogMessage = '' | |
#region Internal Functions | |
Function Get-CallingPath | |
{ | |
<# | |
.SYNOPSIS | |
Internal function to return the calling script's path | |
#> | |
if((Get-Variable MyInvocation).CommandOrigion -match "Internal") | |
{ | |
$retVal = $PWD | |
} | |
else | |
{ | |
$retVal = (Get-Variable MyInvocation).Value.PSScriptRoot | |
} | |
return $retVal | |
} | |
Function Get-LogNameFromScript | |
{ | |
<# | |
.SYNOPSIS | |
Internal function to return a log file name based on the calling script's name and the current date. | |
#> | |
$retVal = [IO.Path]::GetFileNameWithoutExtension((Get-Variable MyInvocation).Value.ScriptName) | |
if(!($retVal) -or ($retVal -match "Logging")) | |
{ | |
$retVal = "CLI" | |
} | |
return "$($retVal)_$((Get-Date).ToString('MM-dd-yyyy')).log" | |
} | |
Function Get-EventSourceFromScript | |
{ | |
$retVal = [IO.Path]::GetFileNameWithoutExtension((Get-Variable MyInvocation).Value.ScriptName) | |
if(!($retVal) -or ($retVal -match "Logging")) | |
{ | |
$retVal = "CLI" | |
} | |
return $retVal | |
} | |
#endregion | |
Function Start-Log | |
{ | |
<# | |
.SYNOPSIS | |
Creates log file | |
.DESCRIPTION | |
Creates log file with path and name that is passed. Once created, writes initial logging data | |
.PARAMETER LogPath | |
Path of where log is to be created. If this is ommitted, a log directory will be created under the calling scripts path | |
.PARAMETER LogName | |
Name of log file to be created. If ommitted it will be the calling script name and current date appended. | |
.OUTPUTS | |
Log file name | |
.EXAMPLE | |
Start-Log -LogPath "C:\Windows\Temp" -LogName "Test_Script.log" | |
#> | |
[CmdletBinding()] | |
Param | |
( | |
[Parameter(Mandatory=$false)] | |
[string]$LogPath = "$(Get-CallingPath)\Log", | |
[Parameter(Mandatory=$false)] | |
[string]$LogName = "$(Get-LogNameFromScript)" | |
) | |
Process | |
{ | |
$sFullPath = $LogPath + "\" + $LogName | |
$global:CurrentOpenLog = $sFullPath | |
#Check if file exists and creates it if it doesn't | |
If(!(Test-Path -Path $sFullPath)) | |
{ | |
if(!(Test-Path -Path $LogPath)) | |
{ | |
New-Item -Path $LogPath -ItemType Directory | |
} | |
New-Item -Path $LogPath -Name $LogName -ItemType File | |
} | |
Add-Content -Path $sFullPath -Value "***************************************************************************************************" | |
Add-Content -Path $sFullPath -Value "Started processing at $([DateTime]::Now)." | |
Add-Content -Path $sFullPath -Value "***************************************************************************************************" | |
Add-Content -Path $sFullPath -Value "" | |
$EventLogMessage += "Started processing at $([DateTime]::Now)." | |
$EventLogMessage += "`n" | |
#Write to screen for debug mode | |
Write-Verbose "***************************************************************************************************" | |
Write-Verbose "Started processing at $([DateTime]::Now)." | |
Write-Verbose "***************************************************************************************************" | |
Write-Verbose "" | |
return "$($LogPath)\$($LogName)" | |
} | |
} | |
Function Write-Log | |
{ | |
<# | |
.SYNOPSIS | |
Writes to a log file | |
.DESCRIPTION | |
Appends a new line to the end of the specified log file | |
.PARAMETER LogPath | |
Full path of the log file you want to write to. Example: C:\Windows\Temp\Test_Script.log | |
If ommitted it will use the CurrentOpenLog file variable | |
.PARAMETER LineValue | |
Mandatory. The string that you want to write to the log | |
.EXAMPLE | |
Write-Log -LogPath "C:\Windows\Temp\Test_Script.log" -LineValue "This is a new line which I am appending to the end of the log file." | |
#> | |
[CmdletBinding()] | |
Param | |
( | |
[Parameter(Mandatory=$false)] | |
[string]$LogPath = $global:CurrentOpenLog, | |
[Parameter(Mandatory=$true)] | |
[string]$LineValue, | |
[Parameter(Mandatory=$false)] | |
[switch]$EventLog | |
) | |
Process | |
{ | |
if($EventLog) | |
{ | |
$EventLogMessage += $LineValue | |
$EventLogMessage += "`n" | |
} | |
if($LogPath) | |
{ | |
Add-Content -Path $LogPath -Value $LineValue | |
} | |
#Write to screen for debug mode | |
Write-Verbose $LineValue | |
} | |
} | |
Function Write-LogError | |
{ | |
<# | |
.SYNOPSIS | |
Writes an error to a log file | |
.DESCRIPTION | |
Writes the passed error to a new line at the end of the specified log file | |
.PARAMETER LogPath | |
Full path of the log file you want to write to. Example: C:\Windows\Temp\Test_Script.log | |
If ommitted it will use the CurrentOpenLog file variable | |
.PARAMETER ErrorDesc | |
Mandatory. The description of the error you want to pass (use $_.Exception) | |
.PARAMETER ExitGracefully | |
Mandatory. Switch runs Log-Finish and then exits script | |
.EXAMPLE | |
Write-LogError -LogPath "C:\Windows\Temp\Test_Script.log" -ErrorDesc $_.Exception -ExitGracefully | |
#> | |
[CmdletBinding()] | |
Param | |
( | |
[Parameter(Mandatory=$false)] | |
[string]$LogPath = $global:CurrentOpenLog, | |
[Parameter(Mandatory=$true)] | |
[string]$ErrorDesc, | |
[Parameter(Mandatory=$false)] | |
[switch]$EventLog | |
) | |
Process | |
{ | |
if($EventLog) | |
{ | |
$EventLogMessage += $LineValue | |
$EventLogMessage += "`n" | |
} | |
if($LogPath) | |
{ | |
Add-Content -Path $LogPath -Value "Error: An error has occurred [$ErrorDesc]." | |
} | |
#Write to screen for debug mode | |
Write-Verbose "Error: An error has occurred [$ErrorDesc]." | |
if($EventLog) | |
{ | |
Stop-Log -LogPath $LogPath -EventLog -EntryType Error | |
} | |
else | |
{ | |
Stop-Log -LogPath $LogPath | |
} | |
} | |
} | |
Function Stop-Log | |
{ | |
<# | |
.SYNOPSIS | |
Write closing logging data & exit | |
.DESCRIPTION | |
Writes finishing logging data to specified log and then exits the calling script | |
.PARAMETER LogPath | |
Mandatory. Full path of the log file you want to write finishing data to. Example: C:\Windows\Temp\Test_Script.log | |
.PARAMETER NoExit | |
Optional. If this is set to True, then the function will not exit the calling script, so that further execution can occur | |
.EXAMPLE | |
Stop-Log -LogPath "C:\Windows\Temp\Test_Script.log" | |
.EXAMPLE | |
Stop-Log -LogPath "C:\Windows\Temp\Test_Script.log" -NoExit | |
#> | |
[CmdletBinding(DefaultParameterSetName="file")] | |
Param | |
( | |
[Parameter(Mandatory=$false, | |
ParameterSetName="file")] | |
[string]$LogPath = $global:CurrentOpenLog, | |
[Parameter(Mandatory=$false, | |
ParameterSetName="file")] | |
[switch]$NoExit, | |
[Parameter(Mandatory=$true, | |
ParameterSetName="eventlog")] | |
[Parameter(Mandatory=$false, | |
ParameterSetName="file")] | |
[switch]$EventLog, | |
[Parameter(Mandatory=$false, | |
ParameterSetName="eventlog")] | |
[string]$EventLogName = "Windows PowerShell", | |
[Parameter(Mandatory=$false, | |
ParameterSetName="eventlog")] | |
[System.Diagnostics.EventLogEntryType]$EntryType = "Information", | |
[Parameter(Mandatory=$false, | |
ParameterSetName="eventlog")] | |
[int]$EventID = 1, | |
[Parameter(Mandatory=$false, | |
ParameterSetName="eventlog")] | |
[string]$EventSource = (Get-EventSourceFromScript) | |
) | |
Process | |
{ | |
Add-Content -Path $LogPath -Value "" | |
Add-Content -Path $LogPath -Value "***************************************************************************************************" | |
Add-Content -Path $LogPath -Value "Finished processing at [$([DateTime]::Now)]." | |
Add-Content -Path $LogPath -Value "***************************************************************************************************" | |
#Write to screen for debug mode | |
Write-Verbose "" | |
Write-Verbose "***************************************************************************************************" | |
Write-Verbose "Finished processing at [$([DateTime]::Now)]." | |
Write-Verbose "***************************************************************************************************" | |
if($EventLog) | |
{ | |
$EventLogMessage += "Finished processing at [$([DateTime]::Now)]." | |
$EventLogMessage += "`n" | |
if(!($EventSource)) | |
{ | |
$EventSource = "PowerShell" | |
} | |
if(!(Get-EventLog -LogName $EventLogName -Source $EventSource -ErrorAction SilentlyContinue)) | |
{ | |
New-EventLog -LogName $EventLogName -Source $EventSource | |
} | |
Write-EventLog -LogName $EventLogName -EntryType $EntryType -EventId $EventID -Message $LineValue -Source $EventSource | |
} | |
#Exit calling script if NoExit has not been specified or is set to False | |
If(!($NoExit)) | |
{ | |
Exit | |
} | |
} | |
} | |
Export-ModuleMember -Function Start-Log | |
Export-ModuleMember -Function Write-Log | |
Export-ModuleMember -Function Write-LogError | |
Export-ModuleMember -Function Stop-Log |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment