Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Indentation the Write-host output in Powershell

I am writing a script that will at some point display the output(Around 20 lines) of a command to the console. To maintain the formatting with rest of my script output, i want the Output of the command to be indented a bit to the left. I tried to use a Write-host with some manual spaces, and -NoNewLine, followed by the output of my command, but it only adds spaces to the first line of the output and rest of the lines still appear from the position 0.

Can anyone please help me out with clues here.

Sample Code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Write-Host "          " -NoNewLine
D:\Opatch\patch.bat apply 124423.zip | Write-Host

>Solution :

You’re running Write-Host with the padding just once at the top of your script, however the Write-Host piped to the output of your script does not have any indication that you want to concatenate the padding with the output from pipeline. You could use a ForEach-Loop to concatenate the output with your desired padding:

$padding = "       "
'test', 'test', 'test' | ForEach-Object { Write-Host ${padding}$_ }

A much easier alternative is to use the PadLeft(..) string method:

'test', 'test', 'test' | ForEach-Object { $_.PadLeft(20) }

Another easy alternative would be to use the Format operator -f as Theo commented:

'test', 'test', 'test' | ForEach-Object { '{0,10}' -f $_ }
# OR
'test', 'test', 'test' | ForEach-Object { [string]::Format('{0,10}', $_) }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading