How do I get only directories using Get-ChildItem? How do I get only directories using Get-ChildItem? powershell powershell

How do I get only directories using Get-ChildItem?


For PowerShell 3.0 and greater:

Get-ChildItem -Directory

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


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


In PowerShell 3.0, it is simpler:

Get-ChildItem -Directory #List only directoriesGet-ChildItem -File #List only files


Use

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

If you prefer aliases, use

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

or

dir -dir #lists only directoriesdir -file #lists only files

To recurse subdirectories as well, add -r option.

ls -dir -r #lists only directories recursivelyls -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