I am a supporter of
St. Joseph's hospice.
 If you find this site useful or if it helped you, consider a small donation to
St. Joseph's, please.

Information on
St. Joseph's

JustGiving - Sponsor me now!

 

Write-Log

<#
.SYNOPSIS
    This script/function enables logging within PowerShell scripts.

.DESCRIPTION
    This script/function enables logging within PowerShell scripts.

Global variables which control features of this script are:
[string]$global:LogFilePath - The text file into which all messages are getting written
[string]$global:SubName - The name of the script calling this Log script
[int]$global:LogLevel - The log level: 1 loggs everything, 2 omits INFOs,
3 omits INFOs and WARNings, 4 only logs severity ALWAYS messages

The contents of a log file will look like:

INFO: BERND-PC\Bernd 2020-02-16 12:19:36 [zip_and_copy.ps1] - Log started
INFO: BERND-PC\Bernd 2020-02-16 12:19:36 [zip_and_copy.ps1] - Log finished

.PARAMETER Message
    The message you want to log.

.PARAMETER Severity
    The severity of the message. This can be 'INFO', 'WARN', 'FATAL', or 'ALWAYS'.
If global variable LogLevel is 1 then messages with all severities will be logged.
If LogLevel is 2 then INFO messages will not be logged.
If LogLevel is 3 then INFO and WARN messages will not be logged.
If LogLevel is 4 then INFO, WARN and FATAL messages will not be logged.

.EXAMPLE
# Initialize global logging variables and make log script known
$global:SubName = $MyInvocation.MyCommand.Name
$global:LogLevel = 1
$global:LogFilePath = "$PSScriptRoot\Logs\LogFile_" + $SubName + "_" +
(Get-Date -UFormat "%Y%m%d") + ".txt"
    . "$PSScriptRoot\Write-Log.ps1"

.EXAMPLE
# How to call
Write-Log -Message 'Log started' -Severity INFO
If(-Not (Test-path $ArchiveFile)) {Write-Log -Message "$ArchiveFile was not created" -Severity FATAL}

.NOTES
    Version Date        Who                   What
    1.0     16-Feb-2020 Bernd Plumhoff        Initial Version

#>

#Requires -Version 4
Set-StrictMode -Version Latest
function Write-Log {
    [CmdletBinding()]
    param(
        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$Message,
 
        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [ValidateSet('INFO','WARN','FATAL','ALWAYS')]
        [string]$Severity = 'INFO'
    )
switch ($Severity)
{
'INFO' {If ([int]$global:LogLevel -gt 1) {Exit} }
'WARN' {If ([int]$global:LogLevel -gt 2) {Exit} }
'FATAL' {If ([int]$global:LogLevel -gt 3) {Exit} }
'ALWAYS' { <# Will always be logged! #> }
}
if (-Not (Test-Path -IsValid $global:LogFilePath)) {$global:LogFilePath = "$PSScriptRoot\Logs\LogFile.txt"}
[string]$Output = $Severity + ": " + [System.Security.Principal.WindowsIdentity]::GetCurrent().Name +
" " + (Get-Date -UFormat "%Y-%m-%d %T") + " [" + $global:SubName + "] - " + $Message
    Write-Output $Output | Out-File -append $global:LogFilePath
}

Sulprobil   Get it done   Contact   Disclaimer   Impressum   Download