How to increment counter variable in “DOS” batch file

Problem : How to increment counter variable in “DOS” batch file

I try to create a batch file to run under Windos XP in a command window (or just double clicking the BAT file).

The intention is to take all files with a given extension, concatenate them and add some extra information “between the files”. To do this, I need to add a counter value like 1 for the first file, 2 for the second and so on. I have managed to solve all other problems to output what I need but the counter variable is not updated as long as I’m inside the FOR loop. See the attached code example. Put it in a BAT file and run it to see the problem. The last echo after the FOR loop gives the correct value.

Any hints are much appreciated.

Code Snippet:

@echo off

set /A Counter=1

echo Initial value of Counter: %Counter%
echo.

for %%f in (*.*) do (
echo File found: %%f
echo Counter Before increment: %Counter%
set /A Counter+=1
echo Counter After Increment: %Counter%
echo.
)

echo Counter after for loop: %Counter%

 

Solution : How to increment counter variable in “DOS” batch file

You will have to enable delayed variable expansion, this will allow for evaluating the variables when they appear (enclosed in !), while %-Expansions takes place when batch is parsed.

@echo off
setlocal enabledelayedexpansion

set /A Counter=1

echo Initial value of Counter: %Counter%
echo.

for %%f in (*.*) do (
echo File found: %%f
echo Counter Before increment: !Counter!
set /A Counter+=1
echo Counter After Increment: !Counter!
echo.
)

echo Counter after for loop: %Counter%