【问题标题】:Overwrite PowerShell output strings onto the same line将 PowerShell 输出字符串覆盖到同一行
【发布时间】:2018-09-17 15:11:20
【问题描述】:

我有一段 PS 代码,它获取 7-Zip 提取输出并将其过滤掉,因此只打印百分比“%”进度更新行。我已经设法将其减少到仅输出百分比:

& $7ZipPath "x" $filePath "-o$extractionPath" "-aos" "-bsp1" | out-string -stream | Select-String -Pattern "\d{1,3}%" -AllMatches | ForEach-Object { $_.Matches.Value } | Write-Host -NoNewLine

此时控制台输出如下所示:

0%1%5%9%14%17%20%23%26%31%37%43%46%48%50%52%54%56%59%61%63%65%67%70%72%74%76%78%80%81%82%83%85%86%87%89%90%91%92%94%95%96%97%98%99%

有没有办法将这些输出保持在同一位置,同一行,使它们相互覆盖?这很棘手,因为输出是从 7-Zip 应用程序传输的。恐怕我不能使用Expand-Archive,因为我正在处理.7z 文件

非常感谢!

【问题讨论】:

    标签: powershell pipe 7zip


    【解决方案1】:

    您可以使用 .Net System.Console 类:

    [System.Console]::SetCursorPosition(0, [System.Console]::CursorTop)
    

    所以你的代码必须是:

    & $7ZipPath "x" $filePath "-o$extractionPath" "-aos" "-bsp1" | out-string -stream | Select-String -Pattern "\d{1,3}%" -AllMatches | ForEach-Object { $_.Matches.Value } | foreach {
        [System.Console]::SetCursorPosition(0, [System.Console]::CursorTop) 
        Write-Host $_ -NoNewLine
    }
    

    注意:只要下一个输出的长度等于或大于您的情况,这就是您所需要的。否则你必须先清除最后的输出。

    【讨论】:

    • 如果您不想插入可能会阻止提示覆盖进度输出的最终回车符,可以将-End { Write-Host } 添加到最终的 ForEach-Object 中。我相信您也可以根据需要使用[Console]::Write()[Console]::WriteLine() 而不是Write-Host。
    【解决方案2】:

    marsze's helpful answer 效果很好,但还有一个更简单的替代方法,它使用 CR 字符 ("`r") 将光标位置重置到行首。

    这是一个在同一行打印数字 1 到 10 的简单演示:

    1..10 | ForEach-Object { Write-Host -NoNewline "`r$_"; Start-Sleep -Milliseconds 100 }
    

    [Console]::Write(...) 代替 Write-Host -NoNewline ... 也有效,正如Bacon Bits 指出的那样。

    同样的限制也适用:如果之前的输出行恰好是longer,额外的字符linger

    要解决这个问题,你必须将任何输出行填充到控制台窗口缓冲区宽度的长度:

    'loooooooong', 'meeedium', 'short' | ForEach-Object { 
       Write-Host -NoNewline ("`r{0,-$([console]::BufferWidth)}" -f $_)
       Start-Sleep -Milliseconds 500 
    }
    

    【讨论】:

      猜你喜欢
      • 2014-12-22
      • 2023-03-17
      • 2014-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-28
      相关资源
      最近更新 更多