Category: iTunes OLE
Author/Contact Info slithymonster
Description: the iTunes SDK code example has an error! it deletes elements out of a list and then continues to use the previous indices (even though the list is now smaller). The solution: delete the tracks backwards.
use Win32::OLE;
use Getopt::Std;

######################################################################
+###
# Globals
######################################################################
+###
my $ITTRACKKINDFILE = 1;

######################################################################
+###
# Main
######################################################################
+###

getopts('sv');

my $app = 'iTunes.Application';
my $hItunes = Win32::OLE->new($app) || die "Could not start $app ($!)\
+n";
my $hTracks = $hItunes->LibraryPlaylist->Tracks;
my $numTracks = $hTracks->Count;

my @deleteme;
for (my($i)=1; $i <= $numTracks; $i++) {
    my $track = $hTracks->Item($i);
    next unless ($track->Kind == $ITTRACKKINDFILE);
    
    my $name = $track->Name;
    my $artist = $track->Artist;
    my $loc = $track->Location;
           unless (-f $loc) {
        print "[DELE] $artist: $name\n" if ($opt_v);
        unshift (@deleteme, $i);
    } else {
        print "[KEEP] $artist: $name\n" if ($opt_v);
    }
}

if ($opt_s) {
    print "** Simulation Only **\n";
} else {
    foreach my $i (reverse sort @deleteme) {
        print "Deleting [$i]...";
        $hTracks->Item($i)->Delete;
        print "Done\n";
    }
}