Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save r0ckbeard/560501912d2e45944d33f1e8709a3dfe to your computer and use it in GitHub Desktop.

Select an option

Save r0ckbeard/560501912d2e45944d33f1e8709a3dfe to your computer and use it in GitHub Desktop.
Add logging with CMTrace compatible formatting
<#
.SYNOPSIS
This script initializes a global log file path and provides a function to log messages with different severity levels (Message, Warning, Error).
.DESCRIPTION
The script defines a global variable for the log file path, which is created based on the script's root path or a custom path if provided.
It includes a Log-Message function to log messages to the file and display them in the console with appropriate colors.
The script logs the start time and the end time along with the total execution time.
.PARAMETER LogFilePath
A global variable defining the path of the log file. It can be set to a custom path if needed.
.PARAMETER Message
The message to be logged.
.PARAMETER Warning
A switch parameter to indicate if the message is a warning.
.PARAMETER Error
A switch parameter to indicate if the message is an error.
.EXAMPLE
.\YourScript.ps1
This runs the script and logs the start time, sample messages, and the end time with the execution duration.
Example included below.
.NOTES
Author: Sebastian Rock
Date: 13/06/2024
Original author: https://www.sharepointdiary.com/2019/06/create-log-file-in-powershell-script.html
Addition from: https://janikvonrotz.ch/2017/10/26/powershell-logging-in-cmtrace-format/
#>
# Define the global variable for the log file path, if executed in ISE with "Run selection" it uses the else part
if ($PSScriptRoot) {
$Global:LogFilePath = Join-Path -Path $PSScriptRoot -ChildPath ("$(Get-Date -Format 'yyyy-MM-dd_HH-mm-ss').log")
} else {
New-Item -Path "C:\Temp\Logs" -ItemType Directory -Force
$Global:LogFilePath = "C:\Temp\Logs\Log_$(Get-Date -Format 'yyyy-MM-dd_HH-mm-ss').log"
}
# If you want to set a custom log file path, uncomment the line below and set your path
# $Global:LogFilePath = "C:\Path\To\Your\CustomLogFile.log"
Function Log-Message {
param (
[Parameter(Mandatory=$true)] [string] $Message,
[string] $Component = $MyInvocation.MyCommand.Name,
[switch] $Warning,
[switch] $Error
)
Try {
# Determine log type
if ($Warning.IsPresent) {
$Type = "Warning"
$TypeInt = 2
} elseif ($Error.IsPresent) {
$Type = "Error "
$TypeInt = 3
} else {
$Type = "Info "
$TypeInt = 1
}
# Create a log entry in CMTrace format
$Content = "<![LOG[$Message]LOG]!>" + `
"<time=`"$(Get-Date -Format "HH:mm:ss.ffffff")`" " + `
"date=`"$(Get-Date -Format "M-d-yyyy")`" " + `
"component=`"$Component`" " + `
"context=`"$([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)`" " + `
"type=`"$TypeInt`" " + `
"thread=`"$([Threading.Thread]::CurrentThread.ManagedThreadId)`" " + `
"file=`"`">"
# Write the line to the log file
Add-Content -Path $Global:LogFilePath -Value $Content
# Set the default color
$Color = "Green"
if ($Warning.IsPresent) {
$Color = "Yellow"
} elseif ($Error.IsPresent) {
$Color = "Red"
}
Write-Host "$Type : '$Message'" -ForegroundColor $Color
} Catch {
Write-Host "Error: $_.Exception.Message" -ForegroundColor Red
}
}
#Log Start Time of the Script
$StartTime = (Get-Date)
Log-Message "Script Started at: $(Get-date -format 'yyyy/MM/dd HH:mm:ss')"
#### Your script starts here ####
Log-Message "Green message"
Log-Message "Yellow warning" -Warning
Log-Message "Red error" -Error
#### Your script ends here ####
#Log End Time
$EndTime = (Get-Date)
Log-Message "Script Ended at: $(Get-date -format 'yyyy/MM/dd HH:mm:ss')"
#Get Elapsed Time
$ElapsedTime = ($EndTime - $StartTime).Seconds
Log-Message "Script Execution Time: $ElapsedTime Seconds"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment