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

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


    [CmdletBinding()]
    [OutputType([void])]
    param(
        [string] 
        $Header, 
        
        [string[]] 
        $Message, 
        
        [LogLevel] 
        $Severity
    )
    
    if (!$LogConfiguration.LogFile) {
        return
    }
    if (![System.IO.Path]::IsPathRooted($LogConfiguration.LogFile)) {
        # we need to set absolute path to log file as .NET working directory would be c:\windows\system32
        $LogConfiguration.LogFile = Join-Path -Path ((Get-Location).ProviderPath) -ChildPath $LogConfiguration.LogFile
    }

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