繁体   English   中英

在 Powershell 中缩进写主机 output

[英]Indentation the Write-host output in Powershell

我正在编写一个脚本,它会在某个时候向控制台显示命令的输出(大约 20 行)。 为了使用我的脚本 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.

任何人都可以在这里帮助我提供线索。

示例代码:

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

您在脚本顶部仅使用一次填充运行Write-Host ,但是通过管道传输到脚本的 output 的Write-Host没有任何迹象表明您希望将填充与管道中的 output 连接起来。 您可以使用ForEach-Loop将 output 与所需的填充连接起来:

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

一个更简单的替代方法是使用PadLeft(..)字符串方法

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

另一个简单的替代方法是使用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