powershell timer cannot stop immediately
I am trying using powershell Timer to do some periodically job and once the job returns results that meet my expectation, I will stop running the job.
>$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()
The result is:
counter is: 1
counter is: 2
counter is: 3
counter is: 4
counter is: 5
counter is: 6
I was expecting the timer to stop once $counter reaches 5, but it continues to work. Is there any way to immediately stop the timer once some condition is satisfied?