Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
AppleScript to eject mounted local disks. Written for when I'm going to take my laptop off my desk and am disconnecting from my TB hub.
-- AppleScript I wrote to eject mounted USB disks before I disconnect my USB-C hub.
-- Notes:
-- this will halt a time machine backup to a locally mounted
-- drive when it tries to eject it.
-- will also halt a time machine backup to a network destination.
-- tested in macOS 11.6 (2021.11.19)
-- License: MIT
tell application "System Events"
set ds to get disks
-- for debugging
if false then
log "list of disks: "
repeat with d in ds
log (get the URL of d)
log (get the name of d)
end repeat
end if
log ("Ejecting local ejectable volumes")
repeat with d in ds
-- before we try to do anything with this disk
-- try to access the disk and catch any errors
-- as a way to test if the disk is still present.
-- set a flag that we can test below.
set diskAvailable to true
set trashme to (get the name of d)
on error errormsg number errorno
if errorno is -1728 then set diskAvailable to false
end try
-- Notes:
-- ejectable excludes sparse volume mounts for time
-- machine, but also means other ejectables aren't unmounted…
-- ...decided to remove this in the if clause below and let it halt
-- time machine backups even for network volumes also
-- since I'm generally calling this script when I'm disconnecting
-- the laptop and heading out.
-- d is not ejectable and ¬
-- starts with "Data@" excludes time machine local snapshot
-- mounts during backups
-- starts with file:///Volumes excludes file:///System/Volumes/...
-- system volumes.
-- local volume excludes network mounts
if diskAvailable and ¬
d is local volume and ¬
the URL of d starts with "file:///Volumes/" and ¬
the displayed name of d does not start with "Data@" then
log ("........ ejecting: " & (get the name of d))
tell application "Finder" to eject (get the name of d)
else if diskAvailable then
log (" Skipping: " & (the URL of d))
log (" Skipping disk that is no longer available")
end if
end repeat
log (" all ejectable local volumes ejected")
end tell
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment