Search code examples
applescriptitunes

Applescript to Delete Watched TV Shows from iTunes Library


Here is what I’m trying to do with the actual code:
if (there are multiple episodes in a tvshow folder AND at least one episode is marked as unwatched){ delete the watched episodes }

My goal here is to always leave a single episode in the TVShow folder. Even if that show is marked as watched or unwatched. The only condition where deletion occurs is when there are multiple episodes and one of those episodes is marked as unwatched. I need this script to run on ALL the tvshows in iTunes. This will keep my iTunes account smaller and auto delete watched shows for me. Anyone know how to do this? I’m very new to Applescripting.

BTW, and if it matters, the TVShows I'm referring to are ones that I've added to the iTunes library OUTSIDE of the iTunes store. This script will not be deleting purchased tvshows. I appreciate any help!


Solution

  • Providing a script which deletes something is always quite dangerous.

    As your request is a bit ambiguous

    … at least one episode is marked as unwatched
    and
    … a single episode … even if that show is marked as watched or unwatched

    the script is going to delete all watched episodes in the playlist TV Shows if there is at least one unwatched episode.
    All unwatched episodes are not deleted.

    There are two scripts one for testing and and one for deleting.


    Script #1 doesn't delete anything but displays the list of the items which are supposed to be deleted.

    tell application "iTunes"
        set watchedEpisodes to tracks of playlist "TV Shows" whose unplayed is false and played count > 0
        set unwatchedEpisodes to tracks of playlist "TV Shows" whose unplayed is true
        if (count unwatchedEpisodes) > 0 then
            set trackNames to {}
            repeat with anEpisode in watchedEpisodes
                set end of trackNames to ((name of anEpisode) as text) & " of show " & show of anEpisode
            end repeat
    
            set {TID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, return}
            display dialog trackNames as text
            set AppleScript's text item delimiters to TID
        end if
    end tell
    

    Please check the output carefully


    Script #2 deletes the items matching the criteria

    tell application "iTunes"
        set watchedEpisodes to tracks of playlist "TV Shows" whose unplayed is false and played count > 0
        set unwatchedEpisodes to tracks of playlist "TV Shows" whose unplayed is true
    
        if (count unwatchedEpisodes) > 0 then
            repeat with anEpisode in watchedEpisodes
                delete anEpisode
            end repeat
        end if
    end tell