如何用脚本获取电池健康度?

wen 实用脚本 2

本文目录导读:

如何用脚本获取电池健康度?

  1. Windows(通过 PowerShell)
  2. macOS(通过 Bash 或 Zsh)
  3. Linux(通过 Bash)
  4. Python 跨平台脚本(通用)

获取电池健康度(通常指电池最大容量相对于原始容量的百分比)的方法取决于你使用的操作系统(Windows、macOS 或 Linux),以下是几个主流系统的脚本获取方式。

Windows(通过 PowerShell)

Windows 原生并没有直接提供“电池健康度”百分比的一键命令,但可以通过生成电池报告来解析。

方法 A:生成报告并解析(推荐)

# 生成电池报告到临时文件
$reportPath = "$env:TEMP\battery-report.xml"
powercfg /batteryreport /duration 1 /output $reportPath 2>$null
# 等待报告生成
Start-Sleep -Seconds 2
# 解析 XML 报告
try {
    $xml = [xml](Get-Content -Path $reportPath -Raw)
    # 找到第一个电池的原始设计容量和当前满充容量
    $designCapacity = $xml.BatteryReport.Batteries.Battery.DESIGNCAPACITY
    $fullChargeCapacity = $xml.BatteryReport.Batteries.Battery.FULLCHARGECAPACITY
    if ($designCapacity -and $fullChargeCapacity) {
        $healthPercent = [math]::Round(($fullChargeCapacity / $designCapacity * 100), 2)
        Write-Output "电池健康度: $healthPercent% (当前容量: $fullChargeCapacity mWh / 设计容量: $designCapacity mWh)"
    } else {
        Write-Output "无法读取电池信息(可能是已移除或虚拟机)"
    }
} catch {
    Write-Output "解析报告失败: $_"
} finally {
    Remove-Item -Path $reportPath -Force -ErrorAction SilentlyContinue
}

方法 B:使用 WMI(Windows Management Instrumentation)直接读取(较新版本 Windows 支持)

# 获取电池信息(注意:不是所有电脑都通过 WMI 完整提供此数据)
$battery = Get-WmiObject Win32_Battery
if ($battery) {
    $designCapacity = $battery.DesignCapacity
    $fullChargeCapacity = $battery.FullChargeCapacity
    if ($designCapacity -and $fullChargeCapacity) {
        $healthPercent = [math]::Round(($fullChargeCapacity / $designCapacity * 100), 2)
        Write-Output "电池健康度: $healthPercent%"
    } else {
        Write-Output "当前系统 WMI 不支持 FullChargeCapacity 字段。"
    }
} else {
    Write-Output "未检测到电池。"
}

注意: 方法 A 更通用(几乎覆盖所有 Windows 机器),方法 B 在一些笔记本上可能返回空值。

macOS(通过 Bash 或 Zsh)

macOS 系统自带 system_profilerpmset 命令可以获取电池状态。

推荐脚本(简洁且准确):

#!/bin/bash
# 获取电池原始设计容量(当前循环数等信息也在此)
battery_info=$(system_profiler SPPowerDataType 2>/dev/null | grep -A 5 "Battery Information")
# 提取最大容量(单位 mAh)
design_capacity=$(echo "$battery_info" | awk -F': ' '/Design Capacity/{print $2}' | tr -d ' ')
current_max_capacity=$(echo "$battery_info" | awk -F': ' '/Maximum Capacity/{print $2}' | tr -d ' ')
# 提取满充容量(单位 mAh),有时显示为 "Charge Remaining" 或 "Full Charge Capacity"
full_charge_capacity=$(echo "$battery_info" | awk -F': ' '/Full Charge Capacity/{print $2}' | tr -d ' ')
# 优先使用 "Maximum Capacity"(百分比值),如果没有则计算
if [[ -n "$current_max_capacity" && "$current_max_capacity" == *"%"* ]]; then
    health_percent="${current_max_capacity%\%}"
    echo "电池健康度: ${health_percent}% (来自系统报告)"
elif [[ -n "$design_capacity" && -n "$full_charge_capacity" ]]; then
    # 某些 Mac 显示为 mAh 数值
    health_percent=$(echo "scale=2; ($full_charge_capacity / $design_capacity) * 100" | bc)
    echo "电池健康度: ${health_percent}% (当前容量: ${full_charge_capacity}mAh / 设计容量: ${design_capacity}mAh)"
else
    echo "无法解析电池健康信息。"
fi

更简单的 macOS 一行命令(仅输出百分比):

pmset -g batt | grep -oP '\d+%' | head -1

注意:pmset -g batt 显示的是当前电量百分比(如 85%),不是健康度,健康度需要上面 system_profiler 的方式。

