Keyboard Maestro Version 7.1 introduced a streamlined way to Get and Set Keyboard Maestro Variables from AppleScript.
In AppleScript, you can tell the application “Keyboard Maestro Engine” to:
getvariable <KM Variable Name> setvariable <KM Variable Name> to <New Value>
where both the <KM Variable Name>
and <New Value>
are text values.
### Requires Keyboard Maestro 7.1+ ### --- Set AppleScript Variables to KM Variable Name and Value --- set myKMVar to "My KM Var Name" set myASVar to "TBD" -- default value of KM variable, will be updated tell application "Keyboard Maestro Engine" ### GET ### -- IF KM Variable does NOT exist, the AS Variable will be set to empty string -- -- Use Explicit Quoted Text -- set myASVar to getvariable "My KM Var Name" -- OR, Use Previously Defined AppleScript Variables -- set myASVar to getvariable myKMVar ### SET ### -- IF KM Variable does NOT exist, it will be created -- -- Use Explicit Quoted Text -- setvariable "My KM Var Name" to "A new value" -- OR, Use Previously Defined AppleScript Variables -- setvariable myKMVar to myASVar end tell
Normally, you would not have both a GET and a SET variable within the same AppleScript tell block.
Here's a real-world example, but with the error checking removed to simplify.
--- GET REQUIRED KM VARIABLES --- tell application "Keyboard Maestro Engine" set mainStr to getvariable "SCPT__MainString" set subStr to getvariable "SCPT__StringToFind" end tell --- PROCESS THESE KM VARIABLES --- --- Get Start of StringToFind --- set posSubStr to offset of subStr in mainStr --- SET OUTPUT KM VARIABLE --- tell application "Keyboard Maestro Engine" to setvariable "SCPT__PosSubStr" to posSubStr
For more details, see Scripting article in the Manual Section.
--- Requires KM 7.0.2+ --- --- Set AppleScript Variables to KM Variable Name and Value --- set myKMVar to "My KM Var Name" set myASVar to "My data" tell application "Keyboard Maestro Engine" if variable myKMVar exists then --- SET KM Variable --- set value of variable myKMVar to myASVar else --- Create & Set KM Variable --- make new variable with properties {name:myKMVar, value:myASVar} end if end tell
set myKMVar to my getKMVar("MY_KM_Variable") on getKMVar(pKMVarNameStr) --- Compatible with Keyboard Maestro 6+ --- -- • Returns "" if variable is not found (just like KM 7) tell application "Keyboard Maestro Engine" try set kmVar to value of variable pKMVarNameStr on error errMsg number errNum if (errNum = -1728) then --- KM Variable NOT Found --- set kmVar to "" else error errMsg end if -- END on error end try end tell return kmVar end getKMVar