Search code examples
batch-filecmdpowercfg

How do I echo "Script Failed" if error is found?


I'm writing a batch file to import power plans in windows 10. My script is mostly done but I need a way to alert the user if there is an error. Ideally, the script would echo the exact error and prompt the user to hit a key to acknowledge it. Here's my code so far:

powercfg -import "%UserProfile%\Desktop\Powercfg CMIT Defalut\CMIT Win10 Power Plan.pow"

******ERROR CODE PROBABLY SHOULD GO HERE?********

start "" cmd /c "echo CMIT Win10 PowerCFG Imported &echo(&pause"

Solution

  • Redirect the error messages to a new file called error.txt

    powercfg -import "%UserProfile%\Desktop\Powercfg CMIT Defalut\CMIT Win10 Power Plan.pow" 2> __error__.txt
    

    Note: this assumes that the errors are output to stderr

    Then you can check the error code , echo the response, and use pause to prompt for the key press

    if %errorlevel% NEQ 0 (
      echo Failed 
      type __error__.txt
    ) else (
        echo Power plan successfully imported
    )
    pause