问题
I have a question about how Windows PowerShell works when dealing with Com Interop.
I have a 3rd party application (let's call it ThirdPartyApp
) that exposes an API that I can call into.
I can early-bind it in e.g. Excel or Visual Studio and talk to it 'directly'. I can late-bind it in VBScript and still talk to it 'directly'.
By 'directly' I mean the way I can call properties and methods exposed by the API using syntax like ThirdPartyApp.Name
So in VBScript I can do:
Dim api : Set api = CreateObject("ThirdPartyApp.API")
WScript.Echo api.Name
In PowerShell, when I do:
$api = New-Object -ComObject ThirdPartyApp.API
I have to use this syntax to get the Name:
[System.__ComObject].InvokeMember('Name',[System.Reflection.BindingFlags]::GetProperty,$null,$api,$null)
Now, I understand that that has something to do with how ThirdPartyApp
was built.
I know this isn't a coding problem, and I hope I don't get downvoted immediately, but my question is: why can't I talk to this assembly the VBScript way when using Powershell? How does New-Object -ComObject
in Powershell differ from CreateObject(identifier)
in VBScript?
回答1:
Information for Visual Basic Programmers
Visual Basic provides full support for Automation. The following table lists how Visual Basic statements translate into OLE APIs.
Visual Basic statement OLE APIs
CreateObject (“ProgID”)
CLSIDFromProgID
CoCreateInstance
QueryInterface to get IDispatch interface.
GetObject (“filename”, “ProgID”)
CLSIDFromProgID
CoCreateInstance
QueryInterface for IPersistFile interface.
Load on IPersistFile interface.
QueryInterface to get IDispatch interface.
GetObject (“filename”)\
CreateBindCtx creates the bind context for the subsequent functions.
MkParseDisplayName returns a moniker handle for BindMoniker.
BindMoniker returns a pointer to the IDispatch interface.
Release on moniker handle.
Release on context.
GetObject (“ProgID”)
CLSIDFromProgID
GetActiveObject on class ID.
QueryInterface to get IDispatch interface.
Dim x As New interface
Find CLSID for interface.
CoCreateInstance
QueryInterface
MSDN Library October 2001 Microsoft Corp.
See https://docs.microsoft.com/en-us/windows/win32/api/combaseapi/
来源:https://stackoverflow.com/questions/61178839/what-is-the-difference-between-new-object-comobject-in-powershell-and-createobj