Can you delete a macro by name?

I have a popup list of obsolete macros (text expansions) that returns a macro name to be deleted. But the AppleScript to delete a macro by name is eluding me:

tell application "Keyboard Maestro"
	delete macro whose name begins with MacroName
end tell

(where MacroName is an AS variable with the name of the macro I want to delete) returns:

Execute an AppleScript failed with script error: text-script:191:240: execution error: Can’t get macro whose name starts with "=fn=". (-1728)

What am I missing? TIA

Your "whose" clause returns a LIST of macros.

Try something like this:

set macroPrefix to "TESTDel"

tell application "Keyboard Maestro"
  set macroList to macros whose name begins with macroPrefix
  
  --- If you want to see the Names of the Macros ---
  set macroNameList to name of macros whose name begins with macroPrefix
  
  repeat with oMacro in macroList
    set macroName to name of oMacro
    
    set oResult to display dialog "Comfirm DELETION of Macro: " & macroName ¬
      with title ¬
      "Delete KM Macros" buttons {"Cancel", "No", "Yes"} ¬
      default button ¬
      "Yes" cancel button ¬
      "Cancel" with icon caution
    
    set buttonStr to button returned of oResult
    if (buttonStr = "Yes") then
      delete oMacro
      log macroName & " was deleted"
    end if
  end repeat
end tell

-- macroNameList
-->{"TESTDel 1", "TESTDel 2"}

-- Log:
--(*TESTDel 1 was deleted*)

image

Ouch, yes. Thanks.

And coming from a Prompt with List (with the notorious empty item on multiple selections) I couldn't build an array of macros, just strings of their names.

So if anyone else is growing old trying to unraveling this trick, here's what I came up with (gratuitously renaming variables just to make sure I tracked them):

set kmInst to system attribute "KMINSTANCE"
tell application "Keyboard Maestro Engine"
	set macroList to getvariable "LocalMacroNames" instance kmInst
	set macroList to paragraphs of macroList
	repeat with theMacro in macroList
		if length of theMacro > 0
			set theResult to display dialog "Delete the macro named '" & theMacro & "'?"¬
				with title ¬
				"Text Expansion Macro Deletion" buttons {"Cancel", "No", "OK"} ¬
				default button ¬
				"OK" cancel button ¬
				"Cancel" with icon caution		
				set buttonStr to button returned of theResult
			if (buttonStr = "OK") then
				tell application "Keyboard Maestro"
					deleteMacro theMacro
				end tell
				display dialog "Macro '" & theMacro & "' has been deleted." buttons {"OK"} default button "OK"
			end if
		end if
	end repeat
end tell
2 Likes