You are not the first, who fell into the famous "delayed expansion trap" (and you won't be the last)
You need delayed expansion if you want to use a variable, that you changed in the same block (a block is a series of commands within brackets
Delayed variables are referenced with
!var! instead of
Reason is the way,
cmd parses the code. A complete line or block is parsed at once, replacing normal variables with their value at parse time. Delayed variables are evaluated at runtime.
Two simple batches to demonstrate:
if 1==1 (
echo %var% !var!
for /L %%i in (1,1,5) do (
echo %random% !random!
Note: also a line is treated as a block:
set "var=new" & echo %var%
with delayed expansion:
set "var=new" & echo !var!
Delayed expansion is per default turned off at the command prompt. If you really need it, you can do:
cmd /v:on /c "set "var=hello" & echo !var!"