目标是有一个进度条监控将其所在步骤写入监视文件的外部进程。
如果我没有 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
}