AppleScript and the Finder

Finder
Finder | Source

If you're new to AppleScript, scripting with the Finder is a good place to start. Starting from a new Script Editor window, click on the green 'record' button at the top of the window. Next, go to the dock and choose the Finder.

Now you can get a whole lot of scripting just by clicking around, opening folders, apps, documents, moving things around, many of the actions will be 'recorded' and will appear in the Script Editor window. When you are done, click on the record button again to see your script.

For general basics on AppleScript go to: AppleScript Code Examples

Here is a sample script that was recorded in its entirety:

tell application "Finder"
	activate
	set position of Finder window 1 to {41, 44}
	close Finder window 1
	open application file "Preview.app" of folder "Applications" of startup disk
	open document file "3diMac.jpg" of folder "Images" of folder "Desktop" of folder "MacBookUser" of folder "Users" of startup disk
	open document file "Apple IIc_Screen.jpg" of folder "Images" of folder "Desktop" of folder "MacBookUser" of folder "Users" of startup disk
end tell

And all of this just clicking and double-clicking around my desktop. Of course, to do more sophisticated things with AppleScript you need to learn a bit about it's syntax, but much of that can be learned in a short time and with little agony involved.


Watch the video below for some useful tips on recording scripts:

Rename Folder and Contents and Sort

When you run this script, it acts on the frontmost finder window and its contents, so it is important to have the intended folder in front. As a precaution, the text entry dialogs indicate the folder that the script is about to act upon.

I wrote this script to quickly rename groups of related screen shots for when I want a sequence for a slide show. I included a tell Finder window 1 block, therefore, to sort by creation date ahead of time to retain that order.

Finally, at the end, the documents are sorted again by name:

tell application "Finder"
	try
		set folderName to (name of front Finder window)
		set newFolderName to text returned of (display dialog "Rename current folder:" default answer folderName with title "Folder " & folderName buttons {"Rename", "Cancel"} default button 2 with icon 2)
		set name of folder folderName of desktop to newFolderName
		set itemName to text returned of (display dialog "Enter name for folder items." default answer newFolderName with title "Rename Items of Folder " & newFolderName buttons {"Rename", "Cancel"} default button 2 with icon 2)
		
		tell Finder window 1
			set current view to list view
			set selectionCount to (get count document file)
			tell application "System Events"
				tell process "Finder"
					tell menu item "Show View Options" of menu of menu bar item "View" of menu bar 1 to if exists then click
					tell checkbox "Date Created" of group 1 of window 1 to if value is 0 then click
					keystroke "3" using {control down, command down} --this is by creation date, only works when creation column is visible
					tell menu item "Hide View Options" of menu of menu bar item "View" of menu bar 1 to click
				end tell
			end tell
		end tell
		
		repeat with x from 1 to selectionCount
			set name of item x of window newFolderName to (itemName & " " & x) as text
		end repeat
		
		tell application "System Events"
			tell process "Finder"
				keystroke "1" using {control down, command down} --this is by name
			end tell
		end tell
		
	on error theError number theNumber
		display alert "Error number " & theNumber message theError
	end try
end tell

--keystroke "1" using command down --this is icon view

Open Recent Items

Choose Multiple Items from ‘Choose from List’

This script shows an unconventional use of the ‘choose from list’ command with the Finder. It displays only the items from Apple Menu>Recent Items that are documents or applications and allows you to open multiple items all at once. A few notes follow the script:

tell application "Finder" to activate
delay 0.3
tell application "System Events" to tell process "Finder"
	tell menu 1 of menu item "Recent Items" of menu 1 of menu bar 1
		set menuitems to name of (menu items where position is not missing value and name is not "Applications" and name is not "Documents" and name is not "Servers" and name is not "Clear Menu" and name is not missing value)
		tell application (path to frontmost application as text)
			activate
			set targetItems to (choose from list menuitems with prompt " Choose a recent document or application to open. To select multiple items, shift-click:" with title "Recent Applications and Documents" OK button name "Open" with multiple selections allowed)
		end tell
		repeat with menuItem in targetItems
			click menu item menuItem
		end repeat
	end tell
end tell

If you choose "System Preferences", the result is:

menu item "System Preferences" of menu "Recent Items" of menu item "Recent Items" of menu "Apple" of menu bar item "Apple" of menu bar 1 of application process "Finder" of application "System Events"

This part:

set menuItems to name of (menu items where position is not missing value and name is not "Applications" and name is not "Documents" and name is not "Servers" and name is not "Clear Menu" and name is not missing value)

Eliminates the extraneous items from the items derived from the Recent items submenu.

Then:

repeat with menuItem in targetItems 			
click menu item menuItem 
end repeat 

Opens the chosen document or application or every item chosen from the list dialog, if multiple items have been selected.

As with all scripts that are directed to System Events, you must enable access for assistive devices for this to work.

Trash Old Downloads

Removing Dated Files from a Folder

I use this script for cleaning up the Downloads Folder, but it could be used to delete files from any folder. You could even use a 'choose file' so that you could delete files from different folders at different times. To use this as a droplet, be sure to use the 'Save as Application' option in Script Editor.

