简体   繁体   中英

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:

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

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}', $_) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM