Sometimes while working with windows batch file, you want to re-execute steps if they fail. This can be achieved in many ways. In this post, I'll use a user defined variable, a built in ERRORLEVEL variable and batch labels to achieve the same.
ERRORLEVEL is a built in DOS variable which is automatically set to 0 if the command executes successfully but there is a catch. In few operating systems, ERRORLEVEL can be set to a negative value if a command is unsuccessful. The ideal way to check and to direct the flow of command execution is by checking IF %ERRORLEVEL% NEQ 0
Thanks to WebGuru’s Blog for this tip but script written by him wasn't working.
The batch script is as follows :
ERRORLEVEL is a built in DOS variable which is automatically set to 0 if the command executes successfully but there is a catch. In few operating systems, ERRORLEVEL can be set to a negative value if a command is unsuccessful. The ideal way to check and to direct the flow of command execution is by checking IF %ERRORLEVEL% NEQ 0
Thanks to WebGuru’s Blog for this tip but script written by him wasn't working.
The batch script is as follows :
rem set a retry variable initially to 0
set retry=0
:step1
set step=1
@echo (%date%%time%) Step 1 : copying file
copy "C:\temp\file1" "E:\temp\file1"
@echo Errorlevel is %ERRORLEVEL%
if %ERRORLEVEL% NEQ 0 goto retry
rem re-set the retry number if success
set retry=0
:step2
set step=2
@echo (%date%%time%) Step 2 : moveing file
ren "E:\temp\file1" "E:\temp\file2"
@echo Errorlevel is %ERRORLEVEL%
if %ERRORLEVEL% NEQ 0 goto retry
rem re-set the retry number if success
set retry=0
:step3
set step=3
@echo (%date%%time%) Step 3 : delete previous file
rm "C:\temp\file1"
@echo Errorlevel is %ERRORLEVEL%
rem At the last step, direct the flow to the end of file otherwise it will execute retry block
if %ERRORLEVEL% EQU 0 goto eof
if %ERRORLEVEL% NEQ 0 goto retry
:retry
set /a retry=%retry%+1
@echo (%date% %time%) There was an error at STEP%step%, retrying again!
if %retry% LSS 6 (goto :step%step%)
if %retry% EQU 6 (goto :err)
:err
@echo (%date% %time%) sorry, this script stopped due to a few unsuccessful retries.
EXIT
:eof
@echo (%date% %time%) Success! The script completed successfully!
EXIT