Yet Another Write-Log Function

Yet Another Write-Log Function


While updating a script earlier this week, I wanted to spruce up my logging.  However, I didn’t have a handy function to incorporate that would allow me to both write to the screen (in various colors for the type of log entry being generated) and to a log file at the same time.  As I work on this, I’ll keep updating it to make it more useful.

The function I’ve put here allows you to choose to write to a log file, screen, or both, as well as color-coding the output based on the parameter LogLevel that you pass to the function.

function Write-Log(
    [string]$LogFile = (Get-Date -Format yyyy-mm-dd-hh-mm) + "_Logfile.txt",
    [ValidateSet("SUCCESS", "INFO", "WARN", "ERROR", "DEBUG")][string]$LogLevel
    $Message = $Message + $Input
    If (!$LogLevel) { $LogLevel = "INFO" }
    switch ($LogLevel)
        SUCCESS { $Color = "Green" }
        INFO { $Color = "White" }
        WARN { $Color = "Yellow" }
        ERROR { $Color = "Red" }
        DEBUG { $Color = "Gray" }
    } # End Switch $LogLevel
    if ($Message -ne $null -and $Message.Length -gt 0)
        $TimeStamp = [System.DateTime]::Now.ToString("yyyy-MM-dd HH:mm:ss")
        if ($LogFile -ne $null -and $LogFile -ne [System.String]::Empty)
            Out-File -Append -FilePath $LogFile -InputObject "[$TimeStamp] $Message"
        } # End If $LogFile
        if ($ConsoleOutput -eq $true)
            Write-Host "[$TimeStamp] [$LogLevel] :: $Message" -ForegroundColor $Color
        } # End If $ConsoleOutput
    } # End If $Message
} # End Function

Here are some examples:

If you wrap it inside a Try/Catch/Finally block:

     $Variable = <cmdlet> -ErrorAction Stop 
     $ErrorMessage = $_.Exception.Message 
     $FailedItem = $_.Exception.ItemName 
     Write-Log -Message $ErrorMessage -LogFile C:\temp\logfile.txt -LogLevel ERROR -ConsoleOutput
     Write-Log -Message $FailedItem -LogFile C:\temp\logfile.txt -LogLevel ERROR -ConsoleOutput 

Happy logging!

Published by Aaron Guilmette

Helping companies conquer inferior technology since 1997. I spend my time developing and implementing technology solutions so people can spend less time with technology. Specialties: Active Directory and Exchange consulting and deployment, Virtualization, Disaster Recovery, Office 365, datacenter migration/consolidation, cheese.

Reader Comments

  1. Great script. The only issue is the the default file name is wrong. It saves as the year-minute-day-hour-minute. Might also want to switch to 24-hour format.

    Line 3 should be:
    [string]$LogFile = (Get-Date -Format yyyy-MM-dd-HH-mm) + “_Logfile.txt”,

    The the first set of ‘M’s needs to be capital to get the month instead of the minute. Capitalize the ‘H’s for 24-hour format.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.