Private/Log/Write-LogToFile.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
function Write-LogToFile() {
    <#
    .SYNOPSIS
        Outputs the Message to file. Helper function.

    .EXAMPLE
        Write-LogToFile -Header "Header" -Message "Message" -Severity $Severity
    #>


    [CmdletBinding()]
    [OutputType([void])]
    param(
        [Parameter(Mandatory=$false)]
        [string] 
        $Header, 
        
        [Parameter(Mandatory=$false)]
        [string[]] 
        $Message, 
        
        [Parameter(Mandatory=$false)]
        [int] 
        $Severity,

        [Parameter(Mandatory=$false)]
        [switch] 
        $PassThru
    )

    if (!(Get-Variable -Scope Script -Name LogConfiguration -ErrorAction SilentlyContinue)) {
        return
    }
    
    if (!$Script:LogConfiguration.LogFile) {
        return
    }

    $logFile = $Script:LogConfiguration.LogFile

    $strBuilder = New-Object System.Text.StringBuilder
    if ($Header) { 
        [void]($strBuilder.Append($Header))
    }
    if ($Message) {
        foreach ($msg in $Message) {
            [void]($strBuilder.Append($msg).Append("`r`n"))
        }
    }
        
    [System.IO.File]::AppendAllText($logFile, ($strBuilder.ToString()), [System.Text.Encoding]::Unicode)
}