AppleScript app need to be launched 2 times to work

I have a script to quit all applications it works right in the script editor but as an app, I have to launch it twice for it to work. Any ideas?


tell application "System Events"
	set theVisibleApps to (name of application processes where visible is true)
end tell

repeat with thisApp in theVisibleApps
	try
		tell application thisApp to activate
		tell application "System Events"
			keystroke "q" using command down
		end tell
	on error errMsg
		display dialog errMsg
	end try
end repeat

If you run the following code in a script editor, you will note that the returned list includes the Finder, which can’t be quit.

tell application "System Events"
	set theVisibleApps to (name of application processes where visible is true)
end tell

Also, there’s no reason to use GUI scripting–which can be cumbersome and error prone–when the same thing can be done otherwise. The following does what you want and it worked for me when saved as an applet on the desktop:

set doNotClose to {"Finder"}

tell application "System Events"
	set activeApps to name of every process whose background only is false
end tell

repeat with anApp in activeApps
	try
		if anApp is not in doNotClose then tell application anApp to quit
	end try
end repeat

The above script contains a potential flaw in that the name of an app and its process name are not in every instance the same. You may want to consider the following, which is faster and in my experience more reliable. I’ve included but commented out a line that closes all Finder windows, just in case that’s desired.

use framework "AppKit"
use framework "Foundation"
use scripting additions -- not required if standalone script

on main()
	set doNotQuit to {"Finder", "Script Editor", "Script Debugger"} -- edit as desired but keep Finder
	
	set theApps to current application's NSWorkspace's sharedWorkspace()'s runningApplications()
	set thePredicate to current application's NSPredicate's predicateWithFormat:"activationPolicy == 0 AND NOT (localizedName IN %@)" argumentArray:{doNotQuit}
	set theApps to theApps's filteredArrayUsingPredicate:thePredicate
	
	repeat with anApp in theApps
		anApp's terminate()
	end repeat
	
	-- tell application "Finder" to close every window
end main

main()

Thanks a lot your last example was exactly what i was looking for.