powershell计时器无法立即停止

时间:2016-09-22 23:39:53

标签: powershell timer

我正在尝试使用powershell Timer定期执行某些工作,一旦作业返回符合我期望的结果,我将停止运行该作业。

>$timer = New-Object System.Timers.Timer
>$counter = 0
>$timer.Interval = 1000
>$timer.AutoReset = $true
>Register-ObjectEvent -InputObject $timer -EventName Elapsed -Action { if ( $counter -eq 5 ) {$timer.Stop(); } ; $counter = $counter +1; write-host "counter is: " $counter; }
>$timer.Start()

结果是:

 counter is:  1
 counter is:  2
 counter is:  3
 counter is:  4
 counter is:  5
 counter is:  6

我期待计数器在$ counter达到5时停止,但它继续工作。一旦满足某些条件,有没有办法立即停止计时器?

1 个答案:

答案 0 :(得分:0)

你的IF应该有一个ELSE。你的逻辑不正确。尝试这样的代码:

$timer = New-Object System.Timers.Timer
$counter = 0
$timer.Interval = 1000
$timer.AutoReset = $true
$wait = $true
Register-ObjectEvent -InputObject $timer -EventName Elapsed -Action { if ( $counter -eq 5 ) {$timer.Stop(); write-host "counter stopped"; $global:wait=$false } else {$counter = $counter +1; write-host "counter is: " $counter; }}
$timer.Start()

while ($wait) { "sleeping..."; Start-Sleep -Milliseconds 500 }
$timer.Close()
"exiting..."

<强>输出

在我的机器上显示:

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command                  
--     ----            -------------   -----         -----------     --------             -------                  
13     3a8d73a2-589...                 NotStarted    False                                 if ( $counter -eq 5 )...
sleeping...
sleeping...
counter is:  1
sleeping...
sleeping...
counter is:  2
sleeping...
sleeping...
counter is:  3
sleeping...
sleeping...
counter is:  4
sleeping...
sleeping...
counter is:  5
sleeping...
sleeping...
counter stopped
sleeping...
exiting...