0

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:

  1. The Code blocks can be quite big so you lose track of where the Indent/Outdent commands are

  2. 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?

8
  • 1
    How are the Set-* functions defined? Commented May 15 at 22:22
  • 3
    There is no issue invoking nested functions in a scriptblock, your code as is should work just fine. I believe you need to provide a reproducible example of the issue. Commented May 15 at 22:44
  • 1
    So then how does Log-Message change 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 in Log-Message Commented May 15 at 22:46
  • 1
    Ok I hate coding sometimes ... I thought I was on to something. I commented all of Log-Message back to just a simple Write-Host .. AND IT WORKED. Then I slowly uncommented the functionality back, testing it as I went ... and ... it STILL WORKS !!! ???? Honestly no idea what the F was going on with this.. if anything I'm now even more confused! Commented May 16 at 6:42
  • 2
    Another suggestion: Use try / finally to ensure Set-LogOutdent is always called, even if the scriptblock produces a script-terminating error (exception): try { & $ScriptBlock } finally { Set-LogOutdent } Commented May 16 at 9:16

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.