Write-LogMessage.psm1
Enum errorLevel { INFO SUCCESS WARNING ERROR DEBUG } $maxErrorLevelLength = ([System.Enum]::GetNames('errorLevel') | Measure-Object -Maximum -Property Length).Maximum $colorTable = @{ INFO = "Gray" SUCCESS = "Green" WARNING = "Yellow" ERROR = "Red" DEBUG = "DarkGray" } Function Write-LogMessage ([string]$logMessage, [errorLevel]$errorLevel = "INFO", [string]$logFilePath, [string]$stack = $null) { $timeStamp = Get-Date -Format yyyyMMddTHHmmssfffZ $writeString = [string]::Format("{0} :: {1} :: {2} {3}", $timeStamp, $errorLevel.ToString().PadRight($maxErrorLevelLength), $logMessage, $stack) Write-Host $writeString -ForegroundColor $colorTable["$errorLevel"] if ($logFilePath) { Try { [io.file]::OpenWrite($logFilePath).Close() $writeString | Out-File $logFilePath } Catch { $errorWriteString = [string]::Format("{0} :: {1} :: {2}", $timeStamp, "ERROR".PadRight($maxErrorLevelLength), "Cannot write to specified logFilePath: $logFilePath") Write-Host $errorWriteString -ForegroundColor "Red" } } } Export-ModuleMember -Function 'Write-LogMessage' |