To exclude directories, use the File parameter and omit the Directory parameter, or use the Attributes parameter. To get directories, use the Directory parameter, its "ad" alias, or the Directory attribute of the Attributes parameter. Gets files.
You can also change directory in PowerShell to a specified path. To change directory, enter Set-Location followed by the Path parameter, then the full path you want to change directory to. If the new directory path has spaces, enclose the path in a double-quote (“”).
Differences Between Get-Item and Get-ChildItemGet-Item returns information on just the object specified, whereas Get-ChildItem lists all the objects in the container.
If you want to list files and directories of a specific directory, utilize the “-Path” parameter in the “Get-ChildItem” command. This option will help PowerShell list all the child items of the specified directory. The “-Path” parameter is also utilized to set the paths of one or more locations of files.
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 directories
Get-ChildItem -File #List only files
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With