Trying out auto-mounting network shares with AppleScript
I wanted a neater way of auto-mounting network shares on startup than simply sticking the path in Login items so I thought I'd search around and see what methods were available.
I finally settled on using a bit of AppleScript to first check if the mount point exists and, if not, to attempt to mount the network share.
1 2 3 4 5 6 7 8 9 | tell application "Finder" if not (exists POSIX file "/Volumes/Data") then try mount volume "afp://some-server.local/Data" end try else display dialog "Already Mounted" end if end tell |
Given that I wanted to mount multiple shares, putting the above in a function seemed like the way to go. Unfortunately, no matter what I tried, passing the path to Finder as a variable caused the test to always fail - even though though the path could be displayed via dialog as well as appearing in the AppleScript Editor's Events box. After finally giving up on that, I switched to a bash style test and all was well.
So, after all that, the function mountSmbShare() checks if the directory exists and, if not, tells Finder to mount it. It takes the remote and local paths as values - the local to allow for checking. I might try improving it so that it splits the remote path on the "/" then using the last value in the resulting array to work out the local path but it'll do for now.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | on mountSmbShare(smbShare, mountPoint) if (do shell script "if [ -d " & quoted form of mountPoint & " ]; then echo '0'; else echo '1'; fi") is "1" then tell application "Finder" try mount volume smbShare end try end tell end if end mountSmbShare mountSmbShare("smb://server.local/Multimedia", "/Volumes/Multimedia") mountSmbShare("smb://server.local/Whatever", "/Volumes/Whatever") mountSmbShare("smb://server.local/Public", "/Volumes/Public") mountSmbShare("smb://server.local/www", "/Volumes/www") |
I export the script to an application in ~/bin and add it to my Login items and - bam! - my shares are all automagically mounted every time I login. Happy days.
So that was my fun introduction to AppleScript. Always nice to play with something new (to me) but I probably would have been better served sticking with bash.
Comments
Post a Comment