10

How can you handle events thrown by .NET object using PowerShell v2? Can someone point me to a simple code sample?

1 Answer 1

11

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.

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

5 Comments

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?
@isme Use the call operator on the job: & $job.module {$random}.
@isme Talking to yourself, eh? :-) BTW I just modified the answer to use the Receive-Job cmdlet. But your suggestion would also be fine.
Thanks. I prefer the Receive-Job version. My suggestion no longer works on your code example because there is no $random variable to read.
@isme I updated it so that both approaches should work. Thanks for the suggestion.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.