Search code examples
batch-filepowercfg

Implement if command to script if power plan already exists


My scripting skills are, well limited, so hopefully someone can help here.

Basically, I have two scheduled tasks which run when a laptop gets connected/disconnected by the mains charger (Via event ID 105) which in turn runs a script to set a power plan.

For example, when the mains charger gets connected, the following bat script runs:

' powercfg /import C:\System\Win\Power_Plan_Ultimate_Performance\Balanced_Power_Plan\Balanced_Power_Plan.pow 381b4222-f694-41f0-9685-ff5bb260df2e powercfg /setactive 381b4222-f694-41f0-9685-ff5bb260df2e '

First, the power plan is imported and then it is set.

However, I've noticed, that if the power plan is already imported, when the script is run, the power plan is deleted, and then of course can't be set. Running it again then imports and then sets it.

There lies my problem. It seems that if the power plan is already imported, the command to import, seems to delete it.

Is there a way to run a 'if' command, that if the power plan is already imported, the first powercfg /import command is skipped and goes straight to 'powercfg 'setactive'.

My thought was that 'powercfg /list' could be run first to see if the GUID already exists.

If it doesn't exist, the import takes place.

Appreciate any assistance with this!

As described above.


Solution

  • Your solution of checking for powercfg /list seems pretty solid to me. Something like this

    @echo off
    set "powerPlanGUID=381b4222-f694-41f0-9685-ff5bb260df2e"
    
    rem Check if the power plan is already imported
    powercfg /list | find /i "%powerPlanGUID%" && (
        echo Power plan already imported
    ) || (
        echo Power plan not imported, importing now...
        powercfg /import C:\System\Win\Power_Plan_Ultimate_Performance\Balanced_Power_Plan\Balanced_Power_Plan.pow %powerPlanGUID%
    )
    
    rem Set the active power plan
    powercfg /setactive %powerPlanGUID%