Error reading values from a batch file and printing them

The variable seems to be set with values of the last run.

This is because of the way cmd parses a batch file. By default variables are expanded at parse time not at run time. This means variable in loops are evaluated incorrectly unless you enable Delayed Expansion:

setlocal enabledelayedexpansion

Delayed Expansion will cause variables to be expanded at execution time rather than at parse time, this option is turned on with the SETLOCAL command.

When delayed expansion is in effect variables can be referenced using !variable_name! (in addition to the normal %variable_name%)

Source Delayed Expansion

Use the following batch file.

test.cmd:

@echo off
setlocal enabledelayedexpansion
for /f "tokens=*" %%a in (data.bat) do (
echo %%a
set server=%%a
echo !server!
)
pause
endlocal

Example Output:

F:\test>test
1
1
2
2
3
3
4
4
Press any key to continue . . .

Further Reading

  • An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
  • enabledelayedexpansion - Delayed Expansion will cause variables to be expanded at execution time rather than at parse time.
  • setlocal - Set options to control the visibility of environment variables in a batch file.

Give this a shot instead using a CALL to a subroutine passing the FOR loop values from the data.bat file to that routine as an argument to then ECHO, etc.:

@echo off
for /f "tokens=*" %%a in (data.bat) do (
CALL :Routine "%%~a"

)
PAUSE
GOTO EOF

:Routine
echo %~1
set server=%~1
echo %server%
GOTO EOF

Further Resources

  • CALL