Posts RSS Comments RSS 48 Posts and 155 Comments till now

Archive for the 'Scripts' Category

Trapping error codes in AppleScript

If you use AppleScript you know sometimes when you try to do things such as mount a remote volume things can go wrong. Then you get a error message with number telling (hopefully) what went wrong. But you might not want that error message to show up. Maybe if that error happens you want your script to do something. If so then you have to trap that error first.

To catch an error you need to wrap the part of your script that is doing the action in a try statement. So, if I wanted to open a file I might use something like this:

[codesyntax lang=”applescript” lines=”no”]
try
tell application “Finder”
open file “Hard Drive:Users:joe:oops.txt”
end tell
on error errmsg
end try
[/codesyntax]

The script trys to run that command and if there is a problem the error message gets put into the variable errmsg. Then we can handle that error another way, perhaps with a dialog box.

[codesyntax lang=”applescript” lines=”no”]
try
tell application “Finder”
open file “Hard Drive:Users:joe:oops.txt”
end tell
on error errmsg
display dialog errmsg buttons {“Oops”}
end try
[/codesyntax]

That works great for generic errors but what if we know the error code of a specific error, such as the file doesn’t exist ,which happens to be -1728. Then we can add the number property to our on error trap and do something specific for that error.

[codesyntax lang=”applescript” lines=”no”]
try
tell application “Finder”
open file “Hard Drive:Users:joe:oops.txt”
end tell
on error errmsg number errNum
if errNum is -1728 then
display dialog “Hey, that file doesn’t exist!” buttons {“Doh!”}
else
display dialog errmsg buttons {“Oops”}
end try
[/codesyntax]

Now we can give the user specific feedback on certain errors and just display the error message for all other errors.

Creating printers in Terminal

Using the Printer Setup Utility in OS X is a very easy and simple way to create printers on a Mac. But occasionally you might have need to create printers at the command line. For example, you might want to create printers on remote machines that only have shell access. Or you might want to add the ability to create printers to a login script or a script that runs after a machine is re-imaged.

Well, the command to do this is lpadmin. lpadmin is used mainly to set up network printers. It’s the command line utility for CUPS, the underlying printing architecture of OS X. As usual you can type man lpadmin to get all the gory details. In this post I’m going to cover how to create a printer and how to delete one using Terminal and lpd.

Creating a new printer

The syntax to create a new printer is:

/usr/sbin/lpadmin -p "name of printer" -E -v lpd://"printer IP or DNS"/"queue name" -P "path to PPD file" -D "description"

The name of the printer is whatever you want the user to see, such as “color laser printer”. Just remember if your name has spaces in it you’ll either need to escape the spaces or quote the name. Also, the name cannot contain any non-printable characters (ex. % $ &). The description field, however, can. If you use the description field that is the name that appears in Printer Setup Utility. If you don’t then the name given in the - p flag will be the name.

All of the standard PPD files on a Mac are kept in /Library/Printers/PPD/Contents/Resources/en.lprog/. The actual PPD file will be contained in a .gz file. You just need to point to that file.

So, for our example we’ll set up a printer with the following attributes:

Name: Color_Laser
Type: HP Color Laser 4700
Print server: print.example.com
print queue: color_laser
description: Color Laser (Front Office)

So our command in the Terminal would be this:

usr/sbin/lpadmin -p Color_Laser -E -v lpd://print.example.com/color_laser -P /Library/Printers/PPDs/Contents/Resources/en.lproj/HP\ Color\ LaserJet\ 4700.gz -D "Color Laser (Front Office)"

Note that I quoted the “Color Laser (Front Office)” part to get around spaces in the name. That’s the name that appears in Printer Setup Utility.

Deleting a Printer

Deleting a printer is much easier. All you need is the name.

The syntax to delete a printer is:

/usr/sbin/lpadmin -x "name of printer"

If I wanted to delete the printer I just created all I would need to do is this:

/usr/sbin/lpadmin -x "Color Laser"

Note: The name you’re deleting is the name you gave it in the - p flag, not the description. So putting “Color Laser (Front Office)” in this would not work.

If you’ve forgotten what names you gave the printers open up a web browser on your machine and enter “http://127.0.0.1:631/printers”. That will take you to the configuration page for CUPS, which will list the printers by name.

Creating printers in AppleScript

You can wrap all of these commands up in an AppleScript and send it to users so they can install printers with just a click. Just wrap the commands in a do shell script command.

The one gotcha is because you are using quotes in the Terminal command AND you have to quote to actual command in AppleScript you have to escape the internal quotes by putting a “\” before each quote. You also have to escape and “escapes” you had in the original command.

To compare, here is the original command:

