PowerShell: how to convert a COM object to a .NET interaction type?

As described in my question Create an ISO image using PowerShell: how to save an IStream file in a file? , in PowerShell, I create an IStream as follows:

 $is = (New-Object -ComObject IMAPI2FS.MsftFileSystemImage).CreateResultImage().ImageStream 

This object is of type (PowerShell) System.__ComObject . And somehow, PowerShell knows this is IStream :

 PS C:\> $is -is [System.Runtime.InteropServices.ComTypes.IConnectionPoint] False PS C:\> $is -is [System.Runtime.InteropServices.ComTypes.IStream] True 

However, casting to this type fails:

 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 to do this conversion without using C # code?

Update: Apparently, this conversion cannot be made to work, as x0n 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 will become a .NET object of type System.Runtime.InteropServices.ComTypes.IStream . Is it possible? If not, what are my alternatives?

+4
source share
2 answers

You can try passing $is to a (unsafe) C # method of type object and try to process it using a VAR declared as System.Runtime.InteropServices.ComTypes.IStream

 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 add-type:

 [MyClass]::MyMethod($is) 
+5
source

You cannot do this work. PowerShell uses a transparent "com-adapter" layer, which prevents this from working, but provides late binding in the script. For most cases, this is a good thing, but not yours.

+3
source

Source: https://habr.com/ru/post/1393389/


All Articles