数学意外地产生无穷大'∞'

时间:2017-12-04 11:31:00

标签: powershell powershell-v5.0 powershell-v6.0

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

如果循环中没有Start-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等。有时错误发生在第二步,但有时会发生在第3步。

[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
}

1 个答案:

答案 0 :(得分:0)

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

编辑:您已完成Get-Content的隐式转换,它会返回数组字符串,因此,如果您的文件中有换行符,则会出现转换错误,并且{{1} 1}}保持为零,因此你除以零得到无穷大。您应该使用$currentcount方法,或仅使用第一行(索引为0)进行解析。或者您应该使用[IO.File]::ReadAllText()标记写入-NoNewLine cmdlet文件。