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.

0

2 Answers 2

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!
)
Sign up to request clarification or add additional context in comments.

2 Comments

@SidABS The extensions are there, for those doesn't have are folders.
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
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!
)

1 Comment

Thanks for the in detail explanation :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.