0

I'm trying to set up an automated deploy script from a windows image. During testing, I'm running into an issue regarding the the part that tries to catch if something went wrong with certain commands.

Instead of stopping the script, the script keeps thinking that it's successful and just keeps going to the next command even though the previous command encountered an error.

I tried adding an else to the sections to see what went wrong and I noticed that the error level was at 0 after executing the command. Unless echo itself sets an error level. Here's the relevant section of the code.

Edit: I isolated the root cause to this code section. I also got rid of the imagex step to reduce complexity and variables.

@echo off
setlocal

set /p i_understand="Begin failure test? (Y/N) "

 if "%i_understand%"=="Y" (
 rem Deliberately causing diskpart to fail by using a nonexistent file.
 diskpart /s doesnotexist.txt
 if %ERRORLEVEL% NEQ 0 (
    echo Diskpart failed and caught.
    endlocal
    exit /b 1 )

 echo Diskpart failed but not caught. Error level is %ERRORLEVEL%
 ) else (
 echo Variable i_understand is %i_understand%
 echo Aborting. )

If I reduce the code to the one below, the error level is properly set:

@echo off
setlocal
rem Deliberately causing diskpart to fail by using a nonexistent file.
diskpart /s doesnotexist.txt
if %ERRORLEVEL% NEQ 0 (
    echo Diskpart failed and caught.
    endlocal
    exit /b 1 )

The idea was to display warnings then get a final answer with a capital "Y" for "Yes, I know this script is dangerous and I know what I'm doing." before proceeding with any other input being interpreted as a denial for safety.

Of course, many things could go wrong during the process. Maybe the network drive connection gets cut off, something causes the target drive to be inaccessible or something yet unforseen causes one of the commands to fail. In this case, the script stops whatever it's doing and leaves a log of the console output up to this point.

Naturally, during my tests, I encountered a bunch of failures due to misconfigured variables but the script kept chugging along as though nothing happened.

JosefZ
  • 13,855

0 Answers0