I am trying to write an AppleScript to connect to a VPN service. Once connected to the VPN, I want to display the VPN icon in the status area of the menu bar.
I've gotten as far as
- connecting to VPN
- displaying the Network section of System Preferences
but I am unable to select the Service. How do I do that?
tell application "System Preferences"
activate
set current pane to pane "com.apple.preference.network"
tell application "System Events" to tell process "System Preferences" to tell window "Network"
-- code to select the VPN Service "XYZ" and click the "Show VPN Status in menu"
end tell
end tell
Best Answer
The answer to your question can be split in two parts:
connecting to a VPN is not a task that needs GUI scripting (i.e. open the network preferences pane and simulate a click on an item), as that functionality is part of the Network Preferences Suite of System Events since Leopard (I think). All you need is
displaying the VPN status bar item however, is not part of the Network Preferences Suite. If you cannot live with the icon being present permanently in your status bar area, you will have to use GUI scripting to enable it on demand:
note this part, as always in GUI scripting, is potentially highly disruptive: it steals focus from the user, in the worst case even canceling whatever she was doing if she happened to be using System Preferences (there is an excellent discussion on the pros and cons of GUI scripting to manipulate System Settings predating the Preferences Suites at MacScripter). It’s also brittle (as it is subject to the specific UI layout of the preferences pane), although if you follow the model I show above, using indexes and process name retrieval via the application ID, it will at least not be affected by localization issues.