get-childitem directories only

This topic contains 4 replies, has 3 voices, and was last updated by Profile photo of Shane Lindberg Shane Lindberg 11 months, 3 weeks ago.

  • Author
  • #31568
    Profile photo of Shane Lindberg
    Shane Lindberg

    I am trying to do the following in powershell version 2

    I have been trying to figure out how to filer only directories. I came to this solution

    get-childitem | where {$_.getdirectories} 

    This is when the confusion started. When I do a get-member of get-childitem I get two main categories: and

    question 1:
    when I do the following command what category is it using: directoryinfo or filename? they share some of the same names of attributes and methods

    get-childitem | where {$_.somethinghere}

    question 2:

    with the following command I and using $_.getdirectories and not $_.getdirectories(). I thought all methods needed the "()". When I do that it fails

    get-childitem | where {$_.getdirectories} 
  • #31570
    Profile photo of Richard Siddaway
    Richard Siddaway

    First problem is the GetDirectories is a method not a property – you can't use the way you were trying. The easiest way to get just the directories in PS 2

    Get-ChildItem | where {$_.PSIsContainer}

    if you want just files use
    Get-ChildItem | where {-not $_.PSIsContainer}
    Get-ChildItem | where {!$_.PSIsContainer}

    To use GetDirectories() try
    $d = Get-Item -Path $pwd

    if you just want files try

  • #31571
    Profile photo of Shane Lindberg
    Shane Lindberg

    That was part of my confusion, when I used it as a property(it was a mistake, but it worked) it did as I wanted. I will look at your examples to do it properly. Any idea to why it worked when I used it as a property? Just curious.

  • #31593
    Profile photo of Tim Curwick
    Tim Curwick


    When you use a method name without the parentheses, PowerShell returns information about the method. And when any non-empty thing (like information about a method) is converted to a boolean, it evaluates as $True.

    FileInfo objects, on the other hand, not having either a method nor a property named GetDirectories, return a $Null. When converted to boolean, $Null is evaluated as $False.

    So effectively you were testing for the existence of either a method with that name or a property with that name with a non-empty value. Mistake or not, it's kind of a neat trick.

  • #31600
    Profile photo of Shane Lindberg
    Shane Lindberg

    Cool. Thanks for explaining that.

You must be logged in to reply to this topic.