(Windows Batch File) IF statement inside FOR LOOP

Blackfusion picture Blackfusion · Jul 9, 2014 · Viewed 15.3k times · Source

I'm trying to write manual document validation part of my program. It's basically opening all the pdf documents one by one in the same folder. When its open i would like to echo few possibilities for user. Here starts the problem. I have around 180 possible choices. I was thinking to ask for the first letter of choice. Then it will echo all choices with started with X letter and user has to simply enter the number of this choice. So for example we have : 1. Asomething 2. Asomename 3. Asomenametoo 4. Bname 5. Bname 2 6. Bname 3

I want user to choose first letter and print possible choices. When the choice is made program should add some string to txt file with the same name in the same folder. Here i have a problem with IF statement inside FOR loop. I wanted to use goto but i can't do it inside FOR loop.

I can set up all the strings for each number before. For example : When you choose 1 it will add SomeString to txt. It's important to use choice option to avoid any typo's. Does anybody knows any other way to do this inside FOR loop ?

CODE:

setlocal enabledelayedexpansion
FOR %%b IN (c:\test\*.txt) DO (
IF "%ERRORLEVEL%"=="0" ECHO    Document will open now...
start Acrobat.exe %%b.pdf
ECHO 1. Sample 1
ECHO 2. Sample 2
set /p choice=   Please enter number:
call :OPTION
ECHO !choice! >> %%b
PAUSE
taskkill /IM Acrobat.exe >> c:\test\log\temp.txt
)
PAUSE
GOTO MENU
:OPTION
IF !choice!==1 SET /A !choice!==MNV666
IF !choice!==2 SET /A !choice!==MNV777
GOTO:EOF

Answer

briantist picture briantist · Aug 10, 2014

I'm having some trouble understanding the problem you're having, but it looks like all of the statements following the IF should all be conditions of the IF, not just the ECHO statement. For that, you can put the entire block in parentheses like this:

setlocal enabledelayedexpansion
FOR %%b IN (c:\test\*.txt) DO (
    IF "%ERRORLEVEL%"=="0" (
        ECHO    Document will open now...
        start Acrobat.exe %%b.pdf
        ECHO 1. Sample 1
        ECHO 2. Sample 2
        set /p choice=   Please enter number:
        call :OPTION
        ECHO !choice! >> %%b
        PAUSE
        taskkill /IM Acrobat.exe >> c:\test\log\temp.txt
    ) else (
        goto :EOF  REM Just an example of else
    )
)
PAUSE
GOTO MENU
:OPTION
IF !choice!==1 SET /A !choice!==MNV666
IF !choice!==2 SET /A !choice!==MNV777
GOTO:EOF

Were you having some problem using goto in the FOR loop?