Exploring COM with PowerShell

What is COM?

I hope to explain how to use COM object in PowerShell. A COM object is an interface into an application or Windows. For example the Excel COM object will allow you to work with an Excel spreadsheet, or the iTunes COM object will allow you to control iTunes via PowerShell. It’s not always pretty, or easy. If you have a built-in PowerShell command, use it. (For example Export-Csv is easier then using Excel to work with CSV.)

Getting Started

Maybe you don’t know the exact name of the COM object you want to use? Sometimes a quick web search will uncover it. If not, this bit of PowerShell code will list the COM objects available on your machine.

Get-ChildItem HKLM:\Software\Classes -ErrorAction SilentlyContinue | Where-Object { $_.PSChildName -match '^\w+\.\w+$' -and (Test-Path -Path "$($_.PSPath)\CLSID") } | Select-Object -ExpandProperty PSChildName

(via PowerShell Magazine)

The list may take a few minutes. I see “iTunes.Application” in there. That’s what I want.

Using the COM Object

I tell PowerShell to create a new object:

$Itunes = New-Object  -ComObject iTunes.Application

To see what we can do with this object, execute the above then type this PowerShell command (gm is the alias for Get-Member):

$Itunes | gm

This tells me the methods and properties supported by this COM object. Browsing through this will reveal more details, if you need it. “$itunes.LibraryPlaylist.Tracks” is all the tracks. And

$itunes.LibraryPlaylist.Tracks[1] | gm

shows you the methods and properties relating to tracks. (I use the “[1]” to make the listing faster. Since tracks is an array of all the tracks in iTunes, this could take a long time to list all the methods and properties, if you have many tracks. Since all tracks have the same member names (like Artist, Year, Name, etc), I’ll just list the members from the first track.)

So for example, if you wanted iTunes to play, you could do:

$Itunes.play()

Or this little script goes through all your tracks and counts the artists in your collection:

$Itunes = New-Object  -ComObject iTunes.Application
# Get a list of artists from tracks
$Artist = @()
foreach ($Track in  $Itunes.LibraryPlaylist.Tracks)
    {
    $Artist += $Track.Artist
    }
# eliminate duplicates in the list
$artist = $artist | sort -Unique 
Write-Host "$($artist.count) artists found in your iTunes collection"