本文目录导读:

Windows系统
PowerShell (推荐)
# 获取电源状态
Get-WmiObject -Class Win32_Battery | Select-Object EstimatedChargeRemaining, BatteryStatus, TimeRemaining
# 简化版本
$battery = Get-WmiObject -Class Win32_Battery
Write-Host "电池剩余: $($battery.EstimatedChargeRemaining)%"
Write-Host "状态: $(switch($battery.BatteryStatus){1{"放电中"}2{"接通电源"}3{"充满"}10{"未充电"}})"
VBScript
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_Battery")
For Each objItem in colItems
WScript.Echo "剩余电量: " & objItem.EstimatedChargeRemaining & "%"
WScript.Echo "状态代码: " & objItem.BatteryStatus
Next
批处理 (有限功能)
@echo off wmic path Win32_Battery get EstimatedChargeRemaining,BatteryStatus
Linux系统
Bash脚本 (使用acpi)
#!/bin/bash # 安装: sudo apt install acpi acpi -V | head -n 5 # 或使用sysfs cat /sys/class/power_supply/BAT0/status cat /sys/class/power_supply/BAT0/capacity
Python脚本
#!/usr/bin/env python3
import os
def get_battery_status():
"""读取电源状态"""
try:
with open('/sys/class/power_supply/BAT0/status', 'r') as f:
status = f.read().strip()
with open('/sys/class/power_supply/BAT0/capacity', 'r') as f:
capacity = f.read().strip()
return status, capacity
except:
return None, None
status, capacity = get_battery_status()
if status:
print(f"状态: {status}")
print(f"电量: {capacity}%")
macOS系统
Shell脚本
#!/bin/bash # 使用pmset命令 pmset -g batt | head -n 2 # 或使用ioreg ioreg -l | grep -i capacity | grep -v legacy
Python脚本
#!/usr/bin/env python3
import subprocess
def get_battery_status():
"""获取macOS电池状态"""
output = subprocess.check_output(["pmset", "-g", "batt"], text=True)
lines = output.strip().split('\n')
if len(lines) > 1:
return lines[1]
return "No battery info"
status = get_battery_status()
print(f"电源状态: {status}")
跨平台Python脚本
#!/usr/bin/env python3
import platform
import subprocess
import sys
def get_power_status():
"""跨平台获取电源状态"""
os_name = platform.system().lower()
try:
if os_name == "windows":
import ctypes
# Windows API
class SYSTEM_POWER_STATUS(ctypes.Structure):
_fields_ = [
('ACLineStatus', ctypes.c_byte),
('BatteryFlag', ctypes.c_byte),
('BatteryLifePercent', ctypes.c_byte),
('Reserved1', ctypes.c_byte),
('BatteryLifeTime', ctypes.c_ulong),
('BatteryFullLifeTime', ctypes.c_ulong)
]
power_status = SYSTEM_POWER_STATUS()
ctypes.windll.kernel32.GetSystemPowerStatus(ctypes.byref(power_status))
status_map = {0: "交流电", 1: "电池", 255: "未知"}
return {
"电源": status_map.get(power_status.ACLineStatus, "未知"),
"电量": power_status.BatteryLifePercent if power_status.BatteryLifePercent <= 100 else "未知"
}
elif os_name == "linux":
status = open('/sys/class/power_supply/BAT0/status').read().strip()
capacity = open('/sys/class/power_supply/BAT0/capacity').read().strip()
return {"状态": status, "电量": capacity + "%"}
elif os_name == "darwin":
output = subprocess.check_output(["pmset", "-g", "batt"], text=True)
return {"完整状态": output.strip()}
except Exception as e:
return {"错误": str(e)}
if __name__ == "__main__":
status = get_power_status()
for key, value in status.items():
print(f"{key}: {value}")
使用第三方工具
PowerShell Gallery模块 (Windows)
# 安装模块 (需要管理员) Install-Module -Name PowerSupplyStatus # 使用 Get-PowerSupplyStatus
Linux 各种工具
# upower (多数发行版预装) upower -i /org/freedesktop/UPower/devices/battery_BAT0 # 或简写 upower -d | grep -E "battery|state|percentage"
注意事项
- Linux系统需要确保
BAT0设备存在,有些笔记本可能是BAT1或电池文件在不同路径 - 电池状态读取可能需要root权限(
sudo) - 台式机可能没有电池设备,需要额外判断
- macOS的
pmset命令需要在终端执行,而不能在login shell中
选择最适合你系统的脚本,如果需要详细的电池健康信息,建议使用系统内置工具(Windows的powercfg /batteryreport,Linux的upower,macOS的system_profiler SPBatteryDataType)。