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

sqougxex  于 2023-11-18  发布在  Shell
关注(0)|答案(1)|浏览(143)

我有一个PowerShell安装脚本,它会调用其他几个脚本,这些脚本会在stdout的过程中写入stdout。通过查看stdout,无法确定安装脚本已经沿着了多远。因此,我想显示一个进度条。
我尝试使用Write-Progress,但只要将某些行写入stdout,进度条就会向上移动并消失在视图中。
有没有一种方法可以让进度条粘在终端的顶部,而不会超出视图?写入stdout的内容可能会表现出价值,所以我不想为了保持进度条可见而丢弃输出。

zxlwwiss

zxlwwiss1#

今天我有一个类似的情况下,发现你的问题没有得到解决。我想出了这样的东西。希望它有帮助。基本上我开始一个后台作业与我的长期运行的任务和保存其id。我做Receive-Job每2秒得到它的输出,然后我重新打印我的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
    
}

字符串

相关问题