Condividi tramite


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[]]$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!

Comments

  • Anonymous
    February 12, 2018
    The comment has been removed
    • Anonymous
      February 12, 2018
      The comment has been removed