That pie man
That pie man

Reputation: 13

Batch file to change power profiles

First-time poster here. I'm trying to make a quick script to switch between power-saving and high-performance power modes based on if my laptop is plugged in. I did a bit of googling and came up with this, and so I tried to modify it to suit my needs. However, there seems to be an issue regarding the IF statement, I can't get it to run for some reason i can't understand. Running the checker function by itself works just fine. Happy for any help. Code included below. (For reference, if OnLine = true, then the device is plugged into mains)

@echo on
call :checker OnLine
if OnLine==true( powercfg /s 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c) else (powercfg /s e2ba9cbc-ad70-403c-8810-530a59af2d53)
pause

:checker 
set OnLine=false
set cmd=WMIC /NameSpace:\\root\WMI Path BatteryStatus Get PowerOnline
%cmd% | find /i "true" > nul && set %~OnLine=true
echo %OnLine%
EXIT /B 0

Upvotes: 1

Views: 875

Answers (1)

user7818749
user7818749

Reputation:

There are a lot of issues like missing spaces between true and the opening parenthesis and the fact that you did not use the variable names with % but regardless, even if we fix them it would not work because no value ever gets assigned to the variable.

This should do what you want.

@echo off
WMIC /NameSpace:\\root\WMI Path BatteryStatus Get PowerOnline | findstr /i "TRUE" >nul && (echo powercfg /s 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c & echo online)
if %errorlevel% equ 1 (echo powercfg /s e2ba9cbc-ad70-403c-8810-530a59af2d53 & echo OffLine)

This is a slightly longer version of the solution should you want to echo Online or offline.

WMIC /NameSpace:\\root\WMI Path BatteryStatus Get PowerOnline | findstr /I "TRUE"
if %errorlevel% equ 0 (
        echo Online
        powercfg /s 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c
      ) else (
        echo Offline
        powercfg /s e2ba9cbc-ad70-403c-8810-530a59af2d53
  )

and just to show you what your solution looks like after it was fixed:

@echo off
set onLine=
set mycmd=WMIC /NameSpace:\\root\WMI Path BatteryStatus Get PowerOnline
%mycmd% | findstr /i "TRUE"> nul && set onLine=true
echo %onLine%
if "%onLine%" == "true" (
      powercfg /s 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c
    ) else (
      powercfg /s e2ba9cbc-ad70-403c-8810-530a59af2d53
)
exit /B 0

To understand the above commands better, open cmd and type the following to read their help files.

for /?
if /?
findstr /?

Upvotes: 1

Related Questions