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:
Write-Host " " -NoNewLine
D:\Opatch\patch.bat apply 124423.zip | Write-Host
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) }
Which also works via member access enumeration:
('test', 'test', 'test').PadLeft(20)
Another way to do it 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}', $_) }