powershell indentation

You could use a wrapper function around write-host which used $MyInvocation to determine the stack depth to create a number of spaces to prefix the message.

Combine this with the -scope ‹n› parameter of Get-Variable to pull out each calling level… something like the showstack function adapted from Windows PowerShell In Action (Payette, 1st Ed):

function ShowStack {
  trap { continue; }
  0..100 | Foreach-Object {
    (Get-Variable -scope $_ 'MyInvocation').Value.PositionMessage -replace "`n"
  }
}

You'll need the maximum value of $_ in the pipeline before Get-Variable fails for scope count being too high.


Check out this script http://poshcode.org/scripts/3386.html

If you load up that Write-Verbose wrapper, you can set $WriteHostAutoIndent = $true and then just call Write-Host and it will be indented based on stack depth. So given these functions as you defined them originally:

function myFn()
{
   Write-Host "Start of myfn"
   myFnNested
   Write-Host "End of myfn"
}
function myFnNested()
{
   Write-Host "Start of myFnNested"
   Write-Host "End of myFnNested"
}

With no changes, you can just dot-source a script file with that Write-Host wrapper function in it:

C:\PS> . C:\Users\Jaykul\Documents\WindowsPowerShell\PoshCode\3386.ps1

And then merely set the preference variable before you call your function:

C:\PS> $WriteHostAutoIndent = $true
C:\PS> myFn
  Start of myfn
    Start of myFnNested
    End of myFnNested
  End of myfn

Beautiful indented output, like magic ;-)

Tags:

Powershell