How to Run an AppleScript When Switching to Mains Power
You can use Power Manager to trigger an event whenever your Mac laptop is connected to mains power.
You can use Power Manager to trigger an event whenever your Mac laptop is connected to mains power.
Previously we covered how to run an AppleScript when switching to battery power. This recipe deals with the opposite situation, where your MacBook or MacBook Pro has its power adapter plugged back in.
For this example, we are going to run an AppleScript to ask iTunes to check for new podcasts. You could use this trigger to perform an action or sequence of actions, for example launching an application or running a shell script.
Create the Mains Power Triggered Event
Launch AppleScript Editor: Applications > Utilities > AppleScript Editor.
Copy and paste the following AppleScript into a new document:
-- The AppleScript to run when mains power is connected set myScriptContents to "#!/usr/bin/osascript tell application \"iTunes\" to updateAllPodcasts " tell application "Power Manager Scripting" tell workshop set myEvent to make new event with properties {trigger ID:"myBatteryEvent", name:"Run script on switch to mains"} -- Create a power source trigger make new trigger power state at front of triggers of myEvent with properties {now:ac power} -- Create an external inline script to store the AppleScript set myExternal to make new external inline with properties {inline:myScriptContents} set myAction to make new action execute external at front of actions of myEvent with properties {external:myApplication,proceed:on exit} end tell -- Deploy the event tell Event Store to store these events myEvent -- Clean up tell the workshop to empty end tell
Save the script: File > Save.
Run the script: Script > Run.
When run, this AppleScript will create a new event in Power Manager. The new event contains one trigger and one action. The trigger tells Power Manager to trigger the event when any power source’s state changes to “ac power”.
The new event’s action tells Power Manager to run the script in the front most user’s session. If no-one is logged in, the AppleScript will not be performed. This is the ideal behaviour for this AppleScript.
You can try this event immediately. Thanks to the event’s on-demand behaviour, the event can be triggered through Power Manager’s status menu bar, or via Power Manager Remote on your iOS device.