0

目标是有一个进度条监控将其所在步骤写入监视文件的外部进程。

如果我没有 aStart-Sleep在循环中,它将产生有关无法转换无穷大的消息。为什么是这样?我愿意有一些睡眠时间,但为什么需要它以及睡眠所需的最短时间是多少?

PS C:\src\t\pb> .\Monitor-Progress2.ps1 -TotalCount 5 -WatchFile wf.txt -Verbose
New-TimeSpan : Cannot bind parameter 'Seconds'. Cannot convert value "∞" to type "System.Int32". Error: "Value was either too large or too small for an Int32."
At C:\src\t\pb\Monitor-Progress2.ps1:46 char:37
+ ... an -Seconds (($ts.TotalSeconds / $currentCount) * ($TotalCount - $cur ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidArgument: (:) [New-TimeSpan], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.NewTimeSpanCommand

这是代码。同样的问题出现在 PowerShell 5.1 和 6.0 上。我要做的就是运行它ECHO>wf.txt 1,然后ECHO>wf.txt 2等等。有时错误发生在第二步,但有时在第三步。

[CmdletBinding()]
Param (
    [Parameter(Mandatory=$true)]
    [int]$TotalCount

    ,[Parameter(Mandatory=$true)]
    [ValidateScript({Test-Path $_ -PathType 'Leaf'})]
    [string]$WatchFile
)

$currentcount = 0
$previouscount = $currentcount

$starttimestamp = Get-Date

while ($currentcount -lt $TotalCount) {
    $currentcount = [int32](Get-Content $WatchFile)

    ### Write-Verbose $currentcount

    if (($currentcount -lt $TotalCount) -and ($currentcount -ne $previouscount)) {
        $ts = $(Get-Date) - $starttimestamp

        ### Write-Verbose $ts.TotalSeconds
        ### Write-Verbose $currentcount
        ### Write-Verbose ($ts.TotalSeconds / $currentcount)
        ### Write-Verbose ($TotalCount - $currentcount)
        ### Write-Verbose (($ts.TotalSeconds / $currentcount) * ($TotalCount - $currentcount))

        $et = New-TimeSpan -Seconds (($ts.TotalSeconds / $currentCount) * ($TotalCount - $currentcount))
        $runningstatus = "Long process running for {0:%d} days {0:%h} hours {0:%m} minutes {0:%s} seconds" -f $ts
        $completionstatus = "Estimated completion in {0:%d} days {0:%h} hours {0:%m} minutes {0:%s} seconds" -f $et
        Write-Progress -Activity $runningstatus `
            -Status $completionstatus `
            -percentComplete ($currentcount / $TotalCount*100)
        $previouscount = $currentcount
    }

    #Start-Sleep -Seconds 1
}
4

1 回答 1

0

虽然您的代码没有处理单个实体,但您$currentcount的值为零,因此您的天真 ETA 计算返回无穷大。您应该首先通过将当前计数与零进行比较来检查是否可以计算 ETA。

编辑:你已经完成了一个隐式转换,Get-Content它返回一个字符串数组,所以如果你的文件中有一个换行符,你会得到一个转换错误并且你$currentcount仍然为零,因此你除以零以获得无穷大。您应该使用[IO.File]::ReadAllText()方法,或者仅使用第一行(索引为 0)进行解析。或者您应该将带有-NoNewLine标志的文件写入Out-Filecmdlet。

于 2017-12-04T12:52:35.380 回答