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.

  • 1
    Run cmd /c dir /ad? – Zoredache Feb 3 '14 at 21:01
  • @Zoredache - That... is not too bad. I tried doing &dir but didn't think of doing cmd /c – Mark Henderson Feb 3 '14 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. – Michael Hampton Feb 3 '14 at 21:05
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.

  • This is a good idea if you log in to the same machine a lot. – Ryan Ries Feb 3 '14 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.

  • This is a PS v4 feature is it? – Mark Henderson Feb 3 '14 at 21:14
  • PS 3 added the -Directory and -File parameters to have Get-ChildItem return only directories or files, respectively. – Ryan Ries Feb 3 '14 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 :) – Mark Henderson Feb 3 '14 at 21:18
  • 2
    You can also use ls -di -r. Powershell understands. – Vasili Syrakis Feb 3 '14 at 22:46

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.