You need to enable "delayed expansion" for this to work. If it isn't enabled, variables are evaluated exactly once, when the script is parsed. This is why you get the one filename n times.
Some notes:
- Enable delayed expansion with
SETLOCAL EnableDelayedExpansion
- When delayed expansion is enabled, to take advantage of it, you need to use
!
instead of %
as variable delimiter, so your %variable%
becomes !variable!
- Loop variables like your
%%i
are an exception in that they will change their value even when delayed expansion is not enabled. Try ECHO
ing %%i
in your original script (i.e. without SETLOCAL EnableDelayedExpansion
) to see what I mean
Edit: dark fang correctly points out syntax errors in your script, which I didn't even catch - but from the behaviour your described, these were not in your script when you were trying run it, because it would just have errored out.
In the end you get:
SETLOCAL EnableDelayedExpansion
set loc=c:\test
for /f %%i in ('dir "%loc%" /b') do (
@set variable=%%i
echo !variable!
)