Change System Preferences by script

Sometimes it'd be nice to be able to make a change in System Preferences without going to the trouble of opening that utility and then navigating to the preference pane you want. Hints reader BrentT had that problem: He wanted a simple way to turn Internet Sharing on and off. His solution: a clever little AppleScript. Even if you don't care about Internet Sharing, you could use his code as the basis for a script of your own.

To implement BrentT's script, open AppleScript Editor and paste the following code into it:

tell application "System Preferences"
end tell

tell application "System Events"
  tell process "System Preferences"
    click menu item "Sharing" of menu "View" of menu bar 1
    delay 2
    tell window "Sharing"
      click checkbox 1 of row 11 of table 1 of scroll area 1 of group 1
      delay 1
      if (exists sheet 1) then
        if (exists button "Turn AirPort On" of sheet 1) then
          click button "Turn AirPort On" of sheet 1
          delay 1
        end if
        click button "Start" of sheet 1
      end if
    end tell
  end tell
end tell

When you're done, save it as an application somewhere convenient—your Desktop or Dock, say. Now, whenever you double-click on that application, the state of Internet Sharing will change to on or off.

The code is pretty straightforward, which makes it a good base for other applications that would change other settings. The basic idea is: Open a preference pane, click a box on it, make sure Airport is on, then implement the change. By altering some of the details—the name of the preference pane and the checkboxes to be clicked, among others—you could adapt this to other preference panes and so control other settings.

To comment on this article and other Macworld content, visit our Facebook page or our Twitter feed.
Shop Tech Products at Amazon