powershellcomidispatch

Call method using IDispatch in PowerShell


I am trying to communicate with a COM application using PowerShell. When I instantiate it, I can only talk to it through the IDispatch interface. That in itself is interesting, because I can early-bind to it in Visual Studio and talk to it 'directly'.

When I do:

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

I get back only standard .Net stuff. But I can call properties using this syntax:

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

That will give me the Path property.

What I want to do is call a method, which takes two parameters (in my case a string and the $path parameter). I found that the general way to call a method is this::

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

My question: what is the syntax to supply <args>? I tried to simply pass them as arguments, that doesn't work.


Solution

  • In this particular case, where SomeMethod simply takes two string arguments, wrapping them in an array as @CherryDT (thanks) suggested did the trick:

    $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))