Search code examples
applescriptosx-yosemite

Detect battery percentage with applescript


How would I detect what my computer's battery percentage is at and set it to a variable using applescript? All answers to similar questions say to install additional software, but I would like to do this with purely applescript. Is this possible? I've also tried searching through the applescript library with no success.


Solution

  • on run
        set theBattString to (do shell script "pmset -g batt")
        -- the above will return something like...
        -- Now drawing from 'Battery Power' -InternalBattery-0  82%; discharging; 4:06 remaining
    end run
    

    Now you can parse theBattString to get the information you'd like from it.

    Another option...

    on run
        do shell script "ioreg -l | grep -i capacity | tr '\\n' ' | ' | awk '{printf(\"%.2f%%\\n\", $10/$5 * 100)}'"
        -- will output...
        -- 79.63%
    end run