Eject nearly any disk via AppleScript

Feb 22, '09 07:30:00AM

Contributed by: renaultssoftware

I'm a very keyboard-based person; I use a keyboard shortcut whenever I can. David Pogue tells of KIAFTMA -- the Keyboard Is Always Faster Than the Mouse Association. So the fact that the Eject key is restricted to the optical drive frustrates me.

To solve the problem, I created an AppleScript to make this easy for me. It calls on the disk powers of System Events and Finder; that way, you can eject any disk (except volumes over intranets like a home network) with a keystroke or two. Here is the code I used:

tell application "System Events" -- I don't target the Finder
  set diskNames to every disk -- gets the list
  set diskCount to count disks -- this is important for list 'triage'
  if diskCount = 0 then -- if an empty list
    beep
  else if diskCount = 1 then -- if one item to eject
    tell application "Finder" to eject (item 1 of diskNames) -- gets the first - and only - item of diskNames; Sys Events cannot eject disks; I could have added a line before
  else if diskCount > 1 then -- if 2 or more items to eject
    set disksToEject to choose from list diskNames with prompt "Select a disk to eject:" OK button name "Eject" with multiple selections allowed
    if disksToEject is not false then -- if you didn't cancel; this avoids the system and you confusion
      tell application "Finder"
        repeat with theDisk in disksToEject -- every disk you chose
          eject theDisk -- duh!
          -- a whole lot of "end blocks"
        end repeat
      end tell
    end if
  end if
end tell
(* Ejector by KOMPILEsoft *)
[robg adds: I tried testing this one, but I can't get it to work on my Mac. It works fine on the author's Mac, though, so I'm publishing it under the assumption it's something about my machine. Please post your experiences.]

Comments (1)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20091130123607259