我有一个PowerShell脚本,它使用异步计时器事件(后台进程)来测量某个条件发生了多长时间,然后再采取适当的操作.当我在PowerGUI中运行脚本时,这非常正常,但是当我使用点源运行脚本或通过批处理文件运行脚本时,Timer事件操作不会触发.
这是一段代码片段.
$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>
}
Run Code Online (Sandbox Code Playgroud)
所以当它工作时,我会看到每10秒写入日志的"timeout:XX"输出.但这只发生在编辑器中运行时.当我通过批处理文件运行它没有任何反应(虽然我可以确认while循环处理正常).
所以我的问题是,当我在PowerGUI内部运行脚本而不是命令行时,为什么我的体验会有所不同?我的想法是范围或并行线程可能存在问题,但我不确定问题是什么.此外,我没有在任何函数或循环中运行这些事件.