Skip to content

Instantly share code, notes, and snippets.

@gravejester
Created October 30, 2024 17:44
Show Gist options
  • Save gravejester/8f9ad825d5933202bc2a73cd8dacf5c3 to your computer and use it in GitHub Desktop.
Save gravejester/8f9ad825d5933202bc2a73cd8dacf5c3 to your computer and use it in GitHub Desktop.
Write-LogMessage
function Write-LogMessage{
[CmdletBinding()]
param (
[Parameter()]
[string] $Message,
[Parameter()]
[string] $LogType = 'Info'
)
# use the built-in variable MyInvocation to get information about the calling script and the line number where it is called
$thisInvocation = (Get-Variable -Name 'MyInvocation' -Scope 1).Value
$callingScript = Split-Path -Leaf $thisInvocation.ScriptName
$scriptLineNumber = $thisInvocation.ScriptLineNumber
# Getting the PowerShell call stack to determine the "nearest" caller
# Use skipStackLevels to offset the first levels if used in a main function of module
$skipStackLevels = 2
$thisCallStack = (Get-PSCallStack)
$nearestCaller = $thisCallStack[(0+$skipStackLevels)]
# if the nearest caller and the calling script is the same, there is no need to write it twice
if ($nearestCaller.Command -eq $callingScript) {
$logMessage = "[$($callingScript):$($scriptLineNumber)] $($LogType.ToUpper()) $Message"
} else {
# here we are including the "actual" script line number for where the function was called in the script
$actualScriptLineNumber = $nearestCaller.InvocationInfo.ScriptLineNumber
$logMessage = "[$($callingScript):$($actualScriptLineNumber) > $($nearestCaller.FunctionName):$($scriptLineNumber)] $($LogType.ToUpper()) $Message"
}
Write-Output $logMessage
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment