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

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 »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »

Price Scanner via MacPrices.net

AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
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
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer 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 MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more
Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more

Jobs Board

Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.