DekGenius.com
Team LiB   Previous Section   Next Section

14.1 Example Finder Scripts

Before we begin our long but intriguing hike through the Finder commands and classes, we will first get our feet wet with five short Finder scripts. These are scripts that I use all the time, so often that I frequently cut and paste them into larger scripts. Together, they help demonstrate the power and ease of Finder scripting. These scripts are designed to accomplish the following tasks:

  • Get the Operating System version that is running on the machine that hosts the script

  • Display the file type and creator type of files that are dragged to this "droplet"

  • Go into specified directories and delete the notorious "Word Work Files" that Microsoft Word 98 creates

  • Get the free space of each disk or volume on the desktop

  • Display all running processes or programs on your machine and give you the option to shut down some of them, including invisible background applications

14.1.1 Finding Out the Operating System Version

Example 14-1 finds out which OS the computer is running by using a property of the Finder called, aptly enough, product version. The script first saves product version, a string, to a variable called myOS. You need to enclose this variable assignment in a tell block that targets the Finder, because product version is a property of the Finder. Otherwise, AppleScript would not know which product version you were referring to. The script then tests the OS version to determine if it is less than 8.5 with the following code statement:

characters 1 thru 3 of myOS

This returns a list like {"9", ".","0"}. This list is converted to text with the as text coercion statement, so now it looks like "9.0." The entire statement is:

(characters 1 thru 3 of myOS as text)

This string ("9.0") is then coerced or converted to a real number (9.0), which is a number with a decimal point and fractional part (unlike an integer, which is a whole number), so we can compare this number with 8.5. This coercion is not strictly necessary, but I like to make explicit conversions so I always know which data type I am working with.

If the myOS value (e.g., 9.0) is less than 8.5, a dialog displays telling the user the script will quit. This function derives from a script that I wrote depended on Mac OS 8.5 or greater to run properly.

Example 14-1. OS Version Retriever
getOS(  )
(* function definition *)
on getOS(  )
   tell application "Finder"
      set myOS to (product version)
      if ((characters 1 thru 3 of myOS as text) as real) < 8.5 then
         display dialog "You cannot run this applet unless the computer" &¬
         " has Mac OS 8.5. or later." & return & return &¬
         giving up after 45
         return -- quit applet
      else
         display dialog "Good, your OS is: " & myOS
      end if
   end tell
end getOS

14.1.2 Displaying the File and Creator Types of Files

It is often important to get the file type and creator type of files. These are actually two properties of the file object, which is a class that the Finder application makes available to AppleScripters. The file type is specifically a four-character name for the kind of file, such as 'TEXT' for a simple text file or 'APPL' for an application file that will execute a program if you double-click it.

The Mac OS X file system supports "file types," but their use is optional and some files may not have a file type. Some files will instead be identified by their extension, as in textfile.txt or myapplication.app. Apple Computer suggests that scripts which rely on file types for identifying certain files should be augmented to include a check for certain extensions. For example, if the script is looking for all files that are pict, gif, or jpeg image files, then it should check for file types (e.g., 'PICT', 'GIFf', or 'JPEG') and certain extensions (e.g., .pct, .gif, or .jpg).

The creator type is a four-character name for the program that will try to open the file if you double-click the file. For example, if the file has a creator type of 'ttxt' then SimpleText tries to handle it; a creator type of 'R*ch' opens BBEdit if you double-click the file. The following script is a droplet that will display the file type and creator type of any file you drag and drop on the droplet's icon. Figure 14-3 shows what this dialog box looks like.

Figure 14-3. The gettype droplet's dialog window
figs/ascr_1403.gif

You can save a script as a droplet by enclosing its statements in an on open handler (see Chapter 2 for more details on saving droplets). Once again, this script targets the Finder app "Finder" because the file object is an element of the Finder class. In the following example, only the Finder knows what a "file" and "creator and file types" are:

on open (list_of_aliases)
   tell application "Finder"
      set myfile to item 1 of list_of_aliases
      if kind of myfile is not "folder" then display dialog¬
      "creator type: " & (the creator type of myfile) & return &¬
      "file type: " & (the file type of myfile)
   end tell
end open

14.1.3 Finding and Deleting Only Certain File Types

