The ‘If Finder Window Open, Then…’ AppleScript code

applescript

I am creating a 'Quit All' keyboard shortcut. I have the Quit All Applications system command and the AppleScript to close open Finder windows (without it, Finder windows stay open). However, if no Finder window is open, an error sound plays every time. I therefore need to code the script to check if there are any open Finder windows, and if this is the case, to then close them. Here is the code I have so far:

tell application "Finder" to activate
tell application "System Events"
    keystroke "w" using {command down, option down}
end tell

Just missing the "if open Finder windows then" part at the beginning. Could someone help me for this line of code?

Best Answer

You can use the following AppleScript code to avoid an error if Finder doesn't have any windows open.


tell application "Finder"
    activate
    if exists window 1 then
        tell application "System Events"
            keystroke "w" using {command down, option down}
        end tell
    end if
end tell