2

How would I detect what my computer's battery percentage is 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.

2
  • How do You want to use the info? Because You can get the percentage using bash script like this: pmset -g batt | egrep "([0-9]+\%).*" -o --colour=auto | cut -f1 -d';' Commented Jul 18, 2016 at 22:03
  • I know that, but I want to set it to a variable in applescript. @MateuszSzlosek
    – ALX
    Commented Jul 18, 2016 at 22:48

1 Answer 1

2

Here is an example of setting the percent charged of the internal battery to a variable using AppleScript.

In the sample code below the batteryPercent variable holds the numeric percentage of battery charge and is shown in a message.

set batteryPercent to do shell script "pmset -g batt | awk '/InternalBattery/ { sub(/;/, \"\"); print $2 }'"

display dialog "Battery is " & batteryPercent & " charged." buttons {"OK"} default button "OK"

enter image description here

3
  • This is interesting! I never knew you could run shell commands in applescript.
    – ALX
    Commented Jul 19, 2016 at 1:34
  • 1
    @ALX, Yes, this is what the do shell script command in AppleScript is for. However depending on how complex the command line portion is, it can be tricky. As an example in the awk substitute command sub() in AppleScript it's necessary to escape the double-quotes with a backslash, e.g. sub(/;/, \"\"). If you did that on the bash command line it would error with awk: illegal statement at source line 1 and show where the error is. From the bash command line it would it would be e.g. sub(/;/, ""). Continued in next comment... Commented Jul 19, 2016 at 2:05
  • 1
    Continued from previous comment... So you may run into similar situations where the code run from the bash command line will need to be escaped in places with a backslash to get it to work in the do shell script command in AppleScript. Commented Jul 19, 2016 at 2:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .