5

Now that in Powershell dir is just an alias to Get-ChildItem, how can I get a list of just folders?

I've been doing dir /ad (for Attribute Directory) in the command prompt for about 20 years. Is there any way to alias this with parameters in PowerShell?

I see How do I get only directories using Get-ChildItem? over on Stack Overflow but I'm not going to type Get-ChildItem -Recurse | ?{ $_.PSIsContainer } by hand every time. Ideally I'd like dir /ad to alias to that command.

3
  • 1
    Run cmd /c dir /ad? Commented Feb 3, 2014 at 21:01
  • @Zoredache - That... is not too bad. I tried doing &dir but didn't think of doing cmd /c Commented Feb 3, 2014 at 21:02
  • I don't believe you can alias anything to dir /ad or anything with arguments, but you can certainly alias it to dir-ad or dirad or something like that. Commented Feb 3, 2014 at 21:05

2 Answers 2

2

Put a function like this in your profile:

 function d([string]$switch) { if ($switch -eq "d") { Get-ChildItem -Recurse | ?{ $_.PSIsContainer } } elseif ($switch -eq "f") { Get-ChildItem -Recurse | ?{ !$_.PSIsContainer } } else { Get-ChildItem -Recurse } } 

then just use

d d 

You cannot use parameters on aliases, but functions work just the same way. You get use d -d rather than just d d, or you could make directory the default and use just d, the possibilities are endless. You could also pass in the path.

1
  • This is a good idea if you log in to the same machine a lot. Commented Feb 3, 2014 at 23:18
3

how can I get a list of just folders?

gci -d is only seven keystrokes counting Enter... and is there waiting for you, if you're willing to upgrade your Powershell to v3 or better. :)

gci -d -r if you want recursion.

Edit: Removed the tab keystrokes because they are not necessary.

4
  • This is a PS v4 feature is it? Commented Feb 3, 2014 at 21:14
  • PS 3 added the -Directory and -File parameters to have Get-ChildItem return only directories or files, respectively. Commented Feb 3, 2014 at 21:17
  • Ok, cool. I have no intention of upgrading PS on these machines, but I do have some Server 2012 R2 and Windows 8.1 machines that I can use that command on. Good to know :) Commented Feb 3, 2014 at 21:18
  • 2
    You can also use ls -di -r. Powershell understands. Commented Feb 3, 2014 at 22:46

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.