问题
I am trying to write an AppleScript that will check if a network drive (in this case, my Time Capsule) is mounted and, if not, mount it. I've figured out how to mount the Time Capsule, but I am at a loss over how to have the script check whether it is mounted first and just exit if it is, or mount it if not.
tell application "Finder"
mount volume "afp://AirPort%20Time%20Capsule._afpovertcp._tcp.local"
end tell
回答1:
Does that the job?
set mountedDiskName to "AirPort Time Capsule"
set diskIsMounted to false
tell application "System Events" to set diskNames to name of every disk
if mountedDiskName is in diskNames then
set diskIsMounted to true
end if
if diskIsMounted then
log "Disk Found, unmounting now..."
do shell script "diskutil unmountDisk" & space & quoted form of mountedDiskName
else
log "Disk Not Found, mounting now…"
mount volume "afp://AirPort%20Time%20Capsule._afpovertcp._tcp.local"
end if
Update
I thought you want to unmount the disk when mounted but that was wrong :) here a shorter version:
tell application "System Events" to set diskNames to name of every disk
if "AirPort Time Capsule" is in diskNames then
display dialog "Disk already mounted" buttons {"OK"} default button 1 with icon 1
else
mount volume "afp://AirPort%20Time%20Capsule._afpovertcp._tcp.local"
end if
…or, if you want the disk name in the dialog:
set diskName to "AirPort Time Capsule"
tell application "System Events" to set diskNames to name of every disk
if diskName is in diskNames then
display dialog quoted form of diskName & " is already mounted." & return buttons {"OK"} default button 1
else
mount volume "afp://AirPort%20Time%20Capsule._afpovertcp._tcp.local"
end if
回答2:
You don’t have to check through a list of all disks. You can just ask if the disk you want exists.
tell application "Finder"
if not (disk "Airport Time Capsule" exists) then
mount volume "afp://AirPort%20Time%20Capsule._afpovertcp._tcp.local"
end if
end tell
回答3:
It seems it doesn't matter whether a share is already mounted or not when using the mount command on Finder with apple script. Just mount it anyway, Finder handles this correctly (it doesn't mount it a second time nor does it complain loudly).
来源:https://stackoverflow.com/questions/29332873/os-x-applescript-to-check-if-drive-mounted-and-mount-it-if-not