For loop and multiple labels in batch script

99封情书 提交于 2020-02-02 18:56:56

问题


I am trying to implement a use case: Where I want to refresh series of reports , with each report when failed should attempt to run again and then send out a email notification.

I have below issues which needs help:

  1. In the below code if my first command (cmd[0]) is success ,I don't want to execute :erroremail section , but just go run the second command (cmd[1]) instead from the loop. How can I achieve this?

  2. Basically when my for loop completes (when all my commands are executed) I don't want to execute the :erroremail label in the last . I want it to be executed only when any command fails in 2nd attempt. IF I use exit 0 at the end of for loop as a solution to this , the code is exited just after the first command cmd[0] is run. What is the alternative?

    **SetLocal EnableDelayedExpansion
    SET cmd[0]=run the report 1
    SET cmd[1]=run the report 2

    SET attempt[0]=1
    SET attempt[1]=2
    SET /A "fail = 1"
    @echo off
    for /F "tokens=2 delims==" %%s in ('set cmd[') do (
        for /F "tokens=2 delims==" %%a in ('set attempt[') do (

         if !fail! equ 1 (
                       `@REM ----run commands`
            %%s >>%LOGFILE% 2>>&1   
            if not %errorlevel%==0 (set errmsg=Unable to run& call :Problem) 

                       `@REM ----check if the command is successful`
            for /f "usebackq delims=" %%b in (%LOGFILE%) do set lastline=%%b
                             echo !lastline! | findstr /I /R /C:"Finished refresh of extracts" >nul

                       `@REM ----command is successful`
            if !errorlevel!==0 (
            SET /A "fail = !fail! + 1" 
            )
            )

                        `@REM ----command is failed`
            if not !errorlevel!==0 (if %%a equ 2 (
            set errmsg=2nd attempt for refresh
                call :erroremail
            ))
         )
)
:erroremail
echo "error email is sent after 2nd attempt"
EXIT /b

:Problem
echo "entering problem" 
EXIT 1

来源:https://stackoverflow.com/questions/58104819/for-loop-and-multiple-labels-in-batch-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!