user1274426
user1274426

Reputation:

How to run an AppleScript automatically once I insert a USB drive?

I need to rename and fill about 70 USB sticks. Having an Applescript run automatically when they are inserted would make it much simpler.

Upvotes: 2

Views: 5260

Answers (1)

kopischke
kopischke

Reputation: 3413

Any external drive you connect to an OS X machine is mounted into /Volumes. If you watch that folder for changes, you can pick up on added external drives and process these. Running this code:

property ignoredVolumes : {"Macintosh HD", "Time Machine Backups"} -- add as needed
tell application "System Events"
    set rootVolume to disk item (POSIX file "/Volumes" as text)
    set allVolumes to name of every disk item of rootVolume
    repeat with aVolume in allVolumes
        if aVolume is not in ignoredVolumes then
            set name of disk item (path of rootVolume & aVolume) to newName
        end if
    end repeat
end tell

will rename drives that are not in your ignoredVolumes list (unplug all but those you want to ignore, run ls /Volumes in Terminal and add the names to the property) to newName. To have this triggered on every change, modify the codes to be a Stay-Open script application:

property pollIntervall : 60 -- in seconds
property ignoredVolumes : {…} -- from above

on run
    my checkVolumes()
end run

on idle
    my checkVolumes()
    return pollInterval
end idle

on checkVolumes()
    tell … end tell -- from above
end checkVolumes

and save it in AppleScript Editor (select “AppleScript application”, make sure you tick “Stay Open” when you do). Once launched, the script will keep running, executing the on idle handler every pollInterval seconds.

This will do fine if you are basically doing a once-in-a-while batch job. If you want a more permanent solution that does not rely on running a stay-open script application, you can either

Upvotes: 5

Related Questions