user1462199
user1462199

Reputation:

Convert C# code to PowerShell

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?

Upvotes: 4

Views: 844

Answers (1)

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262939

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

Upvotes: 4

Related Questions