Page 1 of 1

Determine if laptop is running on AC or battery

Posted: 08 Nov 2019 06:14
by miskox
This topic viewtopic.php?f=3&t=9345#p60689 could be useful. I would like to know if a laptop is running on AC or on battery. Just a few days ago I was doing some work on my laptop when electricity was interrupted (for 2+ hours) because main power line 110kV was damaged (50.000+ homes). Because my battery is very old the autonomy is probably very short. Luckly I was at my computer so immediately did the shutdown etc.

So I would like to have a .bat to see if computer is running on AC or not so I can do the shutdown when AC is lost.

Ideas?

Thanks.
Saso

Re: Determine if laptop is running on AC or battery

Posted: 08 Nov 2019 10:07
by aGerman

Code: Select all

@echo off &setlocal
for /f %%i in ('WMIC /NAMESPACE:\\root\WMI Path BatteryStatus GET PowerOnline /value') do for /f %%j in ("%%i") do set "%%j"
echo %PowerOnline%
pause
You should get either TRUE or FALSE.

Steffen

Re: Determine if laptop is running on AC or battery

Posted: 08 Nov 2019 10:25
by miskox
Thank Steffen!

I get ERROR. WMIC does not work.

Error I get:
ERROR:
Description = Not found
Is this helpful: https://devblogs.microsoft.com/scriptin ... n-battery/

or this: https://devblogs.microsoft.com/scriptin ... ery-power/ (looks like it uses your solution)

I don't know how to incorporate them into .cmd.

Saso

Re: Determine if laptop is running on AC or battery

Posted: 08 Nov 2019 10:29
by aGerman
Does this mean you still work on such an old Windows version where WMIC is not even available? Or is only the BatteryStatus class not available?

Steffen

Re: Determine if laptop is running on AC or battery

Posted: 08 Nov 2019 10:41
by aGerman
Do hybrid scripts work for you?

Code: Select all

@if (@a)==(@b) @end /*

@echo off &setlocal
for /f %%i in ('cscript //nologo //e:jscript "%~fs0"') do set "PowerOnline=%%i"
echo %PowerOnline%
pause

goto :eof */
var objWMIService = (new ActiveXObject('WbemScripting.SWbemLocator')).ConnectServer('.', 'root\\WMI'),
    colItems = new Enumerator(objWMIService.ExecQuery('SELECT * FROM BatteryStatus WHERE Voltage > 0'));
for (colItems.moveFirst(); !colItems.atEnd(); colItems.moveNext())
  WScript.Echo(colItems.item().PowerOnline == true ? 'TRUE' : 'FALSE');
Steffen

Re: Determine if laptop is running on AC or battery

Posted: 11 Nov 2019 04:30
by miskox
Sorry for a late reply. You might be right! I was running it on a desktop computer. I will try that on a laptop computer. I use XP on that machine but WMIC works.

I will let you know about the results.

Thanks.
Saso

Re: Determine if laptop is running on AC or battery

Posted: 11 Nov 2019 05:49
by aGerman
If nothing helps I still can write two lines of C code for this purpose. Just let me know.

Steffen

Re: Determine if laptop is running on AC or battery

Posted: 13 Nov 2019 10:49
by miskox
Your first solution works great on laptop. Sorry for a false alarm.

Thanks.

Saso