The Scriptable Finder

The Finder in the Mac OS can be controlled using the AppleScript language in the same way as any other application. However, to avoid damaging or losing documents, it should be used with care.

Desktop Items

The scriptable Finder can process items on the desktop in the same way as a human user, allowing you to create scripts that eliminate the need for boring and repetitive tasks.

File Path Shortcuts

The Finder provides useful, though limited, shortcuts to standard folders. Those supported by the Classic Mac OS shown are shown here, with the results shown in italic:-

tell application "Finder"

  apple menu items folder as alias --> alias "…System Folder:Apple Menu Items:"

  control panels folder as alias --> alias "…System Folder:Control Panels:"

  desktop as alias --> alias "…Desktop Folder:"

  extensions folder as alias --> alias "…System Folder:Extensions:"

  fonts folder as alias --> alias "…System Folder:Fonts:"

  preferences folder as alias --> alias "…System Folder:Preferences:"

  shutdown items folder as alias --> alias "…System Folder:Shutdown Items:"

  trash as alias --> alias "…Trash:"

  startup items folder as alias --> alias "…System Folder:Startup Items:"

  startup disk as alias --> alias "Macintosh HD:"

  system folder as alias --> alias "…System Folder:"

  temporary items folder as alias --> alias "…Temporary Items:"

end tell

Remember, the term alias has nothing to do with an ordinary alias. Instead, it provides a fixed reference to an item that remains valid even when the item is renamed or moved.

These terms can also be used to generate a reference, as in this example:-

startup items folder as reference

  --> folder "Startup Items" of folder "System Folder"¬

      of startup disk of application "Finder"

The path to instruction, provided by the Standard Additions file in the Scripting Additions folder of the Classic Mac OS, gives a greater range of shortcuts, as shown below:-

path to apple menu --> alias "…System Folder:Apple Menu Items:"

path to application support --> alias "…System Folder:Application Support:"

path to control panels --> alias "…System Folder:Control Panels:"

path to control strip modules --> alias "…System Folder:Control Strip Modules:"

path to desktop --> alias "…Desktop Folder:"

path to desktop pictures folder --> alias "…System Folder:Appearance:Desktop Pictures:"

path to editors folder --> alias "…System Folder:Editors:"

path to extensions --> alias "…System Folder:Extensions:"

path to Folder Action scripts --> alias "…Scripts:Folder Action Scripts:"

path to fonts --> alias "…System Folder:Fonts:"

path to help folder --> alias "…System Folder:Help:"

path to modem scripts --> alias "…Extensions:Modem Scripts:"

path to internet plugins folder --> alias "…System Folder:Internet Plug-Ins:"

path to launcher items folder --> alias "…System Folder:Launcher Items:"

path to preferences --> alias "…System Folder:Preferences:"

path to printer descriptions --> alias "…System Folder:Printer Descriptions:"

path to printer drivers --> alias "…System Folder:Printer Drivers:"

path to printmonitor --> alias "…System Folder:PrintMonitor Documents:"

path to scripting additions --> alias "…System Folder:Scripting Additions:"

path to shared libraries --> alias "…System Folder:Extensions:"

path to stationery folder --> alias "…Documents:Stationery:"

path to shutdown items folder --> alias "…System Folder:Shutdown Items:"

path to trash --> alias "…Trash:"

path to startup items folder --> alias "…System Folder:Startup Items:"

path to startup disk --> alias "Macintosh HD:"

path to system folder --> alias "…System Folder:"

path to temporary items --> alias "…Temporary Items:"

path to voices --> alias "…System Folder:Extensions:Voices"

The word folder can be added to the end of those path to terms that don’t already include it. Some of the terms shown above that don’t include the word folder automatically gain this appendage at compilation, should you fail to enter it manually.

Mac OS X extends the function of the path to command, as in these examples:-

path to preferences folder from user domain

path to preferences folder from local domain

path to help folder from System domain

and in these shortcuts:-

path to "cusr"

path to "dlib"

path to "favs"

path to "ssnd"

path to "usrs"

