Automatically Eject a Backup Drive with Keyboard Maestro

Continuing with our Keyboard Maestro theme for the week, here's one more for you. I have a 1TB USB Hard Drive I keep attached to my Mac and use Carbon Copy Cloner to create daily clones to that drive. I want the drive to remain attached to my Mac so I don't have to remember to plug or unplug the disk each day to create the backup. However, I don't want to drive to be mounted on my Mac all day because it can create problems with launching applications or searching for files, finding the clone drive rather than my main system volume. (Yes, I've set the drive to be excluded in Spotlight).

Carbon Copy Cloner allows me to run a script to automatically mount my drive before a clone job, and will unmount the drive after. So having the drive mounted for the clone operation is not a problem. So, I set a Keyboard Maestro Macro to run at login to eject my clone drive. While this implementation isn't perfect, it catches most instances of my drive auto-mounting because my system restarted or I logged out and back in. Notably, I did not want to set a Macro to run when the volume was attached, because I need the volume to mount in order to create my clone operation.

I set the Macro to run at login and execute an AppleScript to unmount the drive. The AppleScript is as follows where you substitute "diskname" on the first line only for your volume's name as appropriate:

set diskName to "diskname"
tell application "Finder"
if disk diskName exists then
eject disk diskName
tell current application
set deviceLine to (do shell script "diskutil list | grep \"" & diskName & "\" | awk '{ print $NF }' }'")
if deviceLine = "" then
display dialog "The disk \"" & diskName & "\" cannot be found." buttons {"OK"} default button 1 with title "Error" with icon caution
end if
set foundDisks to paragraphs of deviceLine
repeat with i from 1 to number of items in foundDisks
set this_item to item i of foundDisks
if this_item contains "disk" then
do shell script "diskutil mountDisk /dev/" & this_item
end if
end repeat
end tell
end if
end tell
Screen Shot 2013-09-08 at 3.58.04 PM.JPG