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

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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.