如何缩进powershell中的命令输出

How to indent command output in powershell

我正在尝试以漂亮的缩进形式显示 ping 命令输出...但是,似乎无法正确格式化它....

我想要这样的输出:

Result: 
        Pinging google.com [216.58.208.110] with 32 bytes of data:
        Reply from 216.58.208.110: bytes=32 time=223ms TTL=61
        Reply from 216.58.208.110: bytes=32 time=129ms TTL=61

        Ping statistics for 216.58.208.110:
            Packets: Sent = 2, Received = 2, Lost = 0 (0% loss),
        Approximate round trip times in milli-seconds:
            Minimum = 129ms, Maximum = 223ms, Average = 176ms

但是 Powershell 似乎不允许我在不弄乱输出的情况下这样做

这是我正在使用的代码块

$ping = & { Invoke-Expression "ping  -n 2 google.com" } 2>&1 | Out-String
Write-Host ""
Write-Host "$ping" -ForegroundColor Green
Write-Host ""

哪种作品,但没有缩进....

当我尝试不同的变体试图获得缩进时,他们都失败了......

$ping = & { Invoke-Expression "ping  -n 2 google.com" } 2>&1 | Out-String
Write-Host ""
Write-Host "      $ping" -ForegroundColor Green
Write-Host ""

结果:这种方法有效,但只有第一行缩进了...其余的输出不是...

$ping = & { Invoke-Expression "ping  -n 2 google.com" } 2>&1 | Format-Table 
Write-Host ""
Write-Host "    $ping" -ForegroundColor Green
Write-Host ""

结果:Powershell 吐出 windows 错误并且 table 从未出现....

$ping = & { Invoke-Expression "ping  -n 2 google.com" } 2>&1
foreach ($line in $ping ) {
  Write-Host ""
  Write-Host "      $line" -ForegroundColor Green
  Write-Host ""
}

结果:输入的前 3 行左对齐,其余行按预期缩进...

$ping = & { Invoke-Expression "ping  -n 2 google.com" } 2>&1 
$indent = $ping.PadLeft(50)
Write-Host ""
Write-Host "    $indent" -ForegroundColor Green
Write-Host ""

结果:就好像我在 word 中点击了右对齐按钮,输出一团糟...

$ping = & { Invoke-Expression "ping  -n 2 google.com" } 2>&1
foreach ($line in $ping ) {
    Write-Host ""
    Write-Host "`t $line" -ForegroundColor Green
    Write-Host ""
}

结果:选项卡从未出现,输出左对齐,没有缩进...

有人可以指出我方法的错误吗...过去几天一直让我发疯...

提前致谢!

x

大多数命令行工具一次输出一行,因此删除 Out-String 并在每行前面加上所需数量的白色前缀space:

$ping = & { ping -n 2 google.com } 2>&1
$ping |ForEach-Object {"    $_"}

如果工具输出多行字符串(或者如果您非常喜欢 Out-String),您可以使用 -replace 正则表达式运算符添加前导 space 在字符串的开头和任何换行符之后 - 无论您有多个单行字符串还是一个(或多个)多行字符串,这都将起作用:

PS ~> $ping = & { ping -n 2 google.com } 2>&1 |Out-String
PS ~> $ping -replace '(?<=^|\n)',"`t"

        Pinging google.com [142.251.36.14] with 32 bytes of data:
        Reply from 142.251.36.14: bytes=32 time=12ms TTL=117
        Reply from 142.251.36.14: bytes=32 time=13ms TTL=117

        Ping statistics for 142.251.36.14:
            Packets: Sent = 2, Received = 2, Lost = 0 (0% loss),
        Approximate round trip times in milli-seconds:
            Minimum = 12ms, Maximum = 13ms, Average = 12ms

正则表达式模式 (?<=^|\n) 匹配字符串开头 (^) 或文字换行符 (\n) 之后的任何位置。 "`t" 是文字 TAB 的转义序列,因此我们告诉 PowerShell 在输入字符串中的任何此类位置插入一个制表符。