Traditionally, the Mac OS employs a : (colon) to separate the elements in a path, whilst Mac OS X can use POSIX paths, in which the parts are separated by a / (slash). You can convert ‘classic’ paths into the newer form using the POSIX path instruction, as provided by the Standard Additions scripting addition in the Classic Mac OS. Here’s an example:-

tell application "Finder"

  set theFldr to folder "Documents" of startup disk

  return POSIX path of (theFldr as text)

end tell

  --> "/Macintosh HD/Documents/"

Folders and Containers

AppleScript allows you to refer to the folder or disk that encloses an item, as in:-

set theFldr to folder of alias "****"

  --> folder "Extras" of folder "Documents" of startup disk of application "Finder"

set theFldr to folder of alias "****" as alias

  --> alias "Macintosh HD:Documents:"

set theFldr to folder of alias "****" as text

  --> "Macintosh HD:Documents:"

set theDsk to disk of alias "****"

  --> startup disk of application "Finder"

set theDsk to disk of alias "****" as alias

  --> alias "Macintosh HD:"

set theDsk to disk of alias "****" as text

  --> "Macintosh HD:"

Note that the path to a folder always ends in a : (colon), which distinguishes the path from that of a file. If you need the name of a folder or disk you should use the name instruction, as in:-

set theDsk to name of disk of alias "****"

  --> "Macintosh HD"

Sometimes, the nature of what encloses a file isn’t known, as, for example, on a network or where a file is at an unknown location. In these situations you can use the term container, as in:-

set theCntnr to container of alias "****"

  --> folder "Extras" of folder "Documents" of startup disk of application "Finder"

set theCntnr to container of alias "****" as alias

  --> alias "Macintosh HD:Documents:"

set theCntnr to container of alias "****" as text

  --> "Macintosh HD:Documents:"

Note that the above commands always report an error if the file within a folder or container is invisible. Also, any item on the desktop gives a result of desktop of application "Finder".

Fortunately, these lines work even for the invisible items shown here:-

set theFile to alias "Macintosh HD:System Folder:VolumeNameIconPict"

  --> alias "Macintosh HD:System Folder:VolumeNameIconPict"

set theFile to alias "Macintosh HD:System Folder:VolumeNameIconPict" as reference

  --> alias "Macintosh HD:System Folder:VolumeNameIconPict" of application "Finder"

set theFldr to alias "Macintosh HD:Temporary Items:"

  --> alias "Macintosh HD:Temporary Items:"

set theFile to alias "Macintosh HD:System Folder:VolumeNameIconPict" as text

  --> "Macintosh HD:System Folder:VolumeNameIconPict"

Sadly, the following don’t work with invisible items, although they’re fine otherwise:-

set theFile to file "Macintosh HD:System Folder:VolumeNameIconPict"

  --> ‘Finder got an error because the original item cannot be found’

set theFile to item "Macintosh HD:System Folder:VolumeNameIconPict"

  --> ‘Finder got an error because the original item cannot be found’

set theFldr to folder "Macintosh HD:Temporary Items:"

  --> ‘Finder got an error because the original item cannot be found’

Checking that Items Exist

You can check the existence of an item using either of the following:-

exists file "Macintosh HD:Test Document"

  --> true

exists alias "Macintosh HD:Test Document"

  --> true

and you can use the following to check that an item’s on the desktop:-

exists file "Macintosh HD:Desktop Folder:Document on Desktop"

  --> true

exists file "Document on Desktop"

  --> true

but you can’t refer to such a file as an alias, as in:-

exists alias "Document on Desktop"

  --> ‘File Document on Desktop wasn't found’

since the term alias always requires you to include the full path of an item.

Finally, you can include checking for an item in a conditional statement, as in:-

if not (exists file "Macintosh HD:Test Document") then

Disk Drives

Information about your drives can be obtained using lines such as:-

set sysDskNm to name of startup disk

  --> "Macintosh HD"

free space of disk "Macintosh HD"

  --> 2.422775808E+9

You can also use such information in conditional statements, as in:-

