Write-SNSLog.ps1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
function Write-SNSLog { <# .Synopsis Write-SNSLog writes a message to a specified log file with the current time stamp. .DESCRIPTION The Write-SNSLog function is designed to add logging capability to other scripts. In addition to writing output and/or verbose you can write to a log file for later debugging. The configuration variable $LogFilePath can be used to oweride the default logfile scoutnetSync.log. .PARAMETER Message Message is the content that you wish to add to the log file. .PARAMETER Level Specify the criticality of the log information being written to the log (i.e. Error, Warning, Informational) #> [CmdletBinding()] Param ( [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("LogContent")] [string]$Message, [Parameter(Mandatory=$false)] [ValidateSet("Error","Warn","Info")] [string]$Level="Info" ) Process { if (-not [String]::IsNullOrWhiteSpace($script:SNSConf.LogFilePath)) { # If attempting to write to a log file in a folder/path that doesn't exist create the file including the path. if (!(Test-Path $script:SNSConf.LogFilePath)) { Write-Verbose "Creating $($script:SNSConf.LogFilePath)." New-Item $script:SNSConf.LogFilePath -Force -ItemType File > $null } } else { Write-Warning "Log file path is empty. No log file will be created." } # Format Date for our Log File $FormattedDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss" # Write message to error, warning, or verbose pipeline and specify $LevelText switch ($Level) { 'Error' { Write-Error $Message $LevelText = 'ERROR:' } 'Warn' { Write-Warning $Message $LevelText = 'WARNING:' } 'Info' { Write-Verbose $Message $LevelText = 'INFO:' } } if (-not [String]::IsNullOrWhiteSpace($script:SNSConf.LogFilePath)) { # Write log entry to $script:LogPath "$FormattedDate $LevelText $Message" | Out-File -FilePath $script:SNSConf.LogFilePath -Append -Encoding UTF8 } } } |