缩进 Powershell 中的 Write-host 输出

Indentation the Write-host output in Powershell

我正在编写一个脚本,它会在某个时候向控制台显示命令的输出(大约 20 行)。为了保持我其余脚本输出的格式,我希望命令的输出向左缩进一点。我尝试使用带有一些手动空格和 -NoNewLine 的 Write-host,然后是我的命令的输出,但它只在输出的第一行添加空格,其余行仍然出现在位置 0.

谁能帮我提供线索。

示例代码:

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

你 运行 Write-Host 在你的脚本的顶部只有一次填充,但是 Write-Host 管道输出到你的脚本没有任何迹象表明您想要将填充与管道的输出连接起来。您可以使用 ForEach-Loop 将输出与所需的填充连接起来:

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

一个更简单的替代方法是使用 PadLeft(..) string method:

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

另一个简单的替代方法是使用 Format operator -f as Theo 评论:

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