Applescript – Close all windows except frontmost window

applescriptautomatorcatalina

I have created an automator quick action that runs the following apple script

tell application "System Events"
    set frontApp to name of first application process whose frontmost is true --retrieves name of open application
end tell

tell application frontApp
    repeat while window 2 exists
        close window 2
    end repeat
end tell

It works; however, it takes a while to run if I have a lot of windows open.

Is there a way to close all windows simultaneously except for the frontmost one?

I typed in tell application "Finder" to close every window from 2 to 5
After I compiled it, it automatically changed to tell application "Finder" to close ( windows 2 thru 5 ). However, I get the error message error "Finder got an error: Can’t get windows 2 thru 3." number -1728 from windows 2 thru 3. So, then, it accepts the structure of the command, but I'm still missing something.

Edit: I tried the following script

tell application "Finder"
    close (every window where index is greater than 1)
end tell

However, I get the error "Finder got an error: Handler can’t handle objects of this class." number -10010

Why does this not work?

Best Answer

Please try this. It might run faster. (edited my original answer with new code).

tell application "Finder"

    set theWindows to {}
    set theCount to (count of windows)
    if theCount is greater than 1 then
        repeat with i from 2 to theCount
            set theWindow to window i
            copy theWindow to end of theWindows
        end repeat
        close theWindows
    end if
end tell