Question:
As described in my question Create ISO image using PowerShell: how to save IStream to file?, in PowerShell I create an IStream
object as follows:
1 2 |
$is = (New-Object -ComObject IMAPI2FS.MsftFileSystemImage).CreateResultImage().ImageStream |
This object is of (PowerShell) type System.__ComObject
. And somehow PowerShell knows that it is an IStream
:
1 2 3 4 5 |
PS C:\> $is -is [System.Runtime.InteropServices.ComTypes.IConnectionPoint] False PS C:\> $is -is [System.Runtime.InteropServices.ComTypes.IStream] True |
However, a cast to this type fails:
1 2 3 4 5 6 7 8 |
PS C:\> [System.Runtime.InteropServices.ComTypes.IStream] $is Cannot convert the "System.__ComObject" value of type "System.__ComObject" to type "System.Runtime.InteropServices.ComT ypes.IStream". At line:1 char:54 + [System.Runtime.InteropServices.ComTypes.IStream] $is <<<< + CategoryInfo : NotSpecified: (:) [], RuntimeException + FullyQualifiedErrorId : RuntimeException |
How do I make this conversion work, without using C# code?
Update: Apparently this conversion cannot be made to work, as x0n’s answer says.
Now, my goal is to pass this IStream
COM object to some C# code (part of the same PowerShell script using Add-Type
), where it would become a .NET object of type System.Runtime.InteropServices.ComTypes.IStream
. Is that possible? If not, what alternatives do I have?
Answer:
You can try to pass $is
in a (unsafe) c# method like an object
type and try to handle it with a VAR
declared as System.Runtime.InteropServices.ComTypes.IStream
1 2 3 4 5 6 7 8 9 10 |
public unsafe static class MyClass { public static void MyMethod(object Stream) { var i = Stream as System.Runtime.InteropServices.ComTypes.IStream; //do something with i like i.read(...) and i.write(...) } } |
In powershell after the add-type:
1 2 |
[MyClass]::MyMethod($is) |