I’m writing a large script that deploys an application. This script is based on several nested function calls.
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"
Check out this script http://poshcode.org/scripts/3386.html
If you load up that Write-Verbose wrapper, you can set
$WriteHostAutoIndent = $trueand then just call Write-Host and it will be indented based on stack depth. So given these functions as you defined them originally:With no changes, you can just dot-source a script file with that Write-Host wrapper function in it:
And then merely set the preference variable before you call your function:
Beautiful indented output, like magic 😉