Karthi
Karthi

Reputation: 708

How to execute If loop and find text using batch

I am new to windows batch programming. I need to write a loop function to execute a task if a specific error is found. Please see the code below.

I'm having a problem with the Find, which is looking for Kitchen.Error.NoRepDefinied. The script executes five times even though the find key word is not found.

Please help me identify the problem, and explain what is wrong here. Any help is appreciated. I am using Windows Server 2012 R2.

set /a x=0
:while1
if %x% leq 5 (
    echo %x%
    call abc.exe > C:\Logs\App_Error.log
    set file=C:\Logs\App_error.log
    set /a cnt=0
    for /f %%a in ('type "%file%"^|find "!Kitchen.Error.NoRepDefinied!"  /i /c') do set /a cnt=%%a
        if !cnt! NEQ 0 (
            if !x! NEQ 5 (
                DEL C:\Logs\App_error.log
            )
            set /a x=x+1
            goto :while1
        )
    echo "OUTSIDE LOOP"
    echo The Status is %errorlevel%
    call:check_file
    exit /b %errorlevel%
)

Upvotes: 2

Views: 240

Answers (1)

MC ND
MC ND

Reputation: 70971

Simplify the code.

Loop (up to 5 times) calling the process. If the process does not return errorlevel, if in the log file the searched string is not found, then leave the loop.

    set "logFile=c:\logs\App_Error.log"

    for /l %%x in (1 1 5) do (
        echo Loop %%x
        > "%logFile%" call abc.exe 
        if not errorlevel 1 (
            find "Kitchen.Error.NoRepDefinied" "%logFile%" >nul 2>&1 || goto :endLoop
        )
    )

:endLoop

I'm not sure about the errorlevel value you are trying to get.

Upvotes: 1

Related Questions