if free space of disk of destFolder < size of chosenFolder then

  error "There isn’t enough space."

end if

Moving and Opening Items

Files or folders can be selected and processed using references, as in:-

tell application "Finder"

  set theFldr to folder "files" of folder "temp" of disk "Macintosh HD"

  move (every file of theFldr whose name contains¬

    "test" and name contains ".htm") to trash

end tell

  --> file "test.htm" of trash of application "Finder"

which, in this instance moves the one file to the Trash. In the Classic Mac OS this can be written as:-

tell application "Finder"

  move (every file of folder¬

   "Macintosh HD:temp:files:" whose name contains "test" and name contains ".htm") to trash

end tell

  --> file "test.htm" of trash of application "Finder"

where the folder is defined as a path, ending in a : (colon) to indicate that it really is a folder.

Opening a disk, folder or file is very easy, as in:-

tell application "Finder"

    open alias "Macintosh HD:"

end tell

which simply opens the window of the drive called Macintosh HD. The terms disk, folder and file can be used instead of alias in such a statement, although they don’t work if the item is no longer at its original location or doesn’t have its original name.

The next Classic Mac OS script opens a folder that resides alongside the file of an application:-

tell application "Finder"

  activate

  open folder ( ( (folder of application file id "R*ch") as text) & "BBEdit Support")

end tell

  --> folder "BBEdit Support" of folder "BBEdit 6.5" of folder "Applications¬

    (Mac OS 9)" of startup disk of application "Finder"

A similar approach can be used to force the Finder in the Classic Mac OS to open a document using a specific application. This example, for instance, opens a chosen file in Netscape:-

tell application "Finder"

  open file "****" using application file id "MOSS"

end tell

since MOSS is the creator code for this application.

Creating Items

You can create standard aliases to any item. This example makes an alias in a folder on the desktop:-

make alias to file "Document on Desktop" at folder "untitled folder"

  -->file "Document on Desktop" of folder "untitled folder" of application "Finder"

while this simply creates an alias on the desktop itself:-

make alias to selection at desktop

  --> file "Document on Desktop alias" of application "Finder"

Finally, this example makes new folder inside a selected folder on the desktop:-

make new folder in selection

  --> folder "untitled folder" of folder "The Folder" of application "Finder"

In this version you also give the folder a name:-

make new folder in selection with properties {name:"New Folder"}

  --> folder "New Folder" of folder "The Folder" of application "Finder"

Here’s a more complex example that creates a new folder on the desktop containing another folder:-

make new folder at desktop with properties {name:"New Folder"}

make new folder at folder "New Folder" of desktop¬

  with properties {name:"Folder inside New Folder"}

A similar approach can be used to create a file, as in:-

make new file in selection with properties¬

  {name:"Modem Script", file type:"mlts", creator type:"slnk"}

  --> file "Modem Script" of folder "The Folder" of application "Finder"

which, in this instance, is an empty modem script document. It’s worth noting that almost any standard attribute can be included in the properties list. However, by default, the file type and creator type attributes in the Classic Mac OS are set to TEXT and ttxt, respectively, which are applicable to SimpleText. If you’re working with documents destined to be used on a Mac OS X machine you may prefer to create files without a specific creator code, as in this example:-

make new file in selection with properties¬

  {name:"Mac OS X File", creator type:"...."}

    --> file "Mac OS X File" of folder "The Folder" of application "Finder"

where .... represents a string of four null characters. Unfortunately, you’ll need a special utility to get this kind of character onto your clipboard.

Item Attributes

The following forms of script can be used to get information about a file or folder, which in these examples is a selected item. The various results that are possible are shown beneath the scripts.

tell application "Finder"

  activate

  class of selection

end tell

  --> alias

  --> application file

  --> disk

  --> document file

  --> folder

tell application "Finder"

  activate

  kind of selection

end tell

  --> "alias"

  --> "application program"

  --> "disk"

  --> "ClarisWorks word processing document"

The second script gives the text that’s shown in the Kind column of an as List view in the Finder.

