.NET event handler

Hi all,

I’m trying to catch .NET events in Powershell using Register-Object, which on the whole is working nicely. The problem I’m having is with an event whose handler signature looks like:

public void EventHandler(
int Example,
out bool Option

(I don’t have a c# or .NET background so excuse me if the terminology is a little wrong)

The ‘out bool’ is something I can’t figure out how to deal with. Any attempt to register for the event results in Powershell bombing out completely with an ‘Object reference not set to an instance of an object’ error (courtesy of VS2013) when the event is triggered. What scriptblock or function is needed as the -Action parameter on Register-EventObject to satisfactorily handle an event such as above?


out is handled with [ref] in PowerShell, but it means you’re required to set it.

Is that enough for you to go on?

Actually, I’m not sure you can use Register-ObjectEvent with that event signature, because it’s not compliant – it should have a signature like (object sender, EventArgs ea). It may work, because it does have two parameters, and Register-Object event may not be too picky. However, it’s likely that the error you’re getting is because PowerShell is trying to set $EventArgs from the second parameter, and since that signature has an [out] parameter, that means it has no value…

Thanks, your description seems to fit the bill. Powershell generally does a good job of mapping the event data onto it’s own object sender, EventArgs ea representation. The error I’m getting occurs regardless of what my -action sciptblock looks like and it isn’t caught by the ISE - as if the error is generated before the scriptblock is entered. This could well be as you describe, a failure to set an eventargs parameter with an ‘out’ value, i.e. no value.

So am I just going about this wrong? Should I be able to handle .NET events in Powershell?

It should be able to handle most events, yes – because events are supposed (see here) to be based on the EventHandler delegate which is what Register-ObjectEvent supports.

You can handle other events using a syntax like

$Object.Add_EventName({param([int]$example, [ref]$option) $option.Value = $true})

You only need Register-ObjectEvent if the object throws events on a different thread, because it won’t have a PowerShell session available to run the handler script …