How a Powershell Query Interface on a COM Object

I created a COM object using Powershell:

$obj = new-object -com MyLib.MyObj 

Then I need to query the "MyLib.MyInterface" interface on this object, but I have no idea how to do this using PowerShell.

In word order, suppose I have C ++ code below

 CComPtr<IInterface1> pInterface1; CComPtr<IInterface2> pInterface2; pInterface1->CoCreateInstance(CLSID_XXXX); //in PowerShell: $obj = new-object -com MyLib.MyObj pInterface1->QueryInterface(IID_YYYY, &pInterface2); //how to do this in PowerShell? 

How to do the same job with Powershell

Any comments?

thanks

+8
powershell com
source share
3 answers

Here is an example when I call Word (see the Word Object Model Overview ) COM object:

 # Create Word Object $wrd = new-object -com "word.application" # Make Word Visible $wrd.visible = $true # Open a document $doc = $wrd.documents.open("C:\silogix\silogix.doc") 

To view the properties and methods of your COM object, you can use:

 $obj | Get-Member 
+2
source share

If I understand your needs, try the following:

 $obj = new-object -com MyLib.MyObj $type = $obj.gettype() $type.GetInterfaces() # give a list of interfaces for the type 

Hope Can Be A Starting Point

+2
source share

As an experiment, I created $obj=new-object -com file . ("file" is a progid for the COM FileMoniker class). [Runtime.InteropServices.marshal]::GetIUnknownForObject($obj) gives me System.IntPtr on my Windows 2008R2 machine. I was able to pass this value along with the GUID for IMoniker to [Runtime.InteropServices.marshal] :: QueryInterface, and I got the same value (that is, the same pointer) as GetIUnknownForObject. So I was able to request an interface.

However, I'm not sure what is good from Powershell. There are many other methods in [Runtime.InteropServices.marshal] that may be of interest for working with COM from PS. But in general, working with COM objects in PS is very different from working with them in C ++.

EDIT Recently, I found and tested a way to access some COM components from PS that might be of interest here. The Windows SDK comes with a large set of IDL files. If you want to access one of them (and the component does not implement IDispatch), you can compile IDL using MIDL, and then use TLBIMP to create the interop assembly. I have successfully done this with the three VSS hardware vendor interfaces.

I also found out that you can use [type] :: GetTypeFromCLSID to get the type from the CLSID. And depending on the component, you can create it.

+2
source share

All Articles