You can use the results of such tests in conditional statements, as in these examples:-

if kind of item "****" is "folder" then

if kind of alias "****" is "folder" then

if class of item "****" is disk then

if system folder of disk "****" exists then

if free space of disk of destFolder is less than size of chosenFolder then

Some of the information that can be read and set is shown below, although errors are reported if you use alias for items on the desktop or if you work with invisible files. Desktop items should be referred to using the file, folder or item style of reference while information about invisible files can be obtained using info for and the alias style of reference.

set theName to name of alias "****"

  --> "Test Document"

set theModDate to modification date of alias "****"

  --> date "Friday, August 2, 2002 2:29:20 pm"

set theVers to version of alias "****"

  --> "n/a"(not available)

  --> "Z1-1.3, Copyright Apple Computer, Inc. 1997-99"

The information given by version or product version is usually only a number. For the full version string you must use the info for command, as supplied by the Standard Additions scripting addition. This also provides other information, as shown below, although the process of extracting the data is slower than the above commands, especially where folders are concerned.

set theVers to info for alias "****"

  --> {

  name:"Apple DVD Player",

  creation date:date "Tuesday, September 14, 1999 1:00:00 pm",

  modification date:date "Wednesday, September 22, 1999 1:00:00 pm",

  icon position:{1, 0},

  visible:true,

  size:3.73198E+5,

  folder:false,

  alias:false,

  locked:false,

  busy status:false,

  file creator:"ombz",

  file type:"APPL",

  short version:"Z1-1.3",

  long version:"Z1-1.3, Copyright Apple Computer, Inc. 1997-99"

  }

The information normally appears as a continuous list, although it’s shown here in a ‘formatted’ style to enhance the appearance. This kind of instruction can also be used for an invisible file, but only if you refer to the file using the alias term. Here’s an example that gets the icon data for a file:-

set theIcns to icon of alias theFile

  --> {class:Icon Family,

  large one bit icon:«data ICN#…»,

  large eight bit icon:«data icl8…»,

  large four bit icon:«data icl4…»,

  large 8 bit mask:«data l8mk…»,

  large color icon:«data il32…»,

  small one bit icon:«data ics#…»,

  small eight bit icon:«data ics8…»,

  small four bit icon:«data ics4…»,

  «class s8mk»:«data s8mk…»,

  small color icon:«data is32…»

  }

where the data is again shown ‘formatted’, with replacing each long string of data.

Process Control

The scriptable Finder has control over which applications and processes should be visible or brought to the front. The following script hides all visible applications:-

tell application "Finder"

  activate

  set visible of (processes whose visible is true) to false

end tell

where the word processes can be replaced by the phrase every process, if preferred. The next script does the opposite, and shows all the applications:-

tell application "Finder"

  try

    set visible of processes to true

  end try

end tell

However, if you don’t include the try and end try lines this script will report an error as it encounters those applications that only run in the background.

The following script, which would normally be launched via a utility such as OtherMenu or OSA Menu, tells you what application is currently active:-

tell application "Finder"

  set frontApp to processes whose frontmost is true

end tell

  -->{process "Script Editor" of application "Finder"}

Note that the result is in the form of a list, anticipating later versions of the Mac OS that support multi-tasking, allowing more than one application to be at the front. The following variation gives the name:-

tell application "Finder"

    set frontApp to (name of processes whose frontmost is true) as text

end tell

  -->"Script Editor"

Folder Actions

Mac OS 8.x and above support a feature known as folder actions, which lets you automatically run a specified script when a given folder is opened or used in other ways. You can attach a script to a folder by Ctrl-clicking the required folder and then selecting Attach a Folder Action. You’ll then see a standard dialogue, which you can use to navigate to the required script.

A folder with an attached script is identified in the Classic Mac OS by a special icon like this:-

although no such indication is provided in Mac OS X, which can lead to some confusion.

Folder actions in Mac OS X are handled by the System Events application, which must be launched and then added to the Login Items list, a process that happens automatically when you run the script that initiates folder actions. In the Classic Mac OS they’re handled by the Standard Additions file, the dictionary of which contains the following:-

