PowerShell – Write-Log Function

In most of my more advanced scripts or applications there’s a need to log information, warnings, and errors, preferrably to both the console and to a log file. I therefore find it very helpful to reuse a logging function I wrote a while back, every time the need arises.

Usage

[CmdletBinding()]
param ()
# Cmdletbinding is required to run script with -Verbose

# Import the log function, or declare it directly here
. ".\Write-Log.ps1"

# Write an informational message
Write-Log -Message "Script invoked as user: $env:USERNAME"

# Write a warning
Write-Log -Warning "This is a warning"

# Handle errors
try
{
    # Some code that may fail
    Write-Log2
}
catch
{
    Write-Log -ErrorObj $_
}

Output

The function Write-Log

function Write-Log
{
    [CmdletBinding()]
    param
    (
        [String]$Message,
        [String]$Warning,
        [System.Management.Automation.ErrorRecord]$ErrorObj,
        [String]$LogFolderPath = "$PSScriptRoot\Logs",
        [String]$LogFilePrefix = 'Log'
    )

    $Date = Get-Date -Format "dd_MMMM_yyyy"
    $Time = Get-Date -Format "HH:mm:ss.f"
    $LogFile = "$LogFolderPath\$LogFilePrefix`_$Date.log"

    if (-not (Test-Path -Path $LogFolderPath))
    {
        [Void](New-Item -ItemType Directory -Path $LogFolderPath -Force)
    }

    if (-not (Test-Path -Path $LogFile))
    {
        [Void](New-Item -ItemType File -Path $LogFile -Force)
    }

    $LogMessage = "[$Time] "

    if ($PSBoundParameters.ContainsKey("ErrorObj"))
    {
        $LogMessage += "Error: $ErrorObj $($ErrorObj.ScriptStackTrace.Split("`n") -join ' <-- ')"
        Write-Error -Message $LogMessage
    }
    elseif ($PSBoundParameters.ContainsKey("Warning"))
    {
        $LogMessage += "Warning: $Warning"
        Write-Warning -Message $LogMessage
    }
    else
    {
        $LogMessage += "Info: $Message"
        Write-Verbose -Message $LogMessage
    }

    Add-Content -Path $LogFile -Value "$LogMessage"
}

Conclusion

The Write-Log function is a simple and quick way to better handle logging in your scripts and other PowerShell creations. Hope you found this useful 🙂

Leave a Reply