domlao
domlao

Reputation: 16029

How to grab the names of all sub-folders in a batch script?

I just want to know how can I get all the names of the folders in a current directory. For example in my current directory I have three folders:

stackoverflow
reddit
codinghorror

Then when I execute my batch script all the three folders will print in the screen.

How can I achieve this?

Upvotes: 6

Views: 22265

Answers (4)

Arnaf
Arnaf

Reputation: 587

For getting all the subfolders of a specific directory and display it in CMD :

@echo off
dir C:\input /s /b /o:n /a:d
Pause&Exit

For getting all the subfolders of a specific directory and save it in a text file :

dir C:\your_directory /s /b /o:n /a:d > output.txt

Upvotes: 0

Philippe
Philippe

Reputation: 4051

With PowerShell:

gci | ? { $_.PSIsContainer }

Old Answer:

With PowerShell:

gci | ? {$_.Length -eq $null } | % { $_.Name }

You can use the result as an array in a script, and then foreach trough it, or whatever you want to do...

Upvotes: 2

akf
akf

Reputation: 39475

On Windows, you can use:

dir /ad /b

/ad will get you the directories only
/b will present it in 'bare' format

EDIT (reply to comment):

If you want to iterate over these directories and do something with them, use a for command:

for /F "delims=" %%a in ('dir /ad /b') do (
   echo %%a
)
  • note the double % - this is for use in a batch, if you use for on the command line, use a single %.
  • added the resetting of default space delims in response to @Helen's comment

Upvotes: 8

Ben M
Ben M

Reputation: 22492

Using batch files:

for /d %%d in (*.*) do echo %%d

If you want to test that on the command line, use only one % sign in both cases.

Upvotes: 13

Related Questions