User Tools

Site Tools


AppleScript

**This is an old revision of the document!**

Using AppleScript to Get and Set Keyboard Maestro Variables


Get and Set Variables

Keyboard Maestro Version 7.1 introduced a streamlined way to Get and Set Keyboard Maestro Variables from AppleScript.

snippet.applescript
### Requires Keyboard Maestro 7.1+ ###
 
--- Set AppleScript Variables to KM Variable Name and Value ---
set kmVarName to "My KM Var Name"
set kmVarValue 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 --
  set kmVarValue to getvariable kmVarName
 
  ### SET ###
  -- IF KM Variable does NOT exist, it will be created --
  setvariable kmVarName to kmVarValue
 
end tell

Example

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.

snippet.applescript
--- 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.


Prior to Ver 7.1

  • All of the below scripts were designed for use with Keyboard Maestro prior to version 7.1, but they will still work with the latest version.
  • They present an alternate method.

Create & Set Variable

snippet.applescript
--- Requires KM 7.0.2+ ---
 
--- Set AppleScript Variables to KM Variable Name and Value ---
set kmVarName to "My KM Var Name"
set kmVarValue to "My data"
 
 
tell application "Keyboard Maestro Engine"
  if variable kmVarName exists then
    --- SET KM Variable ---
    set value of variable kmVarName to kmVarValue
  else
    --- Create & Set KM Variable ---
    make new variable with properties {name:kmVarName, value:kmVarValue}
  end if
end tell

Get Existing Variable

snippet.applescript
--- Requires KM 7.0.2+ ---
 
--- Set AppleScript Variables to KM Variable Name and Value ---
set kmVarName to "My KM Var Name"
set kmVarValue to "TBD" -- default value of KM variable, will be updated
 
tell application "Keyboard Maestro Engine"
  if variable kmVarName exists then
    --- GET Existing KM Variable ---
    set kmVarValue to value of variable kmVarName
  else
    --- KM Variable NOT Found ---
    set kmVarValue to ""
    -- Optionally, throw an AppleScript error --
    error "[ERROR] KM Variable '" & kmVarName & "' was NOT found."
  end if
end tell
AppleScript.1483734256.txt.gz · Last modified: 2017/01/06 15:24 by JMichaelTX