簡體   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