Home Powershell Logging
Post
Cancel

Powershell Logging

Log file Function

This function creates a logfile if it’s not already created and outputs to the screen in a verbose pattern.

It has an Error, Warn and Info function to either stop the code or just for info.

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
function Write-Log 
{ 
    [CmdletBinding()] 
    Param 
    ( 
        [Parameter(Mandatory=$true, 
                   ValueFromPipelineByPropertyName=$true)] 
        [ValidateNotNullOrEmpty()] 
        [Alias("LogContent")] 
        [string]$Message, 
 
        [Parameter(Mandatory=$false)] 
        [Alias('LogPath')] 
        [string]$Path='.\log.log', 
         
        [Parameter(Mandatory=$false)] 
        [ValidateSet("Error","Warn","Info")] 
        [string]$Level="Info", 
         
        [Parameter(Mandatory=$false)] 
        [switch]$NoClobber 
    ) 
 
    Begin 
    { 
        # Set VerbosePreference to Continue so that verbose messages are displayed. 
        $VerbosePreference = 'Continue' 
    } 
    Process 
    { 
            # If the file already exists and NoClobber was specified, do not write to the log. 
            if ((Test-Path $Path) -AND $NoClobber) { 
                Write-Error "Log file $Path already exists, and you specified NoClobber. Either delete the file or specify a different name." 
                Return 
                } 
    
            # If attempting to write to a log file in a folder/path that doesn't exist create the file including the path. 
            elseif (!(Test-Path $Path)) { 
                Write-Verbose "Creating $Path." 
                $NewLogFile = New-Item $Path -Force -ItemType File 
                } 
    
            else { 
                # Nothing to see here yet. 
                } 

        # Format Date for our Log File 
        $FormattedDate = Get-Date -Format "dd-MM-yyyy HH:mm:ss" 
 
        # Write message to error, warning, or verbose pipeline and specify $LevelText 
        switch ($Level) { 
            'Error' { 
                Write-Error $Message 
                $LevelText = 'ERROR:' 
                } 
            'Warn' { 
                Write-Warning $Message 
                $LevelText = 'WARNING:' 
                } 
            'Info' { 
                Write-Verbose $Message 
                $LevelText = 'INFO:' 
                } 
            } 
         
        # Write log entry to $Path 
        try{
          "$FormattedDate $LevelText $Message" | Out-File -FilePath $Path -Append 
        }
        catch{
            
            Write-Warning ("Unable to write in the log file: " + $_.exception.message)
        }
    } 
    End 
    { 
    } 
}

How to use the logfunction

Create a variable with the location of the log file

1
$LogFilePath = ".\logfile.log"

Then Simply add this anywhere in the code with the log message

1
Write-Log -Message $msg -Path $LogFilePath -Level Info

Example

1
2
$msg = "Added user to group XYZ"
Write-Log -Message $msg -Path $LogFilePath -Level Info
This post is licensed under CC BY 4.0 by the author.
Trending Tags