/usr/sbin/lpadmin -p "Color_Laser" -E -v lpd://print.example.com/color_laser -P /Library/Printers/PPDs/Contents/Resources/en.lproj/HP\ Color\ LaserJet\ 4700.gz -D "Color Laser (Front Office)"

And here is the command with the “do shell script” command in AppleScript:

[codesyntax lang=”applescript” lines=”no”]do shell script “/usr/sbin/lpadmin -p Color_Laser -E -v lpd://print.example.com/color_laser -P /Library/Printers/PPDs/Contents/Resources/en.lproj/HP\\ Color\\ LaserJet\\ 4700.gz -D \”Color Laser (Front Office)\””[/codesyntax]

Finding an image’s color space using AppleScript

I just had a need to write a quick script that told me what the color space of an image was (RGB, CMYK, Gray, etc.). So obviously I turned to AppleScript. AppleScript has a nice Scripting Addition called Image Events that can read lots of different information about an image. You can get all the details on the Image Events addition as well as some good examples here.

The one problem I found with Image Events was that it gagged whenever it looked at a grayscale image. No idea why. But, after doing some more research I found that Image Events is based on a UNIX command line tool named sips. Using sips and the AppleScript do shell script command I was able to get the information I needed.

For my immediate purposes I just wanted a script I could run, select a file and get the color information. So that’s what this script does.

[codesyntax lang=”applescript” lines=”no”]
set theFile to (quoted form of the POSIX path of (choose file))
set theColorSpace to (do shell script “sips -g space ” & theFile)
set oldDelims to AppleScript’s text item delimiters
try
set AppleScript’s text item delimiters to “:”
set theColor to text item 2 of theColorSpace as text
set AppleScript’s text item delimiters to oldDelims
on error
set AppleScript’s text item delimiters to oldDelims
end try
display dialog “The color space is: ” & theColor[/codesyntax]

Notice I had to set the file path to the POSIX path of the file. The POSIX path is the actual Unix style path name (ex. /Users/joe/image.jpg). I also had to use the quoted form part of AppleScript to deal with any spaces that might be in the file names. Running this will give you a dialog box with the name of the color space for this file.

Since Image Events can get lots of other bits of information and it’s easier to manipulate then having to parse. So, I combined AppleScript and Automator to make a Finder plug-in. I developed this Automator script to display the image’s size in pixels, resolution, color space and width in picas. It’s being used by a publisher here to quickly check sizes of images to make sure they meet certain requirements. I expect I’ll be adding things and tweaking it as I go.

Click on Image Info Automator workflow to download the workflow. Save it out as a Finder plug-in to use with any selected images.

Using the Screensaver to change my iChat status

Where I work I have lots of people stopping in to ask questions. Usually this involves me getting up to work with them, often for long periods of time. I’m not very good at remembering to change my iChat status to “away” so I came up with this AppleScript.

I have it run via a cron job every 20 minutes. It checks to see if the screen saver is active. If it is then it changes my iChat status to “away’. Simple.

Paste this code into Script Editor and compile. Save it out as a script file.

[codesyntax lang=”applescript” lines=”no”]
tell application “System Events”
set theList to the name of every process
if theList contains “ScreenSaverEngine” then
tell application “iChat”
set theStat to status
if theStat is available then
set status to away
set status message to “Away”
end if
end tell
end if
end tell
[/codesyntax]

Now use something like Cronnix to set it up as a cron job for your account.

When running AppleScripts either in Terminal or for something like a cron job you need to use “osascript”. If you’re using Cronnix you can use the settings below. Click “OK” in the window and then “Save” in the main Cronnix window and you’re done!

Cronnix cron tab settings window

Automator workflow to import images into PowerPoint

I have lots of users where I work that have folders full of pictures that they just want to import into PowerPoint. I came up with this Automator workflow to allow just that.

It makes a new PowerPoint presentation, then lets you select the folder that contains the images you want to import. It then pads the images so that they fit onto a standard PowerPoint slide and imports them.

This workflow uses actions from the Microsoft Automator Actions package.

Click on PowerPoint AutoImport Workflow to download

Get the system version using Terminal

There is a nice utility available from the command line that allows you get some basic system information quickly. All of this information is available in other places but there are times when it’s easier to get it at the command line.

Open up Terminal and type “sw_vers” (no quotes) and hit return. The results you’ll get look like this:


ProductName: Mac OS X
ProductVersion: 10.4.9
BuildVersion: 8P135

You can use different variations such as “sw_vers -productVersion” to get just that information. On the same machine in the first example that would return:


10.4.9

I recently had a need to get this information at the command line for an installer I was building. I only needed to know the first part of the product version (10.3, 10.4, etc.) so I put together a short shell script to grab that information for me.