Microsoft Word creates a lot of extra files on your hard disk when you are working on a word-processing document. Sometimes Word never disposes of these files (say, if the computer happens to crash). The following script helps trash these leftover files to make sure that your disk is not cluttered up with them. The next example will delete any file in a folder the user chooses that has the following characteristics:

  • The filename contains "Word Work File."

  • The file type is "PDBN."

  • The creator type is "MSWD."

The creator type and file type were exposed for these files by using the script in the previous example. The script in Example 14-2 first uses the choose folder scripting addition to get the user to select a folder. It then calls the list folder osax to get a list of the contents of the selected folder (this list is stored in the flist variable). Appendix A, covers the scripting additions (otherwise known as osax, or osaxen in plural form). With each of the folder's files, the script finds out whether its name contains "Word Work File" and whether it has a creator type of "MSWD" and file type of "PDBN." These are the only kinds of files we want to delete. The Finder's delete command puts these files in the trash. We keep track of how many files got deleted and display this number to the user. I call this script in Example 14-2 unceremoniously "TrashWord."

Example 14-2. The TrashWord Script
set fol to choose folder
set counter to 0
tell application "Finder"
   set folpath to (fol as text) (* the folder path as a string, such as 
"macintosh hd:desktop folder:MyFolder:" *)
   set flist to list folder fol (* returns a list of strings representing 
   file paths *)
   repeat with n in flist
      if (n contains "Word Work File") then
         set f to (file (folpath & n)) (* creates file references out of 
the strings *)
         if (creator type of f is "MSWD") and (file type of f is "PDBN")¬
            then 
            set counter to counter + 1
         end if
      end if
   end repeat
   display dialog ("We trashed " & counter & " files")
end tell

14.1.4 Displaying the Free Space of Each Disk

Like other Mac users, I have a bunch of different volumes, which the Finder treats as separate disks, on my desktop. It is nice to be able to monitor how much space each one of these disks has left, since each of them inevitably fills up with files and new apps. The Finder provides some simple tools to display this data to the user. These include the disk object, which has a free space property. This property returns the amount of space that is left on the disk as integer bytes. So if disk "MyDisk" only had 1024 bytes left on it, then:

free space of disk "MyDisk"

would return 1024. You would have to enclose the latter code fragment in a tell statement that targets the Finder, because the Finder application knows about disk objects and free space properties. This script, which I call "GetFreeSpace," gets a list of all the disks and stores the list in a dskList variable. Since the Finder application class has disk elements, you can get a list of all disks simply by sending the disks command to the Finder. This script gets each disk's free space in megabytes with the following code phrase:

