2

Given the following directory

D:\>dir D:\test1 /b
.dir1dot
.dir2dot
dir1
dir2
file1.txt
file2.txt

I want to iterate through all the directories from a given directory in Windows 10. Therefore I've built the following command

D:\>for /d %i in (D:\test1\*) do @echo %i
D:\test1\.dir1dot
D:\test1\.dir2dot
D:\test1\dir1
D:\test1\dir2

Now I want to obtain the names of the directories. That is:

.dir1dot
.dir2dot
dir1
dir2

I have tried executing the following but this is what happens:

D:\> for /d %i in (D:\test1\*) do @echo %~ni
ECHO is on.
ECHO is on.
dir1
dir2

Thus, the question is How can I only display the names of the directories from a given directory?

3
  1. Use the %~nxi substitution to include the file extensions too since this gets the . prefix named folders. You'll still be assured no files are iterated since FOR /D deals with directories only.

    for /d %i in (D:\test1\*) do @echo %~nxi
    .dir1dot
    .dir2dot
    dir1
    dir2
    

  1. Furthermore, you can use a for /f loop iterating the output of a dir command with the /B and /AD parameters to only get directories and no files, and to get the full path per each iteration including the . prefix named folders.

    Directory Names Only

    for /f "tokens=*" %F IN ('DIR D:\test1 /AD /B') do @echo %F
    .dir1dot
    .dir2dot
    dir1
    dir2
    

    Full Path Directory Names

    for /f "tokens=*" %F IN ('DIR D:\test1 /AD /B') do @echo %~fF
    D:\test1\.dir1dot
    D:\test1\.dir2dot
    D:\test1\dir1
    D:\test1\dir2
    

Supporting Resources

  • For /F
  • FOR /?

    In addition, substitution of FOR variable references has been enhanced. You can now use the following optional syntax:

    %~fI        - expands %I to a fully qualified path name
    %~nI        - expands %I to a file name only
    %~xI        - expands %I to a file extension only
    
  • Dir

2

PowerSHell: (Get-ChildItem -directory).Name

Alias/Abbv version: (gci -ad).Name

enter image description here

0

You can use for /Directory and for /Recursive in one loop for /Directory for /Recursive:

for /d /r "E:\your folder" %i in (*)do @echo\%~nxi

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.