Search code examples
windowsbatch-filescheduled-tasksbatch-processingbatterylevel

Script to check battery status variable and use it in if statement, and is there any script to make .bat file run as a hidden process every minute


Currently, I am trying to create a script file that will launch other programs if it detects that the laptop is running using its battery, not the AC.

Providing that I am using Windows 8.1.

I created a .bat file and I entered the following script:

@ECHO OFF
REM To Check the battery status, providing that 2 is connected to the AC
WMIC Path Win32_Battery Get BatteryStatus 
REM Check the content of battery status variable
IF NOT "%BatteryStatus%"=="2"(
echo laptop started to use its battery )

When I ran the above batch file its as if not detecting the content of BatteryStatus variable.

Can any one guide me to the best way to get batterystatus output in to battery status variable?

Another thing, I need a script to allow this bat to run and do this battery check every minute, how can I achieve that?

I tried to do it using task scheduler, but the problem that the maximum re occurrence time is 5 minute.

Any idea?

Thanks in advance!


Solution

  • A little more robust, check that the variable is really batterystatus:

        for /F "delims== tokens=1,2" %%a in ('WMIC Path Win32_Battery Get BatteryStatus /format:textvaluelist.xsl') do @if "%%a"=="BatteryStatus" call :DoStuff %%b
        goto :EOF
    
    :DoStuff
        do_thing1  >nul
        do_thing2 >nul
        do_thing3 >nul
        goto :EOF
    

    Then, use a loop to continue the process:

    :LOOP
    for /f .....
    
    timeout /t 60
    
    goto :LOOP