After all this time (5 years), and I just now stumble on a simple command line one liner that has been available all along. ROBOCOPY
has been a standard Windows utility since Vista, and is available to XP via the Windows Resource Kit.
robocopy . . /l /s /njh /njs /ns /lev:4 >c:\temp\dir_list.txt
Explanation
/L :: List only - don't copy, timestamp or delete any files.
/S :: copy Subdirectories, but not empty ones.
/NJH :: No Job Header.
/NJS :: No Job Summary.
/NS :: No Size - don't log file sizes.
/LEV:n :: only copy the top n LEVels of the source directory tree.
The /lev:n
option includes the root in the count, and you want 3 subdirectory levels, which is why I added 1 to the value.
Processing further
The output is not perfect in that the root folder is included in the output, and each path includes fixed width leading whitespace. You can conveniently eliminate the root path as well as the leading whitespace with FOR /F
.
(for /f "skip=2 tokens=*" %A in ('robocopy . . /l /s /njh /njs /ns /lev:4') do @echo %A) >c:\temp\dir_list.txt
The ROBOCOPY
output includes an initial blank line, which is why the skip
must be 2 instead of 1.
Each path will end with \
. I like that feature because it makes it obvious that we are listing folders and not files. If you really want to eliminate the trailing \
, then you can add an extra FOR
.
(for /f "skip=2 tokens=*" %A in ('robocopy . . /l /s /njh /njs /ns /lev:4') do @for %B in ("%A.") do @echo %~fB) >c:\temp\dir_list.txt
But the command is becoming a bit ungainly to type. It should be easy to incorporate this technique into a utility batch file that takes the root path and level as arguments. You must remember to double the percents if you put the command within a batch script.