Hello.
I have a PowerShell script that uses an Asynchronous Timer Event (background process) to measure how long a certain condition has been occurring before taking appropriate action.
This is working perfectly fine when I run the script inside PowerGUI but when I run the script using dot-sourcing or run it via a batch file the Timer Event actions are not firing.
Here is a code snippet.
$timer = New-Object System.Timers.Timer
$timer.Interval = 10000
$timer.AutoReset = $true
$timeout = 0
$action = {
"timeout: $timeout" | Add-Content $loglocation<more stuff here>
$timer.stop()
}
$start = Register-ObjectEvent -InputObject $timer -SourceIdentifier TimerElapsed -EventName Elapsed -Action $action $timer.start()
When it works, we will see the "timer: XX" output every 10 seconds written to the log. But this is only happening when inside the editor.
So my question is why is my experience different when running the script inside PowerGUI versus via command line? My thought is there's an issue with scoping but I'm not sure what the issue is. I am not running these events inside any functions or loops (yet).