Question:
I’m writing a PowerShell script which uses a third-party library. One of the objects I’m using requires that I add an event handler. The event delegate looks like this:
1 2 3 4 5 6 |
public delegate void TSBPGPCreateOutputStreamEvent(object Sender, string Filename, System.DateTime TimeStamp, ref System.IO.Stream Stream, ref bool FreeOnExit) |
In PowerShell, I tried doing this:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$reader.Add_OnCreateOutputStream( { param( $sender, $fileName, $timestamp, [ref] $stream, [ref] $freeOnExit ) $stream = New-Object IO.MemoryStream } ) |
But I get back this error message:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Cannot convert value " param( $sender, $fileName, $timestamp, [ref] $stream, [ref] $freeOnExit ) $stream = New-Object IO.MemoryStream " to type "SBPGP.TSBPGPCreateOutputStreamEvent". Error: "The type 'System.IO.Stream&' may not be used as a type argument." |
Is there a better way of subscribing to events? Why can’t the Stream type be used as a type argument? What am I doing wrong?
Answer:
You should use the Register-ObjectEvent cmdlet, take a look at the examples on your own system by using:
1 2 |
PS> Get-Help Register-ObjectEvent -full |