public/New-Log.ps1

FUNCTION New-Log {
    <#
        .DESCRIPTION
        Adds an entry into a current log file.
        .PARAMETER Message
        The message to add to the log file.
        .PARAMETER Tab
        The nunber of tabs to add to a message to indent the text.
        .PARAMETER Type
        The type of message to add to the log. Acceptable values are INF, ERR, WRN, STR, END.
        .PARAMETER Path
        The path to the log file being worked. This value should be in $Global:LogFilePath set by New-LogFile.
        .EXAMPLE
        PS> New-Log -Type 'STR'
        Adds line to log file indicating the execution of script start.
        .EXAMPLE
        PS> New-Log -Message 'Someting occured to log'
        Adds a new line to the log with default typr of INF.
        .EXAMPLE
        PS> New-Log -Message 'An error has occured' -Type 'ERR'
        Adds a new line to the log with type of error and a message.
        .EXAMPLE
        PS> New-Log -Type 'END'
        Adds a new line to the log with type of end.
        ** This also clears the global variable to the log file location. New-LogFile will need to be executed again.
        .NOTES
        Author: Adam Branham
        Date: 20240919
    #>

    PARAM(
        [Parameter(Mandatory = $false)]
        [string]$Message,
        [Parameter(Mandatory = $false)]
        [int]$Tab,
        [Parameter(Mandatory = $false)]
        [ValidateSet('INF', 'ERR', 'WRN', 'STR', 'END')]
        [string]$Type = 'INF',
        [Parameter(Mandatory = $false)]
        [System.IO.FileInfo]$Path = $Global:LogFilePath,
        [Parameter(Mandatory = $false)]
        [string]$Console = $Global:LogFileConsole
    )
    BEGIN {
        IF (-NOT(Test-Path -Path $Path)) {
            THROW 'Log file missing, ensure New-LogFile has been executed first.'
        }
        $NowTime = (Get-Date).ToString('hh:mm:ss tt')
        $Tabs = "`t" * $Tab
    }
    PROCESS {
        SWITCH ($Type) {
            'STR' {
                $LogMessage = "[$NowTime][STR] Execution Starting"
            }
            'END' {
                $LogMessage = "[$NowTime][END] Execution End"
            }
            'ERR' {
                $LogMessage = "[$NowTime][ERR] $Tabs$Message"
            }
            'INF' {
                $LogMessage = "[$NowTime][INF] $Tabs$Message"
            }
            'WRN' {
                $LogMessage = "[$NowTime][WRN] $Tabs$Message"
            }
            DEFAULT {
                $LogMessage = "[$NowTime][UNK] [Message type not found] $Message"
            }
        }
    }
    END {
        Add-Content -Path $Global:LogFilePath -Value $LogMessage
        IF ($Console -eq $true) { Write-Host $LogMessage }
        IF ($Type -eq 'END') {
            Clear-Variable -Name 'LogFilePath' -Scope 'Global'
            Clear-Variable -Name 'LogFileConsole' -Scope 'Global'
        }
    }
}