Modules/Logging.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
function Write-Log 
{ 
    <#
        .SYNOPSIS
            Log Message with given level, default level is "Information"
        
        .DESCRIPTION
            Log Message with given level, default level is "Information"

        .PARAMETER Message
            Message to be logged

        .PARAMETER LogLevel
            Possible values are 'Error', 'Warning', 'Information', 'Verbose', 'Debug'

        .EXAMPLE
            Write-Log "Everything went ok!" -LogLevel Information
            Write-Log "Result is $Result" -LogLevel Debug
            Write-Log "Could not stop service" -LogLevel Error
    #>

    [CmdletBinding()] 
    Param(
        [Parameter(Mandatory=$true, Position=0)]
        [ValidateNotNullOrEmpty()]
        [string]$Message,
        [Parameter(Mandatory=$false, Position=1)]
        [ValidateSet('Error', 'Warning', 'Information', 'Verbose', 'Debug')]
        [string]$LogLevel = 'Information'
      )
 
    Begin 
    { 
        # Set VerbosePreference to Continue so that verbose messages are displayed.
        $VerbosePreference = 'Continue' 
        $InformationPreference = 'Continue' 
        $DebugPreference = 'Continue'
    } 
    Process 
    { 
        switch ($LogLevel) {
            'Error' {
                Write-Error $Message
            }
            'Warning' {
                Write-Warning $Message
            }
            'Information' {
                Write-Information $Message
            }
            'Verbose' {
                Write-Verbose $Message
            }
            'Debug' {
                Write-Debug $Message
             }
            default       { throw "Invalid log level: $_" }
          }
    } 
    End 
    { 
    } 
}