访问内置电源管理器?状态

Access built-in Power Manager? states

我正在尝试编写一个超级简单的 applescript,它将启动 OneDrive App,或确保它处于打开状态,只要机器的电源设置为插入,就会退出,或确保关闭,当电源设置为电池时。

我无法找到如何访问 Yosemite 中的内置 "power indicator"。多年前我所有的 searches lead to old, irrelevant results

编辑:我想我将不得不使用 pmset -g batt

在 applescript 中使用一个 do shell 脚本
Now drawing from 'AC Power'
 -InternalBattery-0 100%; charged; 0:00 remaining

并解析这个结果,但我不确定如何解析。

编辑:这是给以后可能想要类似东西的人的:

global appName

on appIsRunning()
    tell application "System Events" to (name of processes) contains appName
end appIsRunning

on acIsConnected()
    return (do shell script "system_profiler SPPowerDataType | grep -q 'Connected: Yes' && echo \"true\" || echo \"false\"") as boolean
end acIsConnected

on toggleApp()
    if my acIsConnected() then
        if not my appIsRunning() then
            tell application "Finder"
                open application file (appName & ".app") of folder "Applications" of startup disk
            end tell
        end if
    else
        tell application appName
            quit
        end tell
    end if
end toggleApp

-- This will only be executed once.
on run
    set appName to "OneDrive"
end run

-- This will be executed periodically, specified in seconds, every return.
on idle
    my toggleApp()
    -- Execute every 2 minutes.
    return 120
end idle

-- Not mandatory, but useful for cleaning up before quiting.
on quit
    -- End handler with the following line.
    continue quit
end quit

这是一个 轮询 连接状态的单行代码,因为我猜你可以在电量低于 100% 的情况下仍然保持连接状态(充电)。

set acConnected to (do shell script "system_profiler SPPowerDataType |grep -q 'Connected: Yes' && echo \"true\" || echo \"false\"") as boolean

这是另一个班轮...

set acConnected to last word of paragraph 1 of (do shell script "ioreg -w0 -l | grep ExternalChargeCapable")

如果您乐于使用第三方工具,则可以避免轮询电池状态。这将使您的脚本更有效率。

Power Manager 可以在电池状态发生变化时 运行 AppleScripts。 How to Run a Command When Switching to Battery Power,介绍如何为脚本进行设置。

将脚本中的#!/bin/sh换成#!/usr/bin/osascript,就可以使用AppleScript了。

免责声明:我编写了电源管理器,可以回答有关其工作原理的评论。

前提是屏幕右上角有电池图标:

tell application "System Events" to tell process "SystemUIServer" ¬ 
to value of attribute "AXDescription" of ¬
(first menu bar item whose value of attribute "AXDescription" ¬
begins with "Battery") of menu bar 1

你得到 "Battery: Charged""Battery: Calculating Time Remaining… " 或其他东西