TweetFollow Us on Twitter

A platform for protecting mail servers.

Volume Number: 20 (2004)
Issue Number: 6
Column Tag: Programming

AppleScript Essentials

by Benjamin S. Waldie

Introduction to Scripting the Finder

Last month, we looked at the user interaction functionality in the Standard Additions scripting addition. This month, we are going to get started with some basic Finder scripting. We will briefly look at the Finder's dictionary, recording in the Finder, and some basic folder maintenance. In the future, we will explore other aspects of Finder scripting in greater detail.

Finder Basics

Accessing the Finder Dictionary

The first thing to note is that the Finder is not the Mac OS. The Finder is simply an application in the Mac OS, and it provides you with a graphical interface for navigating and organizing your computer's file and folder structure.

The Finder can be found in the System > Library > CoreServices folder on your computer. Please note that, much like any other application on your computer, the Finder's version number typically changes when newer system software becomes available. With these version changes, frequently comes new and/or modified AppleScript functionality, and updates to your existing code may be required.

Like many other applications on the Mac, the Finder is scriptable, and therefore contains an AppleScript dictionary. The Finder's AppleScript dictionary contains all of the AppleScript commands, objects, and properties that the Finder understands.

To open the Finder's dictionary, launch the Script Editor, located in Applications > AppleScript. Then, select Open Dictionary from the File menu. You may also open the Finder's dictionary from the Library palette in the Script Editor. If this palette is not visible, select Library from the Window menu in order to make it visible.


Figure 1. The Finder Dictionary

As you look through the Finder's dictionary, you will see that it is broken up into different sections, or suites. These suites help to organize the dictionary into groups of related objects, properties, and commands, making the dictionary easier to navigate.

You may notice that certain things in the Finder's dictionary indicate a note of "NOT AVAILABLE YET". For example:

Finder preferences  preferences  [r/o]  -- (NOT AVAILABLE YET)

This indicates functionality that was present in Mac OS 9, but has not yet been fully implemented into Mac OS X. This is due to fundamental differences in the way that the Finder behaves in Mac OS X, versus Mac OS 9.

Finder Recording

You may be aware that, in addition to being AppleScriptable, some applications on the Mac are also AppleScript recordable. What this means is that you can click a Record button in the Script Editor and then perform the desired actions in the recordable application. Then, when you come back to the Script Editor, your code has been written for you. This is a method frequently adopted by beginner AppleScripters.

As you may have guessed, one such recordable application in Mac OS X Panther (10.3) is the Finder. Please note that if you are using an older version of Mac OS X, this functionality is not present. While Finder scriptability is present in older versions of Mac OS X, the recording feature was not re-introduced until the release of Mac OS X Panther (10.3). The reason I say the word "re-introduced" is because the Finder was recordable in Mac OS 9. Also, although the Finder is recordable in Mac OS X Panther (10.3), you may notice that it will not record absolutely every single task that you perform.

    Please note that not all scriptable applications on the Mac are recordable. Only certain scriptable applications are recordable. Some popular recordable applications include - BBEdit, MultiAd Creator, QuickTime Player, Stuffit Deluxe, and Tex-Edit Plus.

Figure 2 shows a basic script that was recorded in the Finder. This particular recorded script creates a folder on the desktop, and renames it to My Folder.


Figure 2. A recorded Finder Script

Writing Vs. Recording

So, why record? Recording in the Finder, or any recordable application for that matter, can provide a quick and easy way to get started with scripting a particular application. If you are finding an application's dictionary to be complex and difficult to navigate, or perhaps you just can't seem to get your syntax quite right, then recording can be a tremendous help. By recording a quick script, you will probably find the syntax that you are looking for, and all with only a few clicks of the mouse.

While recording appears to be a simple answer for those looking to learn AppleScript, it is not always the best option for the job. There are some disadvantages to recording. For one, a recorded script contains no logic. It simply contains a series of AppleScript statements to perform a set of tasks. Because of this, the script cannot evaluate situations or data in order to take different courses of action. A recorded script will attempt to perform the exact same tasks time and time again.

Take, for example, the script I recorded a little earlier. If I ran the script as soon as I finished recording, I would have received an error message.


Figure 3. An Example of a Recorded Script Error

In this example, the script created a new folder on my desktop and attempted to change its name to My Folder. However, a folder named My Folder already existed on my desktop, thus causing the script to produce the error message.

Ideally, a script of this nature would be written to anticipate such a scenario, and take a specific course of action based on whether or not a folder with the same name already existed. For example, the script could be written to check to see if a folder with the name My Folder exists, and only create the folder if it does not exist.

set theOutputFolder to path to desktop folder as string
tell application "Finder"
   set theFolderToCheck to theOutputFolder & "My Folder"
   if (folder theFolderToCheck exists) = false then
      make new folder at desktop with properties {name:"My Folder"}
   end if
   open folder theFolderToCheck
