How do I get only directories using Get-ChildItem?

后端 未结 15 1330
北海茫月
北海茫月 2020-11-29 16:30

I\'m using PowerShell 2.0 and I want to pipe out all the subdirectories of a certain path. The following command outputs all files and directories, but I can\'t figure out h

相关标签:
15条回答
  • 2020-11-29 16:39

    A cleaner approach:

    Get-ChildItem "<name_of_directory>" | where {$_.Attributes -match'Directory'}
    

    I wonder if PowerShell 3.0 has a switch that only returns directories; it seems like a logical thing to add.

    0 讨论(0)
  • 2020-11-29 16:40

    For PowerShell versions less than 3.0:

    The FileInfo object returned by Get-ChildItem has a "base" property, PSIsContainer. You want to select only those items.

    Get-ChildItem -Recurse | ?{ $_.PSIsContainer }
    

    If you want the raw string names of the directories, you can do

    Get-ChildItem -Recurse | ?{ $_.PSIsContainer } | Select-Object FullName
    

    For PowerShell 3.0 and greater:

    Get-ChildItem -Directory
    

    You can also use the aliases dir, ls, and gci

    0 讨论(0)
  • 2020-11-29 16:41

    The accepted answer mentions

    Get-ChildItem -Recurse | ?{ $_.PSIsContainer } | Select-Object FullName
    

    to get a "raw string". But in fact objects of type Selected.System.IO.DirectoryInfo will be returned. For raw strings the following can be used:

    Get-ChildItem -Recurse | ?{ $_.PSIsContainer } | % { $_.FullName }
    

    The difference matters if the value is concatenated to a string:

    • with Select-Object suprisingly foo\@{FullName=bar}
    • with the ForEach-operator the expected: foo\bar
    0 讨论(0)
  • 2020-11-29 16:44

    In PowerShell 3.0, it is simpler:

    Get-ChildItem -Directory #List only directories
    Get-ChildItem -File #List only files
    
    0 讨论(0)
  • 2020-11-29 16:45

    Less text is required with this approach:

    ls -r | ? {$_.mode -match "d"}
    
    0 讨论(0)
  • 2020-11-29 16:45

    You'll want to use Get-ChildItem to recursively get all folders and files first. And then pipe that output into a Where-Object clause which only take the files.

    # one of several ways to identify a file is using GetType() which
    # will return "FileInfo" or "DirectoryInfo"
    $files = Get-ChildItem E:\ -Recurse | Where-Object {$_.GetType().Name -eq "FileInfo"} ;
    
    foreach ($file in $files) {
      echo $file.FullName ;
    }
    
    0 讨论(0)
提交回复
热议问题