I'm working on a simple function to indent my log files. The premise is extremely basic:
Set-LogIndent will add an indent to all following log commands
Set-LogOutdent will remove an indent to all following log commands
Now, of course one way of doing this is to just have
Log-Message "Before we indent"
Set-LogIndent
Log-Message "Hello World"
Set-LogOutdent
Log-Message "After we indent"
The log / console output would then be:
Before we indent
- Hello World
After we indent
The problem with this is twofold:
The Code blocks can be quite big so you lose track of where the Indent/Outdent commands are
When you are nesting them you often can't tell which Outdent command refers to which Indent
..
So my solution for this was to create a "wrapper" function, much like a Using statement
function Use-LogIndent {
param (
$ScriptBlock
)
Set-LogIndent
& $ScriptBlock
Set-LogOutdent
}
You could then use the code as follows:
Use-LogIndent {
Log-Message "Hello World"
}
This works GREAT .. until .. I nest them
Use-LogIndent {
Log-Message "Hello World"
Use-LogIndent {
Log-Message "Saying Hello World again!"
}
}
In this final one, I find the entire Script Block is either spat out into the console as text - or the $ScriptBlock parameter is $null
Am I not following the correct pattern here? Is there an easier / better way of doing this?
Log-Messagechange its behavior? Nesting scriptblocks with a "wrapper" function is perfectly valid, none of the code you've shown leads to the behavior you describe - so the problem is likely inLog-Messagetry / finallyto ensureSet-LogOutdentis always called, even if the scriptblock produces a script-terminating error (exception):try { & $ScriptBlock } finally { Set-LogOutdent }