on run
set restoreDelimiters to AppleScript's text item delimiters
set AppleScript's text item delimiters to space
set timeLapse to {"1 Day", "2 Days", "1 Week", "1 Month"}
set modDate to (choose from list timeLapse with prompt "Move items to trash whose last modification date is older than:")
set modDate to modDate as text
if modDate contains "1 Day" or modDate contains "2 Days" then
set modDate to text 1 of modDate as integer
else if modDate = "1 Week" then
set modDate to 7 as integer
else if modDate = "1 Month" then
set modDate to 28 as integer
end if
tell application "System Events"
set currentUser to (name of current user)
end tell
tell application "Finder"
activate
set folderExclusions to {"Attachments_2012_06_17", "Recovered files", "Wordpress"}
try
set targetFolder to (folder "Downloads" of folder currentUser of folder "Users" of startup disk)
set deleteDate to ((current date) - modDate * days) as string
set fileCounter to (count items in targetFolder)
repeat
if name of item fileCounter of targetFolder is not in (items of folderExclusions) then
if (modification date of item fileCounter of targetFolder < ((current date)) - modDate * days) then
delete item fileCounter of targetFolder
end if
end if
set fileCounter to fileCounter - 1
if fileCounter = 0 then exit repeat
end repeat
display alert "Empty Trash ?" message "Are you sure you want to empty contents of the trash ? This cannot be undone." buttons {"Empty", "Cancel"} default button 2 as critical
set trashConfirm to button returned of the result
if trashConfirm = "Empty" then tell application "Finder" to empty trash
set AppleScript's text item delimiters to restoreDelimiters
on error errorMsg
activate
display dialog errorMsg
set AppleScript's text item delimiters to restoreDelimiters
end try
end tell
end run

Converting Lowercase Characters to Uppercase

This is a good study of the differences of AppleScript syntax when it comes to converting lowercase text to uppercase text. This first one with AppleWorks 6 and then a slightly different version for FileMaker:

This is given the text:

"delila was the kind of girl who could cut down trees and split logs better than most men."

tell application "AppleWorks 6"
	try
		set targetConvert to (get every text of document 1)
		set targetConvert to my convert2Upper(targetConvert)
		set text of front document to targetConvert
	on error errorText
		display dialog errorText
	end try
end tell

on convert2Upper(theText)
	set lowerChars to "abcdefghijklmnopqrstuvwxyz"
	set upperChars to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	set convertedText to ""
	repeat with theChar in theText
		set x to the offset of theChar in lowerChars
		if x is not 0 then
			set convertedText to (convertedText & character x of upperChars) as string
		else
			set convertedText to (convertedText & theChar) as string
		end if
	end repeat
	set targetConvert to convertedText
	return targetConvert
end convert2Upper

And now with FileMaker 9:

tell application "FileMaker Pro Advanced"
try
	set targetConvert to (get data of cell "Notes" of current record)
	set targetConvert to my convert2Upper(targetConvert)
	set data of cell "Notes" of current record to targetConvert
on error errorText
	display dialog errorText
end try
end tell

on convert2Upper(theText)
	set lowerChars to "abcdefghijklmnopqrstuvwxyz"
	set upperChars to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	set convertedText to ""
	repeat with theChar in theText
		set x to the offset of theChar in lowerChars
		if x is not 0 then
			set convertedText to (convertedText & character x of upperChars) as string
		else
			set convertedText to (convertedText & theChar) as string
		end if
	end repeat
	set targetConvert to convertedText
	return targetConvert
end convert2Upper

Both result in the uppercase text:

"DELILA WAS THE KIND OF GIRL WHO COULD CUT DOWN TREES AND SPLIT LOGS BETTER THAN MOST MEN"

These both work in a similar fashion, but, as mentioned before, you must know the object to which you are directing the statements ie: document 1 for AppleWorks or cell "Notes" in the case of FileMaker.

Furthermore, one of the most critical parts of convert2Upper(targetConvert) in the previous 2 scripts and convert2Lower(targetDocName) in the script below, is the offset function. It determines the exact location of a given alphabetical character (from a - z) in order to determine the replacement text in upper case (A - Z)

Now, one last similar script, which converts uppercase file names in the current Finder window to lowercase text:

tell application "Finder"
	try
		set itemCount to (count items in front Finder window)
		repeat with x from 1 to itemCount
			set targetDocName to (get name of item x of front Finder window)
			set targetDocName to my convert2Lower(targetDocName)
			set name of item x of front Finder window to targetDocName
		end repeat
		display alert "Lower Case Conversion" message "Conversion of upper case to lower case is complete" as informational
	on error errorText number errorNumber
		display alert errorNumber message errorText as critical
	end try
end tell

on convert2Lower(docName)
	set lowerChars to "abcdefghijklmnopqrstuvwxyz"
	set upperChars to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	set convertedName to ""
	repeat with theChar in docName
		set x to the offset of theChar in upperChars
		if x is not 0 then
			set convertedName to (convertedName & character x of lowerChars) as string
		else
			set convertedName to (convertedName & theChar) as string
		end if
	end repeat
	return convertedName
end convert2Lower

For larger volumes of text, there might be a better method for all of these, but for purposes of instruction for ordinary (average size data), these work quite nicely.

More by this Author

  • AppleScript and FileMaker
    4

    Learning How to Write FileMaker Pro Scripts for Beginners. Free AppleScripts for those who are new. Many scripts are a mix of AppleScript and FileMaker.

  • Free AppleScript Code Examples
    1

    Write AppleScript Code,free AppleScripts of display dialog,display alert,choose from list,finder,choose file,choose file name,choose folder,choose application,choose color,Finder,TextEdit

  • More Advanced AppleScript Code
    0

    For those of you who still cannot get enough AppleScript to feed your fix, some more free applescript code,Finder,Microsoft Word,Pages,AppleWorks,PowerPoint,TextEdit,iTunes,POSIX paths,database events


Comments, Suggestions or Bugs ?

No comments yet.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working