Linux(通过 Bash)

Linux 电池信息通常在 /sys/class/power_supply/BAT0/BAT1/ 目录下。

#!/bin/bash
# 自动检测电池设备
battery_path="/sys/class/power_supply/BAT0"
if [ ! -d "$battery_path" ]; then
    battery_path="/sys/class/power_supply/BAT1"
fi
if [ ! -d "$battery_path" ]; then
    echo "未找到电池设备。"
    exit 1
fi
# 读取当前满充容量和设计容量(单位微安时 µAh 或毫瓦时 mWh)
full_charge=$(cat "$battery_path/charge_full" 2>/dev/null || cat "$battery_path/energy_full" 2>/dev/null)
design_charge=$(cat "$battery_path/charge_full_design" 2>/dev/null || cat "$battery_path/energy_full_design" 2>/dev/null)
if [[ -n "$full_charge" && -n "$design_charge" && "$design_charge" -gt 0 ]]; then
    health=$(echo "scale=2; ($full_charge * 100) / $design_charge" | bc)
    echo "电池健康度: ${health}%"
else
    echo "无法读取电池容量信息(可能不支持)。"
fi

Python 跨平台脚本(通用)

如果你希望一个脚本在多个系统运行,Python 是一个好选择:

import platform
import subprocess
import re
def get_battery_health():
    system = platform.system()
    health = None
    if system == "Windows":
        try:
            # 生成电池报告并解析
            subprocess.run(["powercfg", "/batteryreport", "/output", "battery_temp.xml"], capture_output=True, check=True)
            import xml.etree.ElementTree as ET
            tree = ET.parse("battery_temp.xml")
            root = tree.getroot()
            # 命名空间处理(根据实际文件调整)
            namespaces = {'ns': 'http://schemas.microsoft.com/battery/2015'}
            design = root.find('.//ns:DESIGNCAPACITY', namespaces)
            full = root.find('.//ns:FULLCHARGECAPACITY', namespaces)
            if design is not None and full is not None:
                health = (int(full.text) / int(design.text)) * 100
            # 清理临时文件
            import os
            os.remove("battery_temp.xml")
        except Exception as e:
            print(f"Windows 获取失败: {e}")
    elif system == "Darwin":  # macOS
        try:
            output = subprocess.check_output(["system_profiler", "SPPowerDataType"]).decode("utf-8")
            design_match = re.search(r'Design Capacity: (\d+)', output)
            max_cap_match = re.search(r'Maximum Capacity: (\d+)%', output)
            if max_cap_match:
                health = float(max_cap_match.group(1))
            elif design_match:
                full_charge_match = re.search(r'Full Charge Capacity: (\d+)', output)
                if full_charge_match:
                    health = (float(full_charge_match.group(1)) / float(design_match.group(1))) * 100
        except Exception as e:
            print(f"macOS 获取失败: {e}")
    elif system == "Linux":
        try:
            paths = ["/sys/class/power_supply/BAT0", "/sys/class/power_supply/BAT1"]
            for path in paths:
                if os.path.exists(path):
                    full = open(f"{path}/charge_full").read().strip()
                    design = open(f"{path}/charge_full_design").read().strip()
                    if full and design:
                        health = (int(full) / int(design)) * 100
                    break
            if health is None:
                # 尝试 energy 文件
                for path in paths:
                    if os.path.exists(path):
                        full = open(f"{path}/energy_full").read().strip()
                        design = open(f"{path}/energy_full_design").read().strip()
                        if full and design:
                            health = (int(full) / int(design)) * 100
                        break
        except Exception as e:
            print(f"Linux 获取失败: {e}")
    if health is not None:
        print(f"电池健康度: {round(health, 2)}%")
    else:
        print("无法获取电池健康度。")
if __name__ == "__main__":
    get_battery_health()
系统 推荐方法 命令/脚本类型
Windows PowerShell(利用 powercfg 生成报告并解析 XML) .ps1 脚本
macOS Bash 脚本(system_profiler 解析) .sh 脚本
Linux Bash 脚本(读取 /sys/class/power_supply/BATx .sh 脚本
跨平台 Python 脚本(如上) .py 脚本

重要提示:

  • 电池健康度只是一个估算值,实际寿命还与循环次数、内阻、温度曲线有关。
  • 如果脚本返回错误“未找到电池”,请确认你的设备是笔记本电脑或带有电池的设备(台式机、虚拟机通常没有)。
  • 执行脚本可能需要管理员/root 权限(特别是 Windows 生成报告或 Linux 读取内核节点)。

抱歉,评论功能暂时关闭!