((d's free space) / 1024 / 1024)

It adds this information to a mesg string variable that is finally displayed to the user when all of the free space and total space is computed. The result is a dialog window that looks like Figure 14-4.

Figure 14-4. GetFreeSpace script's dialog window
figs/ascr_1404.gif

You could do something else with this disk data, like store it in a database:

tell application "Finder"
   set total_space to 0
   set mesg to ""
   set dskList to disks -- get a list of disks
   repeat with d in dskList
      (* get each disk's free space as megabytes*)
      set mesg to mesg & (name of d) & ": " & ((d's free space) /¬
      1024 / 1024) & " meg" & return
      set total_space to total_space + (free space of d)
   end repeat
   (* get the total_space as gigabytes *)
   set total_space to (total_space / 1024 / 1024 / 1024)
   set mesg to mesg & return & "Here's the amount of free space you" &¬
   "have left: " & total_space & " gig"
   display dialog mesg
end tell

14.1.5 Displaying the Running Processes in a list Box and Optionally Closing Some of Them

The "CloseApps" script of the next example displays a list in a dialog window that the user may choose from. The list contains the names of all of the application processes that are running on the computer. These include the programs that have a user interface (e.g., windows and menus that you can interact with) and faceless background applications (FBAs) such as Time Synchronizer or File Sharing Extension. FBAs are programs that work invisibly in the background without interacting with the user. CloseApps is similar to one of the functions of the Windows NT Task Manager utility, which lets you select and shut down a process. Figure 14-5 shows the dialog window displayed by this script. Users may choose one or more processes, and the script will quit the selected programs.

Figure 14-5. A dialog window displays running processes
figs/ascr_1405.gif

The script shown in Example 14-3 uses the choose from list scripting addition and a list of application processes. An application process is an element of the Finder's application class. You can get a list of all of the currently running app processes simply by requesting all of the Finder's application processes, as in:

tell app "Finder" to application processes

This phrase does not sound syntactically pleasing, but it does the job. The script gets a list of all application processes with the code:

set applist to application processes

It then creates a list of all of the process names by getting the name property of each member of applist (which contains the application process objects) and adding the name to the list (stored in the namelist variable). An example of the name property of process "Application Switcher" is naturally enough "Application Switcher." The choose from list scripting addition populates the window with the list of process names in namelist. The user can select one or more of the list names and click the Close Em button, and the script will send a quit Apple event withto each of the selected processes.

Example 14-3. The choose from list Script
set applist to {} -- will contain list of process objects
set namelist to {} -- will contain list of process names
set closelist to {} (* will contain list of process names that the user wants 
to shut down *)
tell application "Finder"
   set applist to application processes
   repeat with proc in applist
      set namelist to namelist & (name of proc) (* get names of each 
running process *)
   end repeat
end tell
Choose from list namelist with prompt "Which open applications do you " &¬
"want to close ?" OK button name "Close Em" cancel button name "Outta Here"¬ 
with multiple selections allowed
set closelist to the result
try
   set closelist_len to (length of closelist)
   if closelist_len is greater than 0 then
      repeat with proc in closelist
         try -- trap any errors caused by quitting the program
            tell application proc (* send a quit command to each of the selected 
programs *)
               quit
            end tell
         on error number errNum
            activate
            display dialog (proc & "reported error number " & errNum & ¬
            " when trying to respond to the quit Apple event.")
         end try
      end repeat
   end if
on error number errNum (* this error triggered when the user cancels the 
program *)
   if errNum is equal to -1728 then
      set theMessage to 
      display dialog theMessage
   else
      display dialog
   end if
end try
Finder Commands

The following commands can be used by enclosing them in a tell statement that targets the Finder, as in:

tell app "Finder" to sleep

Dictionary commands

add to favorites reference

The Apple Menu in the upper left corner of the Mac OS 9 screen has a Favorites menu item that includes folders and programs that are displayed or executed if you select them. You can use this command to add to the Favorites list:

tell application "Finder" to add to favorites (folder "today" of desktop)

This adds a folder called today on the desktop to the Favorites menu.

clean up reference

This command neatly arranges buttons or icons in an open window or on the desktop:

tell application "Finder" to clean up window "HFSA2gig"

(See the Finder's View menu, which determines how Finder items like folders are aligned on the desktop.) If you use clean up all, this command has the same effect as clean up desktop by name.

by property

This labeled parameter determines how items are arranged; e.g., by comment, modification date, name, size, or version. An example is:

clean up desktop by name

This Finder command arranges the desktop items by their name in alphabetical order.

close reference

Use the close command followed by a reference to one or more windows. An example is:

tell application "Finder" to close window "HFSA2gig"

You can also close multiple objects:

tell app "Finder" to close every window

This command closes every Finder window on the desktop, such as folder or disk windows.

computer constant or string

The computer command provides information about the machine running the script. The following example displays how much memory is available in megabytes, including virtual memory. This command is the AppleScript equivalent of the Gestalt function that is part of the Macintosh Application Programming Interface (API). You can find out more about this function at http://developer.apple.com/techpubs/mac/OSUtilities/OSUtilities-11.html.

You can use the following constants with the computer command: CPU, FPU, hardware, memory available, memory installed, MMU, operating system, and sound system. There are also numerous other selectors that you can use instead of these constants, as long as you know the four-character string and what its return value means (an integer). For example, the command computer "scr#" tells you how many active scripting systems the computer has, and computer "sysa" indicates whether the computer is a PowerPC (result value of 2 means yes).

tell application "Finder"
   set mem to (computer memory available)
   display dialog (mem / 1024 / 1024)
end tell
has integer

The computer command returns a boolean value if you use this labeled parameter:

tell app "Finder" to computer "sysa" has 2

This code phrase returns true if the computer is a PowerPC.

In Mac OS X, the computer command has been removed from the Finder dictionary and placed in the Standard Additions osax as the command system attribute. You do not have to enclose system attribute in a Finder tell block (as you have to with computer), because system attribute is not a Finder command.

copy

This command copies selected objects to the clipboard, as long as the Finder is the frontmost program (use the activate command first). The following example copies today to the clipboard:

tell application "Finder"
   activate
   select (folder "today" of desktop)
   copy
end tell
count reference to object

You can count the number of objects within another object, such as count files of folder MyFolder. The command returns the number of counted objects as an integer. You can also use the form:

tell folder "MyFolder" to count files

or:

count each file of folder "MyFolder", or count every file of folder¬  "MyFolder"
each class

Use the each keyword to specify the class of the object you are counting:

tell app "Finder" to count each item of apple menu items folder

or:

Count items of apple menu items folder
data size reference to object(s)

data size returns the size in bytes of the object reference that would be returned from a get command. In other words, if you used the phrase:

data size of (file "Boston" of desktop)

the return value would not be the size of the file on disk; it would be the byte size of the actual reference:

file "Boston" of application "Finder"

Yes, I agree, it is difficult to find a purpose for this command. Except that you can get the byte size of an icon family with code such as:

data size of icon of (file "Boston" of desktop)
as class

If we were to use this labeled parameter with one of the aforementioned examples, the code would look like:

data size of (file "Boston" of desktop) as reference.

In other words, data size is computing the size of a reference class type (e.g., file "Boston" of desktop), not the file size.

delete reference to object(s)

You can delete more than one object with this command:

delete every item of folder "actions"

This code deletes all folders and files in the "actions" folder on the desktop. Or, you can use syntax such as:

delete {file "test", folder "saved template"} of folder "actions"

This is a handy method when the items that will be trashed are dynamically assembled in a list variable:

delete deleteList of folder "actions"

If you refer to files or folders in a Finder command and do not specify their container, AppleScript assumes they are on the desktop.

duplicate reference to object

Duplicate an object like a file or folder with code such as:

tell application "Finder" to duplicate folder "today" to folder¬
   "actions" of folder "desktop" with replacing

This code will take the "today" folder on the desktop and duplicate it (reproduce it and its contents) to a desktop folder called "actions." This code will also replace any "today" folders that are contained by the "actions" folder. This is a good command to use when you are backing up files from one volume or disk to another.

to location reference

You can copy or duplicate the objects to another location on your machine by using this labeled parameter. You have to specify a valid location such as:

duplicate folder "today" to folder "2000archive" of disk "BackUp"

The location reference would be to folder "2000archive" of disk "BackUp". If you do not use this to labeled parameter, the objects are duplicated in the same container as the original and given the original name with "copy" appended to it.

replacing boolean

If you use replacing true then any objects with the same name located in the same container where you are copying an object are replaced by the new object.

routing suppressed boolean

This command only applies to objects that are being duplicated to the System Folder. The Finder automatically routes certain objects that are dropped on the System Folder like the Calculator accessory (it is routed to the Apple Menu Items folder). If you set this labeled parameter to false then a file or folder that is duplicated to the System Folder is not automatically routed to a certain location.

eject reference

If you just use eject alone, then every ejectable disk is ejected. For example, the following code causes the computer to eject a zip disk from a disk drive and a floppy disk at the same time:

tell app "Finder" to eject

You can specify the disk to eject, as in eject disk "backupZip". Using eject with a non-ejectable disk such as an internal or external hard disk raises a script error.

empty or empty trash

The following code empties the trash:

tell app "Finder" to empty

Using this command when the trash is already empty just returns a reference to the trash, as in:

trash of application "Finder"
erase reference to disk

This command erases a disk and thereby wipes it clean of all of its data; it is the equivalent of using the Finder's Special Erase Disk... menu command. You cannot erase a disk that has File Sharing turned on for it (which means it is being shared over a network). You should use this command with care (in other words, back up any disk data that you want to preserve).

exists reference to object

You can find out whether a file or folder exists with code such as:

set itExists to (exists folder "today")

If the "today" folder does not exist on the desktop then the itExists variable will be false. You have to provide the exists command with a complete object reference or the Finder will not be able to verify the object's existence. Another example is:

exists (file "Web Sharing Extension" of Extensions Folder)

The parentheses are optional but make the code easier to understand.

make

You can make a new element of the Finder (like a folder or text or image file) with this powerful command. This is a useful command for such tasks as creating a log file and a folder to contain that log. This example creates a new BBEdit text file called "theLog" on the desktop:

tell app "Finder" to make file at desktop with properties {name:¬ "theLog",
creator type: "R*ch", file type: "TEXT"}

If you leave out the at location part when making a new file or folder, then the Finder will by default make the new file or folder on the desktop. The return value of the make command is the object that you created. The "Finder" code sample beneath the "with properties record" section stores the new folder in a variable and then makes a new file in that folder in the next line, using the folder variable as the new file location.

The Finder has a quirk that requires you to not use the new keyword when making a new file, as in make file... instead of make new file.... You have to use the new keyword in most other circumstances when making a new object. You can, however, use the syntax "make new..." with the Finder and AppleScript 1.6 in Mac OS 9.1 and Mac OS X.

new class

What kind of object do you want to make? Use this labeled parameter to declare whether you are making a folder, or some other object:

make new folder with properties {name: "backup"}.
at location reference

In most cases you have to specify where you are making the new object (except for the Finder's default behavior to make new files or folders on the desktop if you leave the at labeled parameter out of your make statement). Be sure to specify a complete location reference as in the example under "with properties record."

to reference

If you are making an alias file type, refer to the alias file's original or parent file with the to labeled parameter. This code phrase tells the Finder to make a new alias file to the Word application on the desktop:

tell app "Finder" to make alias file to application file¬ 
((name of startup disk) & ":Microsoft Office 98:Microsoft Word")
with properties record

You use this labeled parameter to give the new file or folder its properties. The properties are specified as one or more name/value pairs enclosed by curly braces (for example, a record data type). You can find out the properties that you can provide values for by examining the object in the Finder's dictionary. For example, before I created the following example, I found out that the Finder's folder object inherits some properties from the container object, including the icon size property. So I included icon size in the with properties record, with a value of large (a constant). A lot of property values, like the names of files and folders, are strings. with properties is not a required parameter when making files or folders. If you do not use it, then the folder is given the name "untitled folder" and the file is named "untitled":

tell application "Finder"
   activate
   set lfol to (make new folder with properties¬ 
   {name:"LogFolder", icon size:large})
   make file at lfol with properties¬
   {name:"Log file", creator    type:"ttxt", file type:"TEXT"}
   open lfol
end tell
move reference to object

You can move files and folders around to new locations using this command. Unlike duplicate, this command does not create a copy of the object and leave one copy in the original place; it moves it to the new location. This script moves a folder from the desktop to inside another desktop folder called "actions." The script also positions the folder to a spot 10 pixels from the left edge of the parent folder and 10 pixels down from the "actions" folder's top border. The exception is moving files or folders from one disk or volume to another; this copies the original items to the new locations and leaves the originals intact:

tell application "Finder"
   activate
   move folder "LogFolder" to folder "actions" positioned at {10, 10}
end tell
to location reference

This is a required parameter specifying where you want to move the object. Unless the location is on the desktop, you have to make a complete location reference, in the form of folder "HFSA2gig:1wordfiles" or (folder "1wordfiles" of disk "HFSA2gig").

replacing boolean

If the replacing parameter is true then any items with the same name as the items you moved are replaced in the new location. In other words, if the "actions" folder already has a LogFolder folder, then the folder you moved replaces it if replacing is true. replacing is false by default.

positioned at list

You can position the item you moved in the new location by passing the move command a point object. This is a list of coordinates specifying the upper left corner of the item's icon.

routing suppressed boolean

This command only applies to objects that are being moved to the System Folder. The Finder automatically routes certain objects that are dropped on the System Folder icon, such as the Calculator accessory (it is routed to the Apple Menu Items folder). If you set this labeled parameter to false then a file or folder that is moved to the System Folder is not automatically routed to a certain location.

open reference to object(s)

You can open one or more files or folders using the Finder's open command. You can also have the Finder create an object and then instruct another application (the object's or file's creator) to open it. Open several objects at once by passing the Finder open command a list:

open {folder "today",folder "actions"}

This command opens two desktop folders, since the Finder assumes that incomplete folder references are on the desktop. If you refer to files or folders without complete file or folder paths (unless they are located on the desktop) then your code will raise an error. Since the following are hypothetically complete path references, the Finder will open each of the folders without an error:

open {folder "Macintosh HD:Logs:JuneLogs",folder "Macintosh¬  
HD:Logs:JulyLogs"}
using reference to application file

You can specify the application to open the file with this labeled parameter:

open file "Bfile" using¬
   application file "Macintosh hd:BBEdit 5.0:BBEdit 5.0:" &¬
   "BBEdit 5.1"

This code uses the BBEdit 5.0 text editor to open the file. With most files, the open command issued from the Finder results in the file displayed by the proper software program. In other words, if you use the code open file "bigpic.gif" and this is a Photoshop file, then the file will most likely open up in Photoshop. In this case, the Finder's open command is the equivalent of double-clicking the file.

with properties record

This command is designed to pass some object properties along to the application when you are specifying another program to open the file or folder:

using application file "MyProgram" with properties¬  {name:"Newfile"}

But I assume that few programs support this syntax with the Finder's open command, since I have had difficulty finding any:

tell application "Finder"
   activate
   set bpath to "macintosh hd:BBEdit 5.0:BBEdit 5.0:BBEdit 5.1"
   set tf to (make file at desktop with properties¬ {name:"sfile2", 
creator type:"R*ch", file type:"TEXT"})
   open tf using application file bpath
end tell
print reference to object(s)

This does what you would expect it to do—prints a file with code such as print file "myfile". Selecting a printer in the Chooser before using this command helps avoid errors with it.

with properties record

This command is designed to pass some object properties along to the application that will print the file, but the program must support this extension to the print command (which makes it is difficult to find an effective use for this parameter).

put away reference to object

put away serves two main purposes: to eject disks and to return files and folders from the desktop to the disk or folder where they came from. The example below puts two files that were placed on the desktop back into the folders where they were saved. As you can see, you can pass a list as a parameter to the put away command to put away multiple objects. Or you can just use a single object like a disk as the parameter. If disk "flop" was a floppy disk, then using the code

put away disk "Flop"

would eject the disk. The code is the equivalent of selecting the disk icon and typing Command-Y:

tell application "Finder"
   activate
   put away {file "finderclasslist", file "findercomlist"}
end tell
quit

This command quits the Finder. If you want to close the Finder, essentially shutting down the computer's operation, you might as well use the more intuitive restart and shutdown Finder commands.

restart

This command is the equivalent of choosing the Restart menu item in the Finder's Special menu. It closes all open programs and restarts the computer.

reveal reference to object

When used with a running program, reveal makes that program the frontmost one in the Finder. You would normally use the activate command to initiate this behavior. You can also use reveal to open a folder in a disk:

reveal folder "Macintosh HD:MyFolder"

This code opens the "MyFolder" folder and makes it the frontmost item on the desktop. Using reveal with other desktop items like document files selects those items but does not open them into a window (use open to do that).

select reference to object(s)

You can select one or more objects on the desktop with this command. For instance, if you record a Finder operation in which you click on and open various objects, the recorded script usually contains a lot of select commands. Once you have selected the objects, you can use the term "open selection," as shown in the following example:

tell application "Finder"
   activate
   select {disk "HFSB2gig", disk "HFSA2gig"}
   open selection (* opens two Finder windows showing the contents of each 
disk *)
end tell
shut down

This command closes open applications and shuts down the computer; it is equivalent to choosing Shut Down in the Finder's Special menu.

sleep

This command powers down the computer but does not shut down open applications. The Finder is restored to its initial state once the computer "wakes up" after a key is tapped. The command is equivalent to choosing Sleep in the Finder's Special menu.

sort list of references

You can sort files or folders by various properties such as creation date, modification date, name, or size. The by part of the command is required. sort's return value is the sorted list of objects. If you sort files by date, the sort will be in the order of newest files first; if you sort by name, then the sort will be in alphabetical order. The following example sorts the files in a certain folder by their creation date:

tell application "Finder"
   activate
   sort files of folder "HFSA2gig:1wordfiles:fol1" by creation date
end tell
by property

This required labeled parameter specifies how to sort the objects. You can use all kinds of properties with the sort by command; it depends which object(s) you are sorting. For example, you can use the following properties, among others, to sort files: creation date, creator type, file type, kind, modification date, name, and size.

update reference to object

This command updates the display of objects like windows and disks to match their representation on disk. This task is usually done automatically by the operating system. The effect of this command is to force the update of, for instance, a disk on which a script has made a lot of changes.

    Team LiB   Previous Section   Next Section