#!/bin/bash

sysver=`sw_vers -productVersion | cut -c 1-4`
echo $sysver

if [ $sysver = 10.4 ]; then
echo "This is a Tiger System"
elif [ $sysver = 10.3 ]; then
echo "This is a Panther System"
else
echo "This system is too old"
fi

This script was just a “proof of concept” on for me. Once I knew it worked I could control what things happened depending on if the machine was running 10.4, 10.3 or an older version. Just substitute the “echo” statements for what should happen. If you want to try this out paste the script into a plain text document and save it with a “.sh” extension. Go into Terminal and make it executable with chmod.

Setting the startup disk using Terminal

While it’s quite easy to change which disk your machine starts up from using System Preferences there may be times when you need/want to do it either at the command line or within a script.

The command for setting the startup disk using Terminal is “bless“. To get the full story on “bless” open up Terminal and type “man bless” (no quotes).

To change the startup disk type the following in Terminal:

sudo bless -mount /Volumes/"name of your startup disk" -setBoot

So, if the desired disk was named “TestDisk” you would type this:

sudo bless -mount /Volumes/TestDisk -setBoot

If your disk name has spaces in it you’ll need to put quotes around the path to the disk, like this:

sudo bless -mount "/Volumes/My Disk" -setBoot

You can incorporate this into a UNIX shell script to reboot your machine to another disk at a certain time. Perhaps you want to reboot to another disk every Friday to run a disk utility on it, or to image it.


#!/bin/bash
bless -mount /Volumes/TestDisk -setBoot
shutdown -r now

Breaking down this script the first line sets the disk your Mac will boot from. The second line tells it to shutdown and restart immediately. If you have an Intel Mac you can add “–nextonly” at the end of the “bless” line. That will boot the machine to that volume first and then boot back to the original volume on subsequent reboots without having to reset the startup disk.

This command also comes in handy if you’re booting back and forth between volumes to test things. For example, you have a partition with 10.3 and another with 10.4 on it and you want to test some software in 10.3. You can wrap all of this up in an AppleScript and either save it on your desktop as an application or save it as a script and put it in your Script menu.

Paste this code in Script Editor and run it. Make sure you change the disk name to your disk. What for the AppleScript line breaks in the code. Any line that ends in “¬” means the line below is part of the same line. Pasting it in as it is on the web page will still work however.

[codesyntax lang=”applescript” lines=”no”]
do shell script “bless -mount \”/Volumes/Drive Name\” ¬
-setBoot with administrator privileges
do shell script “shutdown -r now” with administrator privileges
[/codesyntax]

Then simply click on the application or select if from the Script menu, enter your admin name and password and it will select the disk and reboot for you.

If you want to choose between several disks you can add in a dialog box to let you choose the correct disk.

[codesyntax lang=”applescript” lines=”no”]
display dialog “Select a startup disk” buttons ¬
{“name of disc 1”, “name of disc 2”]
set bootVol to the button returned of the result as text
do shell script “bless -mount \”/Volumes/” ¬
& bootVol & “\” -setBoot” with administrator privileges
do shell script “shutdown -r now” with administrator privileges
[/codesyntax]

Identifying a DHCP server

Here are three quick ways to identify which DHCP server your machine is getting it’s IP address from. This can come in handy when trying to track down rogue DHCP servers that pop up on a network.

In Tiger:

  • Open System Profiler
  • Click on “Network”
  • Select which service you want to see
  • It is listed under “DHCP Server Responses:” next to “Server Identifier”

In Panther and below:

  • In Terminal type “ipconfig getoption en0 server_identifier”
  • Change “en0” to “en1″ if using wireless

You can also wrap it in an AppleScript. This should work on most version of OS X.

[codesyntax lang=”applescript” lines=”no”]
do shell script “ipconfig getoption en0 server_identifier”
set theIP to the result
display dialog “Your DHCP server IP is: ” & theIP
[/codesyntax]

Save it as an application. Great for getting this information from the Terminal-challenged user.

Get the name of the computer in Tiger (10.4)

In certain AppleScripts you’ll find you need to get the name of the computer you’re currently on. Usually you need this for things like writing to logs, etc. Here’s how to do it in Tiger:

[codesyntax lang=”applescript” lines=”no”]set theName to the computer name of the (system info)[/codesyntax]

This sets the variable “theName” to the name of your computer from the Sharing preference panel

Here’s an example. Paste the text below in Script Editor and run it.

[codesyntax lang=”applescript” lines=”no”]set theName to the computer name of the (system info)
display dialog “My computer’s name is ” & theName[/codesyntax]

« Prev