Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# ContextLogger.psm1
$ContextStack = [System.Collections.Stack]::new()
function Invoke-InContext {
Param(
[ValidateNotNullOrEmpty()]
[string] $Name,
[ValidateNotNullOrEmpty()]
[scriptblock] $ScriptBlock
)
Write-Log "<$Name>"
$ContextStack.Push($Name)
$start = Get-Date
& $ScriptBlock | % {Write-Log $_} # format each line of output
$stop = Get-Date
$ContextStack.Pop()
Write-Log "</$Name> $($stop - $start)"
}
function Write-Log {
Param(
[ValidateNotNullOrEmpty()]
[string] $Message
)
$timestamp = Get-Date -Format 'MM/dd hh:mm:ss'
$contextArray = $ContextStack.ToArray()
[array]::Reverse($contextArray)
Write-Output "$timestamp [$($contextArray -join ">")] $Message"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment