applescriptshutdownapplication-shutdown

Applescript shut down issues


I'll apologize upfront for posting another dang question/problem with an AppleScript shut down app. I must have read 1,000 threads relating to this topic.

Sequoia 15.3.2

2025 Apple M4 pro

I've pared down the code for my app to the basics and it has the same problems. The code follows:

on run
    tell application "Finder" to activate
    
    tell application "System Events" to set the visible of every process to true
    try
        tell application "Finder"
            set listOfApps to name of every application process whose visible is true and name is not "Finder" and name is not "Script Editor" and name is not {name of me}
        end tell
        
        repeat with appToClose in listOfApps
            tell application appToClose to quit without saving
        end repeat
    on error errStr number errorNumber
        display dialog "errStr = " & errStr & return & "number = " & number & return & "errorNumber = " & errorNumber buttons {"Quit"} default button 1
        return
    end try
    
    tell application "Finder" to close every window
    
    tell application "System Events" to shut down
end run

If I comment out the "shut down" command, the code works fine in both the AppleScript Editor and as an app. If uncommented and run as an app, I get one of the following three results when I next boot.

Error Message

Any insights would be appreciated. Fairly new to AppleScript and I find it limited and frustrating.


Solution

  • Update:

    Try adding with state saving preference, which is an option of the restart command, like so:

    tell application "System Events" to restart with state saving preference

    Alert

    Be careful to not use without as that will likely trigger an automatic restart loop. For myself, it required a 'safe' restart (holding down the shift key as the computer restarted) and a long wait for the system to finish booting up.

    Suggestion but not solution

    Try this:

    on run
        delay 2
        set keepAlive to {"Finder", "Script Editor", "killApp"} -- latter is name of this applet
        tell application "System Events"
            set openApps to name of (every process whose background only is false)
        end tell
        
        -- optional: list of open applications
        set AppleScript's text item delimiters to linefeed
        display dialog (openApps as text) with title "Open applications"
        
        repeat with appn in openApps
            if appn is not in keepAlive then
                tell application appn to quit
            end if
        end repeat
        
    end run
    

    A couple of notes: