【问题标题】:Call method using IDispatch in PowerShell在 PowerShell 中使用 IDispatch 调用方法
【发布时间】:2020-07-24 16:10:55
【问题描述】:

我正在尝试使用 PowerShell 与 COM 应用程序进行通信。当我实例化它时,我只能通过 IDispatch 接口与它对话。这本身就很有趣,因为我可以在 Visual Studio 中提前绑定它并“直接”与它对话。

当我这样做时:

$obj= New-Object -ComObject ComAssembly.Identifier # that's a made up name
$obj | gm

我只取回标准的 .Net 内容。但我可以使用以下语法调用属性:

$path = [System.__ComObject].InvokeMember('Path',[System.Reflection.BindingFlags]::GetProperty,$null,$obj,$null)

这会给我Path 属性。

我想做的是调用一个方法,它接受两个参数(在我的例子中是一个字符串和$path 参数)。我发现调用方法的一般方式是这样的::

$anotherthing = [System.__ComObject].InvokeMember('SomeMethod',[System.Reflection.BindingFlags]::InvokeMethod,$null,$cmc,<args>)

我的问题:提供&lt;args&gt; 的语法是什么?我试图简单地将它们作为参数传递,但这是行不通的。

【问题讨论】:

  • 我猜它应该是一个数组。你检查docs了吗?它实际上说有object[] args,和“一个包含要传递给要调用的成员的参数的数组。”。
  • 例如:$anotherthing = [System.__ComObject].InvokeMember('SomeMethod',[System.Reflection.BindingFlags]::InvokeMethod,$null,$cmc,new Object[] {'SomeString', $path})
  • 感谢您提供的链接,这不是一个简单的发现。会学习。事实上,我曾尝试传递一个数组,但我的 PowerShell 仍然很差。
  • 实际上,我认为我将您指向错误的地方和错误的示例,因为它更多的是 C# 而更少的 PowerShell,即使两者都调用了 .NET 函数
  • 很抱歉。试试这个语法:@('SomeString', $path)

标签: powershell com idispatch


【解决方案1】:

在这种特殊情况下,SomeMethod 只需接受两个字符串参数,将它们包装在一个数组中,正如@CherryDT(谢谢)所建议的那样:

$obj= New-Object -ComObject ComAssembly.Identifier # that's a made up name
$path = [System.__ComObject].InvokeMember('Path',[System.Reflection.BindingFlags]::GetProperty,$null,$obj,$null)
$anotherthing = [System.__ComObject].InvokeMember('SomeMethod',[System.Reflection.BindingFlags]::InvokeMethod,$null,$obj,@('SomeString', $path))

【讨论】:

    猜你喜欢
    • 2011-01-07
    • 2019-10-25
    • 2011-03-24
    • 2011-05-13
    • 2016-01-05
    • 1970-01-01
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多