PowerShell: Use Get-ChildItem to Return Folders Only


By default, the Get-ChildItem cmdlet in PowerShell returns both folders and files in a particular directory.

However, you can use the -Directory operator to specify that you would only like to get the folders in a particular directory:

Get-ChildItem c:\users\bobbi\current_data -Directory

This particular example will return only the folders located in the following directory:

  • c:\users\bobbi\current_data

Also note that you could use the gci alias for Get-ChildItem if you’d like even shorter syntax:

gci c:\users\bobbi\current_data -Directory

The following example shows how to use this syntax in practice.

Example: Use Get-ChildItem to Return Folders Only in PowerShell

Suppose we have a folder named current_data saved in the following location:

  • c:\users\bobbi\current_data

Suppose that we use the Get-ChildItem cmdlet to return all folders and files in this directory:

Get-ChildItem c:\users\bobbi\current_data

The following screenshot shows how to use this syntax in practice:

We can see that this directory contains three folders:

  • data1
  • data2
  • data3

It also contains three files:

  • baseball_data.xlsx
  • football_data.xlsx
  • hockey_data.xlsx

Suppose that we would like to only return the folders and not the files.

We can use the following syntax to do so:

Get-ChildItem c:\users\bobbi\current_data -Directory

The following screenshot shows how to use this syntax in practice:

PowerShell Get-ChildItem folders only

Notice that only the folders are returned this time and not the files.

We could also use the gci alias for Get-ChildItem to get the same results:

gci c:\users\bobbi\current_data -Directory

The following screenshot shows how to use this syntax in practice:

Once again, only the folders are returned and not the files.

Note that if you only want to return the folders that are not empty then you could use the following syntax:

gci c:\users\bobbi\current_data -Directory -recurse | ? {$_.GetFiles().Count -ne 0}

The following screenshot shows how to use this syntax in practice:

PowerShell Get-ChildItem only get folders that are not empty

Notice that this only returns the folders named data1 and data2, which means that the folder named data3 was actually empty.

Note: In this example we used the ? operator to filter the results to only contain folders where the file count was not equal to zero.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Use Get-ChildItem with Filter
PowerShell: How to Use Get-ChildItem to Get Full Path of Files
PowerShell: How to List Files in Directory by Date

Leave a Reply