写入标准输出时保持进度条可见

问题描述 投票:0回答:1

我有一个 PowerShell 安装脚本,它会调用其他几个脚本,这些脚本会在安装过程中写入

stdout
。通过查看
stdout
无法确定安装脚本已经进行了多远。因此,我想显示一个进度条。

我尝试使用

Write-Progress
,但是一旦将某些行写入
stdout
,进度条就会向上移动并消失在视野之外。

有没有办法让进度条粘在终端顶部,而不离开视图?写入

stdout
的内容可能会描绘出价值,所以我不想为了保持进度条可见而丢弃输出。

powershell progress-bar
1个回答
0
投票

今天我遇到了类似的情况,发现你的问题没有解决。 我想出了这样的东西。希望能帮助到你。 基本上,我用长时间运行的任务启动后台作业并保存其 ID。我每 2 秒执行一次

Receive-Job
以获得其输出,然后重新打印我的
Write-Progress

Function Replace-GhorsePlots {
    Write-Progress -Id 1 -Activity "Replacing Ghorse Plots" -Status "Starting" -PercentComplete 0
    $PlotCount = Get-GhorsePlots | Measure-Object | Select-Object -ExpandProperty Count
    $i=0
    Get-GhorsePlots | ForEach-Object {
        $PlotFile = $_
        Write-Progress -Id 1 -Activity "Replacing Ghorse Plots" -Status ("{0} of {1} Plots replaced. Replacing {2}" -f $i, $PlotCount, $PlotFile.Name) -PercentComplete ($i / $PlotCount * 100)
        #Remove on Ghorse Plot and instead plot one Bladebit Plot
        $NewPlotDestPath=$PlotFile.DirectoryName.Replace("/ghorse", "/bladebit")
        # Write-Host("Replacing " + $PlotFile.FullName + " with a new plot in " + $NewPlotDestPath)
        Remove-Item -Path $PlotFile.FullName -Confirm:$false
        # Create PlotJob to reference to the ID later
        $PlotJob = Start-Job -ArgumentList @($NewPlotDestPath) -ScriptBlock {
            param(
                $NewPlotDestPath
            )
            # To be sure we have the Module on the new process
            Import-Module -Name ChiaShell -DisableNameChecking
            # This lasts really long and prints a lot on stdout
            Invoke-BladebitPlotter -DestDir $NewPlotDestPath -Count 1
            # Start-Sleep -Seconds 1
        }

        #Wait for PlotJob to finish and show progress
        do {
            Start-Sleep -Seconds 2
            $PlotJob = Get-Job -Id $PlotJob.Id
            Write-Progress -Id 1 -Activity "Replacing Ghorse Plots" -Status ("{0} of {1} Plots replaced. Replacing {2}" -f $i, $PlotCount, $PlotFile.Name) -PercentComplete ($i / $PlotCount * 100)
            Receive-Job -Job $PlotJob
        } while ($PlotJob.State -eq "Running")
        # Finished -> Remove
        Remove-Job -Id $PlotJob.Id
        $i++
    }
    Write-Progress -Id 1 -Activity "Replacing Ghorse Plots" -Status "Finished" -PercentComplete 100 -Completed
    
}
© www.soinside.com 2019 - 2024. All rights reserved.