Applescript - Close all windows except frontmost window

Solution 1:

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

Solution 2:

If you're running it as an Automator quick action, then you can close all windows except the frontmost window of the frontmost application by using the code below inside a Run AppleScript action (you can delete any sample code that appears, including on run {input, parameters}...end run:

tell application id "com.apple.SystemEvents" to tell the first process ¬
    whose frontmost = true to tell a reference to windows 2 thru -1 to ¬
    if exists then tell the value of attribute "AXCloseButton" to click