I need to implement an event handler for this NewCivicAddressReport event of the CivicFactory object. This following code, using event handler naming convention, works perfectly in VBScript:
Dim CivicFactory
Set CivicFactory = WScript.CreateObject("LocationDisp.CivicAddressReportFactory", "CivicFactory_")
Function CivicFactory_NewCivicAddressReport(report)
MsgBox "Location changed!"
End Function
However in PowerShell the following code fails:
$CivicFactory = new-object -comObject LocationDisp.CivicAddressReportFactory
Register-ObjectEvent $CivicFactory -EventName "NewCivicAddressReport" -Action ({ echo "hello" })
The error message is : Register-ObjectEvent : Cannot register for event. An event with name 'NewCivicAddressReport' does not exist.
I also tried $CivicFactory.add_NewCivicAddressRerport( {"hello"} )
and it failed too.
So I turned to $CivicFactory | Get-Member
: it did return its methods and properties but NO events.
So I suspect PowerShell doesn't support COM events very well. I installed the pseventing snapin and tried Get-EventBinding CivicFactory -IncludeUnboundEvents | Format-Table -Auto
- it returned nothing, which mean开发者_StackOverflows the system doesn't believe this object has events.
So now I'm doubting: is it possible at all to bind an event handler to an object?
Can anyone show me the correct way?
PowerShell doesn't work very well with COM objects if there is no type library available. It's not just events that are missing, typically other members are not there either if you try to use get-member to explore the instance. On the whole, late binding support is sadly lacking but this is probably because of the way powershell uses "adapters" to expose objects' members to the runtime. You can invoke members in a late-bound fashion by using InvokeMember. Take a look at:
http://www.sorrell.mcleod.co.uk/Scotty/powershell/COMinterop.htm
I thought I was finished with PSEventing but it appears there might be room for a v2.0 that can work with late-bound events. Hmmm.
I'm not saying that COM events don't work, they work pefectly well but only if there's an interop or type library available.
-Oisin (author of pseventing)
精彩评论