powershell indentation

Posted by Steve B on Server Fault See other posts from Server Fault or by Steve B
Published on 2011-06-30T08:15:31Z Indexed on 2011/06/30 8:24 UTC
Read the original article Hit count: 179

Filed under:

I'm writing a large script that deploys an application. This script is based on several nested functions call.

Is there any way to "ident" the output based on the depth ?

For example, I have :

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"
}


Write-Host "Start of myscript"
Write-Host "End of myscript"

The output of the script will be :

Start of myscript
Start of myfn
Start of myfnNested
End of myFnNested
End of myFn
End of myscript

What I want to achieve is this output :

Start of myscript
  Start of myfn
    Start of myfnNested
    End of myFnNested
  End of myFn
End of myscript

As I don't want to hardly code the number of spaces (since I does not know the depth level in complex script), how can I simply reach my goal ?

Maybe something like this ?

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


Write-Host "Start of myscript"
Write-Host "End of myscript"

© Server Fault or respective owner

Related posts about powershell