Skip to content

Instantly share code, notes, and snippets.

@r0ckbeard
Last active June 13, 2024 09:42
Show Gist options
  • Select an option

  • Save r0ckbeard/9b85086509bf25b99190a96dc125df32 to your computer and use it in GitHub Desktop.

Select an option

Save r0ckbeard/9b85086509bf25b99190a96dc125df32 to your computer and use it in GitHub Desktop.
Add logging to your powershell script
<#
.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: 31/05/2024
Original author: https://www.sharepointdiary.com/2019/06/create-log-file-in-powershell-script.html
#>
# 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,
[switch] $Warning,
[switch] $Error
)
Try {
# Add Content to the Log File
$TimeStamp = (Get-Date).ToString("yyyy/MM/dd HH:mm:ss:fff")
$Line = "$TimeStamp - $Message"
Add-Content -Path $Global:LogFilePath -Value $Line
# Set the default color and prefix
$Color = "Green"
$Prefix = "Message"
# Change color and prefix based on the parameters
if ($Warning.IsPresent) {
$Color = "Yellow"
$Prefix = "Warning"
} elseif ($Error.IsPresent) {
$Color = "Red"
$Prefix = "Error "
}
Write-Host "$Prefix : '$Line'" -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