MacOS – Apple Script – Reopen Closed Finder Windows


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 AppleShowAllFiles"
if OnOff = "NO" or OnOff = "OFF" then
    set OnOffCommand to "defaults write AppleShowAllFiles ON"
    set OnOffCommand to "defaults write AppleShowAllFiles OFF"
end if
do shell script OnOffCommand
delay 1
tell application "Finder" to launch
tell application "Finder"
        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 NSQuitAlwaysKeepsWindows -bool true

I use this script to toggle showing hidden files:

do shell script "[[ $(defaults read AppleShowAllFiles) = 1 ]] && b=false || b=true
defaults write AppleShowAllFiles -bool $b"
tell application "Finder"
    delay 0.1 -- without this delay Finder was not made frontmost
    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