Changing Location With Alfred
As developer, I’ve always been a fan of keyboard; as many other coders I learned as much key combinations as possible instead of using a mouse: and here comes Alfred and its workflows. Alfred is a powerful conterpart to Apple Spotlight as it saves your time when you search for files online or on your Mac, it helps you to more productive with hotkeys, keywords and file actions at your fingertips. With Alfred you can also create immensely powerful workflows by connecting keywords, hotkeys and actions together to extend Alfred to do amazing things without writing a single line of code!
That’s the scenario for my first workflow!
I configured three network locations on my laptop, two for home and the last one for office setup; I can switch between locations using the network pane in System Preferences or via the Apple logo in the menu bar… but why don’t reach these settings via keyboard?
Since 2003, Macos comes with an handy command line utility called scselect: scselect provides access to the system configuration sets, commonly referred to as “locations”. When invoked with no arguments, scselect displays the names and associated identifiers for each defined “location” and indicates which is currently active. scselect also allows the user to select or change the active “location” by specifying its name or identifier.
Let’s see how it works.
1 2 3 4 5 6
As we expects, without any paramters, scselect returned all the configured locations: each of them is represented by the tuple <ID, name>; the line marked with the star represents the currently active network location, “Office” in this case.
If you want to switch to a specific location, simply specify its ID as parameter and let scselect do the rest.
My workflow will be made up of three objects:
- scselect, without any arguments, will be used in the first block to get the list of all network location (or part of it)
- the second block would be executed by Alfred only if the user select the an entry from the result list
- the third and last one will notify the user if everything went fine.
The script filter
For a script filter (the first block in the above picture) to display an output in result list, Alfred expects at least a XML like this:
1 2 3 4 5 6 7 8 9
The first block, the script filter, will use scselect to display all configured locations, formatted in XML.
1 2 3 4 5 6 7 8 9 10
This would generate the folloing result:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
Each location is represented by an
<item> entry: if the user selects a specific location, its ID will be extracted from the property UID of the item: this will be the input for the second block.
The second script is invoked only if user didn’t abort the operation and selected something.
query variable will be filled by Alfred with the
UID of the selected item.
Yay, you changed the location, let Alfred notify the user.
You can download the workflow here.