Mac OS X 10.3 and later: Keychain Scripting "isn‘t running" error in AppleScript scripts

Some AppleScript scripts that use Keychain Scripting may produce this error message:

To resolve the issue, make sure that the Keychain Scripting process is already running; it should be launched by a process other than the one that wants to run the script.

One method for doing this is demonstrated in the following AppleScript:

-- Begin Script

property pKeychainItemName : "kctest"


on startKeychainScripting()
	
	-- This function ensures that the Keychain Scripting.app is launched by a process
	-- different from the one executing this script. It is only needed when using Keychain Scripting to
	-- retrieve the password property of a key.
	
	-- Quit Keychain Scripting if it's running, since opening this script may have implicitly launched it.	
	try
		tell application "System Events"
			set foundApp to first process whose name is "Keychain Scripting"
			set pid to id of foundApp -- this will exit the try block if the process isn't running
			quit foundApp -- we get here if the process is found
		end tell
	end try
	
	-- get Finder to launch Keychain Scripting
	tell application "Finder"
		open application file ((startup disk as string) & "System:Library:ScriptingAdditions:Keychain Scripting") as alias
	end tell
	
	-- make sure that Keychain Scripting is up and running
	repeat while true
		try
			tell application "System Events"
				set foundApp to first process whose name is "Keychain Scripting"
				set pid to id of foundApp -- this will exit the try block if the process isn't running
			end tell
			exit repeat -- we get here if the process is found
		end try
	end repeat
	
end startKeychainScripting


on run
	set x to my getPassword(pKeychainItemName)
	activate
	display dialog x buttons {"OK"} default button "OK"
end run


on getPassword(keyname)
	
	startKeychainScripting()
	
	tell application "Keychain Scripting"
		try
			set theKey to first key of current keychain whose name is keyname
			set thePassword to password of theKey
		on error message number errNum
			set thePassword to message & " (" & errNum & ")"
		end try
	end tell
	
	return thePassword
	
end getPassword

-- End Script

This document will be updated as more information becomes available.

Published Date: Oct 7, 2016