简体   繁体   English

在 Powershell 中缩进写主机 output

[英]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.我正在编写一个脚本,它会在某个时候向控制台显示命令的输出(大约 20 行)。 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.为了使用我的脚本 output 的 rest 保持格式,我希望命令的 Output 向左缩进一点。 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. 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.您在脚本顶部仅使用一次填充运行Write-Host ,但是通过管道传输到脚本的 output 的Write-Host没有任何迹象表明您希望将填充与管道中的 output 连接起来。 You could use a ForEach-Loop to concatenate the output with your desired padding:您可以使用ForEach-Loop将 output 与所需的填充连接起来:

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

A much easier alternative is to use the PadLeft(..) string method :一个更简单的替代方法是使用PadLeft(..)字符串方法

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

Another easy alternative would be to use the Format operator -f as Theo commented:另一个简单的替代方法是使用Format 运算符-f正如Theo评论的那样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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