views:

431

answers:

5

I simply want to list all of the directories under my current working directory, using PowerShell. This is easy from a Bash shell:

ls -d */

or cmd.exe in Windows:

dir /a:d

Using PowerShell however I cannot seem to be able to do it with a single command. Instead the only the I've found that works is:

ls | ? {$_Mode -like "d*"}

That seems way too wordy and involved, and I suspect that I don't need a separate Where clause there. The help for Get-ChildItem doesn't make it clear how to filter on Mode though. Can anyone enlighten me?

+3  A: 

This works too:

ls | ?{$_.PsIsContainer}

There is no doubt that it is a little more wordy than bash or cmd.exe. You could certainly put a function and an alias in your profile if you wanted to reduce the verbosity. I'll see if I can find a way to use -filter too.

On further investigation, I don't believe there is a more terse way to do this short of creating your own function and alias. You could put this in your profile:

function Get-ChildContainer
{
    param(
      $root = "."
       )
    Get-ChildItem -path $root | Where-Object{$_.PsIsContainer}
}

New-Alias -Name gcc -value Get-ChildContainer -force

Then to ls the directories in a folder:

gcc C:\

This solution would be a little limited since it would not handle any fanciness like -Include, -Exclude, -Filter, -Recurse, etc. but you could easily add that to the function.

Actually, this is a rather naive solution, but hopefully it will head you in the right direction if you decide to pursue it. To be honest with you though I wouldn't bother. The extra verbosity in this one case is more than overcome by the overall greater flexibility of powershell in general in my personal opinion.

EBGreen
Really? Alias "gcc"? :)
jeffamaphone
Ehh...I left my compiler at home, so no conflict.
EBGreen
+2  A: 

Try:

ls | ? {$_.PsIsContainer}
Kai
I guess I was too slow for EBGreen!
Kai
I guess speed isn't all that matters. :)
EBGreen
A: 

Cheating, but this is technically PowerShell:

cmd /c dir /a:d
Peter Seale
The only problem I would have with this is that you would get back strings not objects.
EBGreen
+2  A: 

You can check old post on PowerShell team blog: http://blogs.msdn.com/powershell/archive/2009/03/13/dir-a-d.aspx

+2  A: 
dir -Exclude *.*

I find this easier to remember than

dir | ? {$_.PsIsContainer}

Plus, it is faster to type, as you can do -ex instead of -exclude or use tab to expand it.

buti-oxa
Great trick, thanks!
fatcat1111