In relation to my article on Combining PDFs in Apple Automator, I needed to automate moving files from one location to another, with the final destination name of the file being different than the original. At first I thought this would be 5 minutes in AppleScript, until I realized, as with all programming, that I would run into programming language complexities. The first one was moving to a mounted location, the second was formatting dates and the third was getting a single object in the array, added_items, to output the UNIX style path.
The script to accomplish this task ended up looking like this:
on adding folder items to this_folder after receiving added_items
repeat with this_item in added_items
set destpath to "/Volumes/[mount name]/[share]/" as string
set datestring to ((year of (current date)) * 10000) + ((month of (current date) as integer) * 100) + (day of (current date)) as integer
set destfilename to "thefile_" & datestring & ".pdf" as string
set sourcepath to POSIX path of this_item
end repeat
end adding folder items to
If you are familiar with Visual Basic, the “repeat with this_item in added_items” would be similar to “for each this_item in added_items”. This creates a single object (this_item) from the array of objects (added_items). The destpath is a variable of the location that we will write the final file, which in this case is a mounted server.
datestring
The date format was not as easy to accomplish as I would have expected, especially considering that AppleScript is supposed to simple to use with its English language type structure. To create a date of 20100101, I had to use traditional math starting with the current year multiplied by 10000, which would end up:
2010 * 10000 = 20100000
Next I needed to add the month in the appropriate location in the integer. This was accomplished by current month multiplied by 100, which would end up:
01 * 100 = 100
Add the month to the year integer and you have:
20100000 + 100 = 20100100
Finally, we need to add the day, which as you can imagine, needs no modification:
20100100 + 01 = 20100101
The final number is stored in the variable datestring.
sourcepath
After about 30 minutes of frustration, working with other avenues to accomplish the same task, I finally found an AppleScript example that used “POSIX path of”. Being that I am a native Windows guy, POSIX is fairly foreign to me, however, it is key to making sure the shell command, “mv”, works properly.
If you were to use:
set sourcepath to name of this_item
you would get a path separated with colons, such as harddrive:Volumes:[mount name]:[share], which is clearly useless in a shell environment. So instead, we must request the POSIX path, which is the full path and file name of “this_item”:
set sourcepath to POSIX path of this_item
That is it…assign this script to a folder using the Folder Actions functionality of the Mac operating system.
-Aaron Gilbert