How can you handle events thrown by .NET object using PowerShell v2? Can someone point me to a simple code sample?
1 Answer
Look at the docs on the Register-ObjectEvent cmdlet. Be sure to use the -full parameter. It has some good examples of usage including this one:
$timer = New-Object Timers.Timer
$timer.Interval = 500
$timer.Start()
$job = Register-ObjectEvent -inputObject $timer -eventName Elapsed `
-sourceIdentifier Timer.Random `
-Action {$random = Get-Random -Min 0 -Max 100; $random}
Receive-Job $job
You might also want to check out this PowerShell Eventing QuickStart blog post. Note that some of the cmdlet names have changed e.g. Get/Remove-PsEvent is now just Get/Remove-Event.
5 Comments
Iain Samuel McLean Elder
I don't understand what the output of this script should be. Nothing displays in the console. How do I read the value of
$random?Iain Samuel McLean Elder
@isme Use the call operator on the job:
& $job.module {$random}.Keith Hill
@isme Talking to yourself, eh? :-) BTW I just modified the answer to use the Receive-Job cmdlet. But your suggestion would also be fine.
Iain Samuel McLean Elder
Thanks. I prefer the Receive-Job version. My suggestion no longer works on your code example because there is no
$random variable to read.Keith Hill
@isme I updated it so that both approaches should work. Thanks for the suggestion.