AppleScript Folder Action: Auto-Rename File

June 26th, 2010  Posted at   AppleScript, OS X
arrow   |   1 Commentarrow

In my last post I described my goal to make an auto-rename Folder Action for my Desktop folder, specifically for handing scan files generated by Image Capture.

Now it’s time to talk about the actual script that does the work. The script is called whenever new files are added to the Desktop folder. If the file to be renamed exists, the script does its work.

First activity is to get the date and time and format them into a string as I desire. The default date/time string given by AppleScript looks like this: Saturday, June 26, 2010 4:02:15 PM. That’s lovely for humans to see in a document, but far from what I want in a filename. I want this: 20100626_160215.

So I get the datetime, format it, make a new filename with the formatted datestamp in it, and tell Finder to rename the file. The main Folder Action handler script is below.

on adding folder items to this_folder after receiving added_items
	try
		set oldFileName to "scan_to_auto_rename.pdf"
		set oldFilePath to ((path to desktop folder as text) & oldFileName)

		tell application "Finder"
			if not (exists file oldFilePath) then
				return -- nothing to do
			end if
		end tell

		-- Build the pathname to the util library.
		set utilLibPath to ((path to home folder as string) & "Scripts:mt_util_library.scpt")

		-- Open the util library.
		set utilLib to load script (alias utilLibPath)

		set ds to utilLib's datestamp()

		set newFileName to "scan_" & ds & ".pdf"

		tell application "Finder"
			set name of file oldFilePath to newFileName
		end tell

	end try
end adding folder items to

Here’s a more detailed breakdown of what’s happening in the script.

1. Make sure file to rename exists. Exit if it doesn’t.
2. Since I moved the datestamp formatting function to its own file, we must open that file (“library”).
3. Get the formatted datestamp string.
4. Create the new filename.
5. Tell Finder to change the name of the old file to the new name.

See the next post for details on my utility script that provides the datestamp formatting.

One Response to “AppleScript Folder Action: Auto-Rename File”

  1. [...] About « AppleScript Folder Action: Auto-Rename File [...]

Leave a Reply

You must be logged in to post a comment.