Set Recursive-Depth for dir command in dos

Sauer picture Sauer · Sep 18, 2012 · Viewed 28.5k times · Source

I'm currently using the following command to list some directories:

dir /b /s /AD > c:\temp\dir_list.txt

This gives me almost the list that I need. But it is way too much data, because some folders have very many subfolders, that I don't want to see in my listing.

Is it possible, to limit the recursion depth of the command to -lets say- 3?

c:\dir_1\dir_2\dir_3\dir_foo

So if I execute the command in the above example in c:> I don't want to see the dir_foo directory, but just the dir_n ones...

Maybe without a batch/vb-script?

Answer

dbenham picture dbenham · Sep 18, 2012

I'm sure it is possible to write a complex command that would list n levels of directories. But it would be hard to remember the syntax and error prone. It would also need to change each time you want to change the number of levels.

Much better to use a simple script.

EDIT 5 Years Later - Actually, there is a simple one liner that has been available since Vista. See my new ROBOCOPY solution.

Here is a batch solution that performs a depth first listing. The DIR /S command performs a breadth first listing, but I prefer this depth first format.

@echo off
setlocal
set currentLevel=0
set maxLevel=%2
if not defined maxLevel set maxLevel=1

:procFolder
pushd %1 2>nul || exit /b
if %currentLevel% lss %maxLevel% (
  for /d %%F in (*) do (
    echo %%~fF
    set /a currentLevel+=1
    call :procFolder "%%F"
    set /a currentLevel-=1
  )
)
popd

The breadth first version is nearly the same, except it requires an extra FOR loop.

@echo off
setlocal
set currentLevel=0
set maxLevel=%2
if not defined maxLevel set maxLevel=1

:procFolder
pushd %1 2>nul || exit /b
if %currentLevel% lss %maxLevel% (
  for /d %%F in (*) do echo %%~fF
  for /d %%F in (*) do (
    set /a currentLevel+=1
    call :procFolder "%%F"
    set /a currentLevel-=1
  )
)
popd

Both scripts expect two arguments:

arg1 = the path of the root directory to be listed

arg2 = the number of levels to list.

So to list 3 levels of the current directory, you could use

listDirs.bat . 3

To list 5 levels of a different directory, you could use

listDirs.bat "d:\my folder\" 5