I created a PowerShell script that accesses iTunes on my PC, but I failed at receiving events from the iTunes object. The code which I found on the internet (in fact, Chat GPT recommended this code) is:
$eventHandler = {Write-Host "OnPlayerPlayEvent"}
$iTunes = New-Object -ComObject iTunes.Application
Register-ObjectEvent -InputObject $global:iTunes `
-EventName "OnPlayerPlayEvent" -Action $eventHandler `
-SourceIdentifier "iTunesPlayerPlay"
The 'Register-ObjectEvent' line returns this error message: "Cannot register for the specified event. An event with the name 'OnPlayerPlayEvent' does not exist."
Note: The Documentation of OnPlayerPlayEvent can be found at http://www.joshkunz.com/iTunesControl/interface__IiTunesEvents.html#a1
What I have tried:
Chat GPT suggested variants of the above code, Replacing 'Register-Object' by this:
$iTunes.add_OnPlayerPlay($eventHandler)
or this:
$comObject = [System.Runtime.InteropServices.Marshal]::GetIUnknownForObject($iTunes)
$iTunesEventSource = [System.Runtime.InteropServices.Marshal]::GetObjectForIUnknown($comObject)
$event = Register-ObjectEvent -InputObject $iTunesEventSource `
-EventName "OnPlayerPlayEvent" -Action $eventHandler `
-SourceIdentifier "iTunesPlayerPlay"
The former failed with "Method invocation failed because [System.__ComObject] does not contain a method named 'add_OnPlayerPlay'" and the latter with "An event with the name 'OnPlayerPlayEvent' does not exist".
I varied the event name, adding or removing the "On" prefix and/or "Event" postfix, with no effect.
I tried
$iTunes | Get-Member -MemberType Event
but that returned nothing (i.e. $null).
I am wondering whether events must be enabled in iTunes (didn't find an option), or maybe I must retrieve a different interface before I can subscribe to events? Or have I run into a limitation of PowerShell? Or have I misunderstood the concept of subscribing to COM events in PowerShell?
Thanks for your help
Hans