CMD - create a BAT file to choose actions

101 Views Asked by At

I want to initially check for DISM health, then based on result, I want to select 1 (to run DISM restore & sfc) or 2 (run only sfc).

I cannot get this to work. Any guidance would be appreciated.

Edit: Maybe there's a way to do this all automatically? Execute choice based on initial result?

@ECHO OFF
:BEGIN
CLS

Dism /Online /Cleanup-Image /CheckHealth
timeout /t -1

ECHO.

CHOICE /N /C:12 /M "Press '1' to Run DISM/RestoreHealth & SFC, or Press '2' to run only SFC"%1

ECHO.

IF ERRORLEVEL ==1 GOTO 1
IF ERRORLEVEL ==2 GOTO 2
GOTO END

:2
sfc/scannow
GOTO END

:1
Dism /Online /Cleanup-Image /RestoreHealth
sfc/scannow

:END
pause
1

There are 1 best solutions below

0
Stephan On

(comments is a bad place to show code, so...)

choice returns an errorlevel. You do several if %errorlevel% == N goto N - not needed as your labels and errorlevels are the same. You can just goto %errorlevel% after the choice command:

...
CHOICE /N /C:12 /M "Press '1' to Run DISM/RestoreHealth + SFC, or Press '2' to run only SFC"
goto :%errorlevel%
GOTO :END
:0
echo you cancelled the question.
goto :end
:1
echo running dism and sfc
goto :end
:2
echo running sfc only
goto :end
:end
pause

(for explanation: choice returns an errorlevel of 0 when you press CTRL-C (and answer the following question "Termiate batch job" with "no" - if you answer "yes", the script immediately ends))

The colon in goto is optional. I personally use it to be consistent with the call command and make it clearly visible as a label. There are other opinions about that - pick your choice, but try to stay consistent for readabilty.