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[]]$Message, [string]$LogFile = (Get-Date -Format yyyy-mm-dd-hh-mm) + "_Logfile.txt", [switch]$ConsoleOutput, [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:
Try { $Variable = <cmdlet> -ErrorAction Stop } Catch { $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 } Finally { }
Happy logging!


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.
Nice catch!
Line 9 should be:
If (!$LogLevel) { $LogLevel = “INFO” }
Instead of: $LogLexvel
Ahh, yes! Victim of the copy/paste/bang on the keyboard yet again. Updated. Thanks!