4

Given this piece of code:

someobject.ProgressChanged += (sender, args) => Console.WriteLine(args.ProgressPercentage);

How could I write the same thing in powershell, i used Register-Event but when i called the execute method on the object it just blocks the thread and you only see that the event has fired after the action is finished, I also tried to use Start-Job.

Any ideas?

0

1 Answer 1

4

Register-ObjectEvent should work:

Register-ObjectEvent -InputObject $someobject -EventName ProgressChanged `
    -Action { Write-Host $EventArgs.ProgressPercentage }

See this TechNet article for more information about asynchronous event handling in PowerShell.

EDIT: As requested in comments, here is the code I used in my tests:

$timer = New-Object System.Timers.Timer
$timer.Interval = 500
$timer.AutoReset = $true
Register-ObjectEvent -InputObject $timer -EventName Elapsed `
    -Action { Write-Host $EventArgs.SignalTime }
$timer.Start()

From there on, the signal times of the Elapsed events were printed to the console every half second until I managed to blind-type $timer.Stop().

Sign up to request clarification or add additional context in comments.

3 Comments

I probably wasn't clear enough, you can use Register-ObjectEvent to subscribe to the event but it still only fires after the execution of my method has completed
@Taylor, interesting, I tested the code above with a timer and the handler was definitely called asynchronously. Where and how are you triggering the ProgressChanged event? Is it coming from a BackgroundWorker?
my suspicious were right, its actually the library that i am using that is causing this behavior with its MRE.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.