How to Run a Command When Switching to Battery Power

You can have your Mac automatically run a command line tool when switching to and from battery power.

We have previously shown how to run an AppleScript when your Mac switches to battery power. This previous recipe was written in AppleScript, but today's recipe will use the new Schedule Assistant task introduced with Power Manager 4.1.

Let's make your Mac provide an audible warning when you disconnect the mains power supply from your laptop. To do this we are going to use Power Manager and the command line tool say.

Create a Battery Triggered Command Line Event

  1. Launch System Preferences and select Power Manager.
  2. Click Add… to create a new event.
    Click Add to create a new Power Manager event
  3. Choose the template Run a script on battery.
    Choose the template Run a script on battery.
  4. Click Continue to the Script step.
  5. Copy and paste your shell script into the Script step:
    #!/bin/sh
    
    say "Switching to battery power."
    Copy and paste your shell script into Script.
  6. Continue through the remaining steps until your event is created.
    Continue passed the Constraints step.
    Continue through the Why step.
    Your event is now ready and scheduled.

After following the above steps, your event is scheduled and ready. Try disconnecting your mains power. A moment after disconnecting, your Mac will speak and warn that you are now running on battery power.

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

Published by Graham Miln on