end tell

Another limitation of recorded scripts is that they contain no variables, handlers, if/then statements, or repeat loops. Because of this, recorded scripts are typically very verbose, and contain a lot of unnecessary and repetitive code. For example, let's say that you want a script that will create ten folders, and name them from 1 to 10. To record this functionality, you would need to click record in the Script Editor, and then actually create ten folders and rename them manually. Doing this for ten folders may not be too time consuming, but what if you needed to do it for a hundred folders, or a thousand? In order to do this, you would be much better off writing the script than recording it. With only a simple repeat loop and a few lines of code, you could write in a few moments what would take you quite a while to record. In addition, your code would be much shorter, more efficient, more expandable, etc. The following example of written code will create 100 folders in a user specified output folder, and rename them from 1 to 100.

set theOutputFolder to choose folder
tell application "Finder"
   repeat with a from 1 to 100
      make new folder at theOutputFolder with properties {name:a as string}
   end repeat
end tell

The sample code displayed above does not contain any error protection or handling to check for existing folders with the same names, but this could be added into the script, if necessary, with only a few extra lines of code.

With recorded scripts, you can also go back in, once recording is complete, and clean up and improve the code. This is a suggested procedure if you do choose to record your scripts.

Folder scripting

Creating a Folder

As you have already seen from some of the code above, creating a folder in the Finder is fairly straightforward. The following code, which will create a new folder on the desktop, illustrates this again:

tell application "Finder"
   make new folder at desktop
end tell

Once a folder has been created, you will probably want to store a reference to a newly created folder in a variable. This way, you can actually do something with the folder, such as assign a name to it, move it, open it, etc.

tell application "Finder"
   set theFolder to make new folder at desktop
   set name of theFolder to "My Folder"
end tell

Please note that since the code above will rename the folder, whose reference has been stored in a variable, the variable will no longer link to the folder once it has been renamed. Therefore, you will need to alias the folder reference once it has been created, or re-create your variable to link to the newly renamed folder. For example:

This code will alias the folder reference, causing the reference to the folder to dynamically update, regardless if the folder is renamed or moved.

tell application "Finder"
   set theFolder to (make new folder at desktop) as alias
   set name of theFolder to "My Folder"
   open theFolder
end tell

This code will recreate the variable containing the folder reference, after the folder has been renamed:

tell application "Finder"
   set theFolder to make new folder at desktop
   set name of theFolder to "My Folder"
   set theFolder to folder ((path to desktop folder as string) & "My Folder")
   open theFolder
end tell

In some cases, you may want to specify certain properties of a folder, such as a name or a comment, during its creation, rather than after it has been created. This can help to shorten your code and make it more efficient.

tell application "Finder"
   set theFolder to make new folder at desktop with properties {name:"My Folder", 
   comment:"Test comment"}
   open theFolder
end tell

Working with Folders

Sometimes, when working with a folder, you may notice that the Finder's interface does not update immediately. This sometimes will occur when creating a new folder or file, or when moving, copying, or deleting a folder or file. To cause the Finder to update immediately, simply use the update command, which will immediately refresh the view of the path specified.

tell application "Finder"
   update (path to desktop folder)
end tell

When working with folders, you may want to customize the look and feel of an opened folder. For example, you may want to change the view of the folder to list view, icon view, or column view. Or, you may want to change the size and/or position of the window to default settings. To do this, you need to actually work with the window of the folder, rather than the folder itself. The following sample code will create a folder, open it, set it to list view, and resize it to a predefined size.

tell application "Finder"
   set theFolder to make new folder at desktop with properties {name:"My Folder"}
   open theFolder
   set current view of window of theFolder to icon view
   set bounds of window of theFolder to {13, 69, 470, 396}
end tell

In Closing

This general introduction should help you to get started with scripting the Finder. In the future, we will begin to take a more in-depth look at the different aspects of Finder scripting.

In the meantime, be sure to check out the sample Finder scripts that are already built right into your system. You can find these sample scripts under Applications > AppleScript > Example Scripts > Finder Scripts folder on your hard drive. These scripts will also appear in your Script Menu, if it has been enabled on your machine. These sample Finder scripts are unlocked, and fully editable for you to explore and enhance. You can also find additional sample Finder scripts on Apple's AppleScript web site at http://www.apple.com/applescript/toolbar/.

Until next time, keep scripting!


Benjamin Waldie is president of Automated Workflows, LLC, a firm specializing in AppleScript and workflow automation consulting. In addition to his role as a consultant, Benjamin is an evangelist of AppleScript, and can frequently be seen presenting at Macintosh User Groups, Seybold Seminars, and MacWorld. For additional information about Benjamin, please visit http://www.automatedworkflows.com, or email Benjamin at applescriptguru@mac.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.