How to Run an AppleScript When Switching to Battery Power

You can use Power Manager to run an AppleScript when you disconnect your Mac from mains power and start using battery power.

Running an AppleScript when your Mac laptop's power source changes is surprisingly useful. With this ability, you can turn on and off power hungry services and settings, launch applications, or just warn the user that the power cord has come out.

To run the AppleScript we will be creating an event using the new power state trigger; this trigger was introduced in Power Manager v4.0.3. For this example, the AppleScript will be separate from our event.

Create the Power State Triggered Event

  1. Launch AppleScript Editor: Applications > Utilities > AppleScript Editor.
  2. Copy and paste the following AppleScript into a new document:
    set myPathToTheApplicationToRun to "/Users/Shared/MyScript.app"
    
    tell application "Power Manager Scripting"
    
        tell workshop
    
            set myEvent to make new event with properties {trigger ID:"myBatteryEvent", name:"Run script on switch to battery"}
    
            -- Create a power source trigger
            make new trigger power state at front of triggers of myEvent with properties {now:battery}
    
            -- Create an launch application action
            set myApplication to make new application description with properties {path:myPathToTheApplicationToRun}
            set myAction to make new action launch application at front of actions of myEvent with properties {application description:myApplication}
    
        end tell
    
        -- Deploy the event
        tell Event Store to store these events myEvent
    
        -- Clean up
        tell the workshop to empty
    
    end tell
    AppleScript to create a battery triggered Power Manager event.
  3. Save the script: File > Save.
  4. Run the script: Script > Run.

When run, this AppleScript will create a new event in Power Manager. The event will contain one trigger and one action. The trigger tells Power Manager to trigger the event when any power source's state changes to "battery" powered.

The action launches the application stored at /Users/Shared/MyScript.app.

Power Manager showing a battery triggered event.

Create an AppleScript to Launch

  1. Launch AppleScript Editor: Applications > Utilities > AppleScript Editor.
  2. Copy and paste the following AppleScript into a new document:
    say "Switched to battery power."
  3. Save the script as an Application to /Users/Shared with the name MyScript.app.

With this simple AppleScript application in place, your Mac will say the phrase "Switched to battery power." each time the mains power cable is removed. Of course, you can go on to extend this short AppleScript to make it do much more.

This article was posted in , , , , and and tagged , , , , and .

Published by Graham Miln on