tags:

views:

164

answers:

3

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?

+4  A: 

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
akf
hi akf, thanks. but i want to use the name of the folder.
sasayins
sasayins, i have updated based on your comment, take a look.
akf
wow! great thanks a lot.
sasayins
You forgot "delims=" to deal with folders that have spaces in their names.
Helen
thanks, Helen - i have updated the example
akf
+2  A: 

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...

Philippe
Or you can filter using {$_.Mode -like "d*" } instead of the Length thing. I'm sure that a PowerShell guru will read this and show us the right solution.
Philippe
`gci | ?{$_.PSIsContainer}` is the canonical way, actually.
Joey
Also, please don't reduce objects to string unless you absolutely have to. This causes more harm than good in most cases.
Joey
Good point, though the output described by sasayins was to have only directory names.
Philippe
+4  A: 

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.

Ben M
"for /d %%d in (*.*) do @echo %%d" is prettier.
Peter Mortensen
You mean `for /d %%d in (*) do @echo %%d`?
Helen
@Helen: yes, the asteriskes apparently were swallowed.
Peter Mortensen
They caused an italic dot :-) You have to enclose your code in \` :-)
Joey