Check if computer is plugged into AC power in batch file
set OnAC=false
set cmd=WMIC /NameSpace:\\root\WMI Path BatteryStatus Get PowerOnline
%cmd% | find /i "true" > nul && set OnAC=true
if %OnAC% == true *Do your thing here*
A quick google1 dragged up
- A powershell solution
- A C++ solution here. I compiled up the example as battery.exe2. I also coded up a modified program that returns 0 (offline), 1 (online) or 255 (unknown) depending on the
ACLineStatus
field of theSYSTEM_POWER_STATUS
Structure. I called it ACLineStatus.exe. You can use this in a batch file, checking the exit code for one of these values.
Here is the - impressive - C source code to the tool :)
#include <windows.h>
int main()
{
SYSTEM_POWER_STATUS status;
GetSystemPowerStatus( &status );
return status.ACLineStatus;
}
Hope that helps
1http://www.google.com/search?q=windows%20powershell%20battery%20mains%20status
2 note: cross compiled on Linux since I don't have Windows. It worked under wine though, output:
$./battery.exe 255% -> Amount of time remaining is unknown
There's a direct batch file way:
WMIC Path Win32_Battery Get BatteryStatus
Using this and some find
/errorlevel
magic, you should be able to turn it into a condition.
Here is the script I am using in our environnement, works nicely:
wmic path Win32_Battery Get BatteryStatus | find /v "BatteryStatus" | find "1" >nul 2>&1
if "%errorlevel%" == "0" (echo Do whatever you want if on BATTERY) else (echo Do whatever you want if on AC POWER)
Description:
From the wmic command, isolate the number from the output.
Try to find the number "1" in the result. If succesfull, it means the computer is running on battery only. The official terminology is "(1) The battery is discharging."
Else, the computer is plugged in AC power.