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

Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »

Price Scanner via MacPrices.net

New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more
Sunday Sale: Apple iPad Magic Keyboards for 1...
Walmart has Apple Magic Keyboards for 12.9″ iPad Pros, in Black, on sale for $150 off MSRP on their online store. Sale price for online orders only, in-store price may vary. Order online and choose... Read more
Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more

Jobs Board

DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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
IT Systems Engineer ( *Apple* Platforms) - S...
IT Systems Engineer ( Apple Platforms) at SpaceX Hawthorne, CA SpaceX was founded under the belief that a future where humanity is out exploring the stars is Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.