PowerShell:如何将COM对象转换为.NET互操作类型?

PowerShell:如何将COM对象转换为.NET互操作类型?,powershell,com,powershell-2.0,com-interop,Powershell,Com,Powershell 2.0,Com Interop,如问题中所述,我在PowerShell中创建了一个对象,如下所示: $is = (New-Object -ComObject IMAPI2FS.MsftFileSystemImage).CreateResultImage().ImageStream 此对象属于(PowerShell)类型System.\u ComObject。不知何故,PowerShell知道这是一个IStream: PS C:\> $is -is [System.Runtime.InteropServices.ComT

如问题中所述,我在PowerShell中创建了一个对象,如下所示:

$is = (New-Object -ComObject IMAPI2FS.MsftFileSystemImage).CreateResultImage().ImageStream
此对象属于(PowerShell)类型
System.\u ComObject
。不知何故,PowerShell知道这是一个
IStream

PS C:\> $is -is [System.Runtime.InteropServices.ComTypes.IConnectionPoint]
False
PS C:\> $is -is [System.Runtime.InteropServices.ComTypes.IStream]
True
但是,对此类型的转换失败:

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
PS C:\>[System.Runtime.InteropServices.ComTypes.IStream]$is
无法将“System.\u ComObject”类型的“System.\u ComObject”值转换为“System.Runtime.InteropServices.ComT”类型
IStream”。
第1行字符:54

+[System.Runtime.InteropServices.ComTypes.IStream]$s您不能让它工作。PowerShell使用一个透明的“com适配器”层来阻止此操作,但在脚本中启用后期绑定。在大多数情况下,这是一件好事,但对你来说不是

您可以尝试在(不安全的)c#方法中传递
$is
,如
对象
类型,并尝试使用声明为
System.Runtime.InteropServices.ComTypes.IStream的
VAR来处理它

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(...)
    }
}
在powershell中添加类型之后:

[MyClass]::MyMethod($is)

谢谢我希望您能更新您的答案,包括一个指向您所描述的功能/行为的更多文档的指针。另外,我的目标是在一些C代码中使用这个
IStream
COM对象,这些C代码使用
Add Type
内联在同一个PowerShell脚本中,C代码需要从
IStream
读取。(我将很快更新此问题。)有什么简单的方法可以做到这一点?检查我的个人资料-我是一名5年的powershell microsoft mvp,可以直接访问powershell团队。我知道;)这就行了!以前我使用了
MyMethod(IStream I)
,然后PowerShell将其转换为
IStream
,但失败了。正如您所建议的那样,让.NET/CLR进行转换是可行的。赏金就要来了。