This is one of the most common problems with scripting batches:
most administrators dont know/dont understand delayed expansion, which is EXTREMELY important if you want to make more complex scripts.
So what is it about?
First let me show one really small example:
Set Variable=1
If %Variable% EQU 1 (
Set /a Variable=%Variable% + 1
Echo %Variable%
)
Quite simple script, right? Set variable is one, if it is one, add one and show the result. And what do you think the result is? Two?
WRONG!
The result is in fact one! That is because variables are expanding when interpreter encounters the beginning on the script, so Echo %Variable% command output is prepared BEFORE Set /a Variable... is evaluated.
However there is something called delayed variables, which means these variables are expanded in the moment when they are encountered.
So how to enable these functionality? It is quite simple - you just need to add SetLocal EnableDelayedExpansion at the beginning of the script and then you can use !Variable! (note that you can decide if you want to use normal %variable% or delayed !variable!).
But lets show it on example:
SetLocal EnableDelayedExpansion
Set Variable=1
If %Variable% EQU 1 (
Set /a Variable=%Variable% + 1
Echo %Variable%
Echo !Variable!
)
Output from this script block is 1 (normal %Variable%) and 2 (delayed !Variable!).
If you want to implement more complex script blocks (nested For + If + If + For etc.), you must understand this concept and get familiar with it :)