How do I get only directories using Get-ChildItem?

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

    Use:

    dir -Directory -Recurse | Select FullName
    

    This will give you an output of the root structure with the folder name for directories only.

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

    Use:

    Get-ChildItem \\myserver\myshare\myshare\ -Directory | Select-Object -Property name |  convertto-csv -NoTypeInformation  | Out-File c:\temp\mydirectorylist.csv
    

    Which does the following

    • Get a list of directories in the target location: Get-ChildItem \\myserver\myshare\myshare\ -Directory
    • Extract only the name of the directories: Select-Object -Property name
    • Convert the output to CSV format: convertto-csv -NoTypeInformation
    • Save the result to a file: Out-File c:\temp\mydirectorylist.csv
    0 讨论(0)
  • 2020-11-29 16:52

    Use this one:

    Get-ChildItem -Path \\server\share\folder\ -Recurse -Force | where {$_.Attributes -like '*Directory*'} | Export-Csv -Path C:\Temp\Export.csv -Encoding "Unicode" -Delimiter ";"
    
    0 讨论(0)
  • 2020-11-29 16:52

    To answer the original question specifically (using IO.FileAttributes):

    Get-ChildItem c:\mypath -Recurse | Where-Object {$_.Attributes -and [IO.FileAttributes]::Directory}

    I do prefer Marek's solution though (Where-Object { $_ -is [System.IO.DirectoryInfo] }).

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

    Use:

    dir -r | where { $_ -is [System.IO.DirectoryInfo] }
    
    0 讨论(0)
  • 2020-11-29 16:55

    A bit more readable and simple approach could be achieved with the script below:

    $Directory = "./"
    Get-ChildItem $Directory -Recurse | % {
        if ($_.Attributes -eq "Directory") {
            Write-Host $_.FullName
        }
    }
    

    Hope this helps!

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