# FOR Loop Batch file not working



## keneo (Nov 10, 2009)

Hi
I am trying to write a batch file that will list the files and sizes in a directory based on the file that passed to the batch file as a parameter.

So for example, Let's say my batch file is called "mybatch.bat" and I have a folder "C:\My Folder" with 3 files in it "file1.txt", "file2.txt", "file3.txt".

If I type:
*mybatch.bat "C:\My Folder\file1.txt"*

The output should be:
*-- 77 -- file1.txt*
*-- 395 -- file2.txt*
*-- 465 -- file3.txt*

Here is the batch file I wrote:
*ECHO OFF *
*FOR /F "delims=" %%A IN ('DIR "%~dp1" /A-D /B') DO (
echo -- %%~zA -- %%A 
)*

But this is not working. Here is my output
*-- -- file1.txt
-- -- file2.txt
-- -- file3.txt*


----------



## Squashman (Apr 4, 2003)

```
ECHO OFF

pushd %1
FOR /F "tokens=*" %%A IN ('DIR /A-D /B') DO (
echo -- %%~zA -- %%A
)
popd
```


----------



## TheOutcaste (Aug 8, 2007)

Welcome to TSG!

Using the */B* switch with *Dir* means *%%A* has only the file name. The output of a For loop is just a text string.
With out a path included in the variable, *%%~z* uses the Current Directory to try to find the file to get the size, so if you haven't switched to that folder, it can't find the file, and won't report the size.

One bug with Squashman's code, *PushD* won't accept a file name, so if passing a path that includes a file name, you would need to extract the path from the passed file. 

```
ECHO OFF
PushD "%[COLOR=Red][B]~dp[/B][/COLOR]1"
FOR /F "Tokens=*" %%A IN ('DIR /A-D /B') DO (
echo -- %%~zA -- %%A
)
PopD
```
The above will work with:
*mybatch.bat "C:\My Folder\file1.txt"*
or
*mybatch.bat "C:\My Folder\"*
but not
*mybatch.bat "C:\My Folder"*
The last one will be seen as just *C:\*

This will work for all three cases:

```
ECHO OFF
PushD "%~1" 2>Nul
If Errorlevel 1 PushD "%~dp1"
FOR /F "delims=" %%A IN ('DIR /A-D /B') DO (
echo -- %%~zA -- %%A
)
PopD
```
*Delims=* and *Tokens=** are equivalent, either can be used
Quotes shouldn't be needed with PushD, but there are settings that would require a path with spaces to be quoted, so best to use "%~1" to remove any passed quotes and then quote the parameter, just in case.


----------



## Squashman (Apr 4, 2003)

Not sure why I removed the ~dp option. I had it in there and then removed it at the last minute. Quick brain fart.

I could have sworn I ran the batch like this.
mybatch.bat "C:\My Folder"


----------

