How do I get only directories using Get-ChildItem?

后端 未结 15 1332
北海茫月
北海茫月 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:56

    My solution is based on the TechNet article Fun Things You Can Do With the Get-ChildItem Cmdlet.

    Get-ChildItem C:\foo | Where-Object {$_.mode -match "d"}
    

    I used it in my script, and it works well.

    0 讨论(0)
  • 2020-11-29 17:02

    From PowerShell v2 and newer (k represents the folder you are beginning your search at):

    Get-ChildItem $Path -attributes D -Recurse
    

    If you just want folder names only, and nothing else, use this:

    Get-ChildItem $Path -Name -attributes D -Recurse
    

    If you are looking for a specific folder, you could use the following. In this case, I am looking for a folder called myFolder:

    Get-ChildItem $Path -attributes D -Recurse -include "myFolder"
    
    0 讨论(0)
  • 2020-11-29 17:05

    Use

    Get-ChildItem -dir #lists only directories
    Get-ChildItem -file #lists only files
    

    If you prefer aliases, use

    ls -dir #lists only directories
    ls -file #lists only files
    

    or

    dir -dir #lists only directories
    dir -file #lists only files
    

    To recurse subdirectories as well, add -r option.

    ls -dir -r #lists only directories recursively
    ls -file -r #lists only files recursively 
    

    Tested on PowerShell 4.0, PowerShell 5.0 (Windows 10), PowerShell Core 6.0 (Windows 10, Mac, and Linux), and PowerShell 7.0 (Windows 10, Mac, and Linux).

    Note: On PowerShell Core, symlinks are not followed when you specify the -r switch. To follow symlinks, specify the -FollowSymlink switch with -r.

    Note 2: PowerShell is now cross-platform, since version 6.0. The cross-platform version was originally called PowerShell Core, but the the word "Core" has been dropped since PowerShell 7.0+.

    Get-ChildItem documentation: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-childitem

    0 讨论(0)
提交回复
热议问题