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()

while(1)
{
    <do some testing here>
}

So when it works, I will see the "timeout: XX" output every 10 seconds written to the log. But this is only happening when run inside the editor. When I run it via batch file nothing happens (although I can confirm the while loop is processing fine).

So my question is why is my experience different when I'm running the script inside PowerGUI versus via command line? My thought is there might be an issue with scoping or parallel threads but I'm not exactly sure what the issue is. Also I am not running these events inside any functions or loops.

Edit
Report