Script with Register-ObjectEvent hanging


This is the script in Example 3 of the Wait-Event page, with some little modifications.

$Timer = New-Object Timers.Timer

$objectEventArgs = @{
    InputObject = $Timer
    EventName = 'Elapsed'
    SourceIdentifier = 'Timer.Elapsed'
    Action = { Write-Host "Action triggered" }

$handlers = Register-ObjectEvent @objectEventArgs

$Timer.Interval = 4000
$Timer.Autoreset = $False
$Timer.Enabled = $True

Wait-Event Timer.Elapsed

Unregister-Event -SourceIdentifier 'Timer.Elapsed'
$handlers | Remove-Job

If I run it on PowerShell 7.4.1, two problems show up:

  1. After printing Action triggered it hangs. Shouldn’t the execution continue? How to make it go on?
    If instead there is no Action argument at all, the script ends as expected.
  2. With no Action argument, if I try to run the script two consecutive times in the same PowerShell console, the second time it ends apparently normally, but without waiting for the timer to expire: it ends instantaneously. Why?

I’m not sure on the action triggered . I reproduced that in 7.4 and 5. PowerShell, Return from “Wait-Event” when “Register-ObjectEvent -Action” triggers? - Stack Overflow indirectly suggests that using action with wait-event is a ‘no-no’ but unfortunately they link to another thread that’s no longer available. I don’t know enough about those commands work to give you an intelligent answer than, it doesn’t seem like doing these two things together work. I don’t have time unfortunately to dig/google around more.

on the second thing, I think it’s because you already waited for the event. The timer has elapsed. If you were to change the autoreset to $true, and run Get-Event, you’ll see every 4 seconds a new event is tirggered in that PS session, but Wait-Event I think is simply waiting for you timer to elapse 4 seconds, which it has already.

Are you just playing around, or are you trying to solve an actual issue? If so, could you share the problem you are trying to solve, as there might be another way to address it?

Thank you.

1 Like

No problem, it’s anyway useful, thank you!
A simple workaround is to put the same code of the Action block right after Wait-Event Timer.Elapsed:

Wait-Event Timer.Elapsed
Write-Host "Action triggered"

It works this way (even if automatic variables like $Event, $Sender, etc. will not be available).

Ok, so IIUC the timer expiration (that is: this specific event) can be detected by Wait-Event only once in that single PowerShell terminal. Once it has been consumed, Wait-Event is done.

Both the things. I am playing around and trying to better understand the Register-ObjectEvent and Wait-Event usages, because of the issues I’m having in this thread.

Thank you so much!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.