MacOS – Apple Script – Reopen Closed Finder Windows

applescriptfindermacmacos

I have the following Applescript which toggles the show/hide hidden files and I would like to reopen the user's Finder windows which will be closed as the Finder gets relaunched.

tell application "Finder" to quit
set OnOff to do shell script "defaults read com.apple.finder AppleShowAllFiles"
if OnOff = "NO" or OnOff = "OFF" then
    set OnOffCommand to "defaults write com.apple.finder AppleShowAllFiles ON"
else
    set OnOffCommand to "defaults write com.apple.finder AppleShowAllFiles OFF"
end if
do shell script OnOffCommand
delay 1
tell application "Finder" to launch
tell application "Finder"
    try
        target of window 1
        make new Finder window to result
    on error
        make new Finder window to home
    end try
end tell

Can anyone point me in the right direction?

Best Answer

You might just disable closing windows when you quit Finder:

defaults write com.apple.finder NSQuitAlwaysKeepsWindows -bool true

I use this script to toggle showing hidden files:

do shell script "[[ $(defaults read com.apple.finder AppleShowAllFiles) = 1 ]] && b=false || b=true
defaults write com.apple.finder AppleShowAllFiles -bool $b"
tell application "Finder"
    quit
    delay 0.1 -- without this delay Finder was not made frontmost
    launch
    delay 0.5 -- without this delay there was sometimes a "connection is invalid" error
    activate -- make Finder frontmost
    reopen -- open a new default window if there are no open windows
end tell