1

I want to get the list of all files inside of c:\test. My attempt is this:

set loc=c:\test

for /f %%i in(dir "%loc%" /b') do (

 @set variable=%%i

echo %variable%

)

...but I'm getting back only one file name, n times. How to get all the files in that folder.

zb226
  • 9,586
  • 6
  • 49
  • 79
Sid ABS
  • 59
  • 1
  • 11

2 Answers2

0

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 ECHOing %%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!
)
Community
  • 1
  • 1
zb226
  • 9,586
  • 6
  • 49
  • 79
0

1. The reason you get back only 1 file name all the time is that you did not Setlocal EnableDelayedExpansion.
2. Check again you code, you did not add a single quotation mark before dir "%loc%" /b'.
3. Check again your code once more, you can't stick "in" and "(" like in(, this will absolutely ruin your code.

@echo off
Setlocal EnableDelayedExpansion

set "loc=c:\test"

for /f %%i in ('dir "%loc%" /b') do (
    set "variable=%%i"
    echo !variable!
)
Happy Face
  • 1,061
  • 7
  • 18
  • @SidABS The extensions are there, for those doesn't have are folders. – Happy Face Oct 29 '15 at 08:15
  • Thanks . It works properly . now I do have another doubt . the bat file is on desktop and the files that I am looking for are in D:\Folder. Can I know how to change the directory inside the for loop .I had to do further more processing .Thanks in advance – Sid ABS Oct 29 '15 at 09:56