Scripting Menu Commands
Applescript is very powerful but very poorly documented (from what I’ve found so far).
Here is the Apple Developer AppleScript Language Guide. Almost everything in this post isn’t found in the guide, though.
I saw a very good, recent blog post and it does something similar to what I want to automate: backing up my data from Address book, iCal, etc. From that post I discovered that the System Events application make all the menu items and interactions with dialog boxes available to AppleScripts. Here is the Apple documentation on System Events. Again, not very good.
To use the System Events, you need to make sure you have enabled access for assistive devices so that the commands will work (this is illustrated in the documentation). Then from the documentation and examples you can see how to navigate to the proper menu and submenu items. Then you can
- click menu item menuname
- click button 1
- keystroke “characters”
- keystroke “characters” using control down
- keystroke “characters” using {command down, shift down}
to interact with the application.
One tricky item to note: some of the menu items have 3 dots after the name (e.g. Export…) implying that they will bring up a dialog box. You need to include these dots in the script but sometimes they are 3 periods and sometimes they are an ellipsis (i.e. Apple developers aren’t consistent). You can’t tell by looking, but if the script gets an error try the other one. You enter an ellipsis by typing option/alt-; which gives …
Finally here are 2 scripts for backing up iCal and Address Book archives. The original blog post I referenced above puts the file on the desktop. I have directories setup for these files and you should change the path in the scripts below to what you use on your machine.
tell application "iCal" to activate
delay 2
tell application "System Events"
tell menu item "Back up iCal…" of menu "File" of menu bar 1
of application process "iCal" to click
delay 3
keystroke "g" using {command down, shift down}
delay 2
keystroke "~/Documents/backups/calendar/"
delay 2
keystroke return
delay 2
keystroke return
delay 5
keystroke "q" using command down
end tell
tell application "Address Book" to activate
delay 2
tell application "System Events"
tell process "Address Book"
tell menu bar 1
tell menu bar item "File"
tell menu "File"
tell menu item "Export"
tell menu "Export"
click menu item "Address Book Archive…"
delay 3
keystroke "g" using {command down, shift down}
delay 2
keystroke "~/Documents/backups/address book/"
delay 2
keystroke return
delay 2
keystroke return
end tell
end tell
end tell
end tell
delay 5
keystroke "q" using command down
end tell
end tell
end tell
