Running for loop and setting the variable values within the for loop is different in window batch file comparing to other scripting or programming language.
Following example is trying to get the total value of 1, 2, 3 and 4.
for %%F in (1 2 3 4) do (
set /A COUNT=!COUNT! + 1
echo %COUNT%
)
But we will get:
0
0
0
This is because batch processor expands the variable only once, thus %COUNT% is expanded to its value, which is the initial value, 0.
To fix this, ENABLEDELAYEDEXPANSION can be turned on to delay the batch processor expanding the variable the end of the looping. Also, using ! instead of % to expand the environment variable value.
set COUNT=0
for %%F in (1 2 3 4) do (
set /A COUNT=!COUNT! + %%F
echo !COUNT!
)
The result of the above code is:
3
6
10
There’s another way to enable the delay expansion is through the registry. Please refer to http://batcheero.blogspot.com/2007/06/how-to-enabledelayedexpansion.html.