Search code examples
applescriptfreezefinder

applescript hangs finder with simple "whose" query


I've tried to code a very simple Automator service to select all the files with the same extension as the file currently highlighted. It calls an Applescript script that I've written like that (inspired by some code found here actually):

on run {input, parameters}
    try
        set anItem to first item of input
        tell (info for anItem) to set theExt to name extension
        tell application "Finder"
            set parentFolder to (parent of anItem as alias)
            select (every document file of parentFolder whose (name extension is theExt))
        end tell
    end try
end run

It runs fine up to the line 'select...' with proper variables parentFolder and theExt. Then I get a beachball. Finder stuck at 100% for ages, I have to kill it and relaunch.

EDIT: I just realized it actually runs fine if the folder contains a few dozen elements. It hangs (even allowed to run for hours) on a large folder of around 10000 elements (obiously you write that kind of code when dealing with a large number of files...).


Solution

  • The Finder is terribly slow when filtering items with the where clause.

    This is an alternative using System Events which is much faster

    on run {input, parameters}
        try
            set anItem to first item of input
            tell application "System Events"
                set theExt to name extension of anItem
                set parentFolder to path of container of anItem
                set itemsToSelect to (path of files of folder parentFolder whose name extension is theExt)
            end tell
            tell application "Finder"
                open parentFolder
                select itemsToSelect
            end tell
        end try
    end run
    

    Note: info for is deprecated for a long time. Getting the information directly from System Events is preferable.