目标是有一个进度条来监视外部进程,该进程将它所在的步骤写入监视文件。
如果我在循环中没有Start-Sleep
,它将产生有关无法转换无穷大的消息。这是为什么呢?我愿意有一些睡眠时间,但为什么需要它,睡眠所需的最短时间是多少?
PS C:srctpb> .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:srctpbMonitor-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
,等等。有时错误发生在步骤 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
}
虽然您的代码没有处理单个实体,但您的$currentcount
为零,因此您的天真 ETA 计算返回无穷大。您应该检查是否可以首先通过将当前计数与零进行比较来计算 ETA。
编辑:您已经完成了Get-Content
的隐式转换,该转换返回一个字符串数组,因此,如果您的文件中有一个换行符,则会出现转换错误并且$currentcount
保持为零,因此您除以零以获得无穷大。应使用[IO.File]::ReadAllText()
方法,或仅使用第一行(索引为 0)进行分析。或者,应使用-NoNewLine
标志写入文件以Out-File
cmdlet。