Details regarding these five ‘handlers’ are shown in the following table:-

HandlerScript runs when:-
opening folder…folder window is opened
closing folder window for…window is closed
moving folder window for…open window is moved
adding folder items to…items are added to open folder window
removing folder items from…items are removed from open folder window

Here’s an example Classic script:-

on opening folder theFolder

  tell application "Finder"

    activate

    set numItems to number of items in theFolder

    set msgTxt to "There are " & numItems & " items in this folder."

    if numItems = 1 then set msgTxt to "There’s one item in this folder."

    display dialog msgTxt buttons "OK" default button 1 with icon note

  end tell

end opening folder

which you’d normally save in the Folder Action Scripts folder. To conform with Apple’s naming convention you could call it open - count items and then attach it to the required folder, as described above. Once this is done you should see a dialogue when you open the folder, such as:-

The syntax for the five handlers is rather cumbersome, as shown in the following table:

Start of HandlerEnd of Handler
on opening folder theFolderend opening folder
on closing folder window for theFolderend closing folder window for
on moving folder window for theFolderend moving folder window for
on adding folder items to theFolderend adding folder items to
on removing folder items from theFolderend removing folder items from

Fax Notification

In Mac OS X you can use folder actions to warn you that the contents of a folder has changed, which is what happens when a fax message arrives. To enable this, Ctrl-click the folder used for receiving faxes and choose Enable Folder Actions from the contextual menu. Do this again, this time selecting Attach a Folder Action. Then select the required folder action script, which is called add - new item alert.scpt. Now, whenever a fax is delivered you’ll get an alert.

Backup Scripting Example

Here’s a script that backs up documents, as well as the cache folder used by Internet Explorer 5.x in the Classic Mac OS:-

tell application "Finder"

  activate

  with timeout of 600 seconds

    duplicate folder "Documents" of startup disk¬

      to disk "Backup Disk" with replacing

    duplicate folder "MS Internet Cache" of preferences folder¬

      to disk "Backup Disk" with replacing

  end timeout

end tell

The with timeout instruction ensures that the script doesn’t quit should the copying process take too long. So, if you’ve got a lot of files you may have to replace the 600 by a bigger number.

The above script can be improved by introducing extra scripting after the activate line so as to check whether or not the backup disk is actually available. It’s also a good idea to clear the contents and empty the Trash on the backup drive prior to doing the backup. The next script incorporates all these improvements, working through a list a folders:-

tell application "Finder"

  activate

  -- makes a list of items to back up

  tell startup disk to set itemList to ¬

    {¬

    folder "Documents:Letters", ¬

    folder "Information", ¬

    folder "MS Internet Cache" of preferences folder¬

    }

  -- checks the backup disk is available

  set diskName to "Backup Disk"

  if not (exists disk diskName) then

    set theMsg to "The disk “" & diskName & "” is not available." & ¬

      return & "Please insert it and try again."

    display dialog theMsg buttons "Cancel" default button 1 with icon stop

  end if

  -- clears files off backup disk and empties Trash

  try

    delete every item of disk diskName

    empty trash

  on error errMsg

    display dialog errMsg buttons "Cancel" default button 1 with icon stop

  end try

  -- backs up items in list

  repeat with theItem in itemList

    with timeout of 600 seconds

      try

        duplicate theItem to disk diskName with replacing

      on error errMsg

        display dialog errMsg buttons "Cancel" default button 1 with icon stop

      end try

    end timeout

  end repeat

end tell

This script illustrates some interesting points. For example, the list of folders has been organised to make it as readable as possible. Note also that each item is described in a ‘shorthand’ form, especially the Preferences folder. In addition, tell startup disk has been used, meaning that the text of startup disk doesn’t have to be repeatedly entered into the list. Finally the use of try statements and dialogues containing a Cancel button ensure appropriate handling or errors.

References

MacWorld magazine (UK), IDG Communications, 2002-2004

1984-Online, Steve Harris

©Ray White 2004.