如何在PowerShell中使循环每1秒计数1?

时间:2019-01-05 17:20:18

标签: powershell

我写了一个从1到20的代码,开始睡眠5个,然后继续。但是我需要计数器每秒计数1,因此整个循环需要25秒才能运行。现在只需要7到9秒。

$counter = 0
for ($counter -lt 20)
{
    Start-sleep 0
    $Counter++
    write-host $Counter
    if ($Counter -eq 10)
    {
        Start-sleep 5
    }
    If ($Counter -eq 20)
    {
        Break
    }
}

2 个答案:

答案 0 :(得分:0)

秒表可以用来保持时间更好。 一旦达到阈值(10秒),就必须重新启动它。

此方法的唯一缺点是,如果您处于7秒,然后在循环中执行需要5秒的操作,那么您将在12秒时达到10秒的循环(因此,为什么使用-ge作为条件)。

$StopWatch = New-Object -TypeName 'System.Diagnostics.Stopwatch'
$StopWatch.Start()

For ($Counter = 0;$counter -lt 20) {
    Write-Host '.' -NoNewline
    Start-Sleep -Milliseconds 500 

    if ($StopWatch.Elapsed.Seconds -ge 10) {
        Write-Host ''
        Write-Host "$($StopWatch.Elapsed.Seconds) seconds elapsed... " -ForegroundColor Cyan
        $StopWatch.Restart()
    }

}

或者,您可以将主要内容放入工作中,因此即使需要2分钟才能完成,仍然可以正确执行10秒循环。

$MainStuffAction = {
   Start-Sleep -Seconds 20
    Write-Host 'Completed !'
}


$MainStuff = Start-Job -ScriptBlock $MainStuffAction 
$StopWatch = New-Object -TypeName 'System.Diagnostics.Stopwatch'
$StopWatch.Start()

while($true) {
    if ($StopWatch.Elapsed.Seconds -ge 10) {
        Write-Host '10 seconds elapsed!' 

        # We only restart the stopwatch at the end to get our full 10 seconds
        $StopWatch.Restart()
    } 
    elseif ($MainStuff.State -ne 'Running') {
        $MainStuff | Receive-Job
        $MainStuff = Start-Job -ScriptBlock $MainStuffAction 
    }

    Start-Sleep -Milliseconds 500

}

答案 1 :(得分:0)

这是另一种方法。它使用while构造并显示$Counter$Stopwatch值,因此您可以清楚地看到它是否在执行您想要的操作。 [咧嘴]

$Stopwatch = [System.Diagnostics.Stopwatch]::new()
$Stopwatch.Start()

$Counter = 0
# correct for off-by-one
$Threshold = 19
while ($Counter -le $Threshold)
    {
    Start-Sleep -Seconds 1
    $Counter ++
    'Counter = {0:D2}, Seconds = {1:D2}' -f $Counter, $Stopwatch.Elapsed.Seconds
    if ($Counter -eq 10)
        {
        Start-Sleep -Seconds 5
        '{0} {1:D2} Seconds' -f (' ' * 15), $Stopwatch.Elapsed.Seconds
        }
    }

$Stopwatch.Stop()
$Stopwatch.Elapsed.TotalSeconds

输出...

Counter = 01, Seconds = 01
Counter = 02, Seconds = 02
Counter = 03, Seconds = 03
Counter = 04, Seconds = 04
Counter = 05, Seconds = 05
Counter = 06, Seconds = 06
Counter = 07, Seconds = 07
Counter = 08, Seconds = 08
Counter = 09, Seconds = 09
Counter = 10, Seconds = 10
                15 Seconds
Counter = 11, Seconds = 16
Counter = 12, Seconds = 17
Counter = 13, Seconds = 18
Counter = 14, Seconds = 19
Counter = 15, Seconds = 20
Counter = 16, Seconds = 21
Counter = 17, Seconds = 22
Counter = 18, Seconds = 23
Counter = 19, Seconds = 24
Counter = 20, Seconds = 25
25.2769325