How can I set a Variable in For-Loop in a batchscript

779 Views Asked by At

I am looking for an solution for a trivial problem, i can't get solved. Please help me with that. My plan is to read 2 files. one of them is an folder structur the other is a user list. if the folder word is not found in the user list the (e.g. Profile) folder gets deleted. I am still testing so please do not refere yet to the missing delete in my code. here is what i've got yet:


@echo off
chcp 1252 >nul

setlocal ENABLEDELAYEDEXPANSION
cls

echo --- working ---

for /f "delims=," %%x in (Profile.txt) do (
    set counter = 0
    for /f "tokens=1,2 delims=," %%a in (ADMPReport.csv) do (
        IF "%%x"=="%%b" (
            echo %%x & echo %%b
            REM IF User is found counter gets 1
            set counter = 1
            echo %counter%
            pause
        ) 
    )
    echo %counter%
    REM if no user found Counter = 0
    if %counter% == "0" echo %%x 
        REM ping -n 3 127.0.0.1 >NUL
)

echo ---- done ----
ENDLOCAL

ping -n 3 127.0.0.1 >NUL

My Problem here is that the counter stays at 1 ...

Any Help would be perfect. Best, Andreas

1

There are 1 best solutions below

1
On

First, initialize your counter variable outside the for loop. Second, you're setting counter to 1 on every iteration...not adding to it. To do this in dos batch you must use set /a. It should look like this:

@echo off
chcp 1252 >nul

setlocal ENABLEDELAYEDEXPANSION
cls

echo --- working ---

set counter=0
for /f "delims=," %%x in (Profile.txt) do (
    for /f "tokens=1,2 delims=," %%a in (ADMPReport.csv) do (
        IF "%%x"=="%%b" (
            echo %%x & echo %%b
            REM IF User is found counter gets 1
            set /a counter=%counter%+1
            echo %counter%
            pause
        ) 
    )
    echo %counter%
    REM if no user found Counter = 0
    if %counter% == "0" echo %%x 
        REM ping -n 3 127.0.0.1 >NUL
)

echo ---- done ----
ENDLOCAL

ping -n 3 127.0.0.1 >NUL