我有一个 PowerShell 脚本,它使用异步计时器事件(后台进程)来测量在采取适当措施之前某个条件已经发生了多长时间。当我在 PowerGUI 中运行脚本时,这工作得非常好,但是当我使用点源运行脚本或通过批处理文件运行它时,定时器事件操作不会触发。
这是一个代码片段。
$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>
}
所以当它工作时,我会每 10 秒看到一次“超时:XX”输出写入日志。但这只有在编辑器中运行时才会发生。当我通过批处理文件运行它时,没有任何反应(尽管我可以确认 while 循环处理正常)。
所以我的问题是为什么我在 PowerGUI 中运行脚本与通过命令行运行脚本时的体验不同?我的想法是作用域或并行线程可能存在问题,但我不确定问题是什么。此外,我没有在任何函数或循环中运行这些事件。