PowerShell: Use Get-ChildItem and Limit Recursion Depth


When using the Get-ChildItem cmdlet in PowerShell, you can use the -Depth operator to limit the recursion depth.

For example, you can use the following syntax to get all folders and files in a particular directory but limit the recursion to only go one level down:

Get-ChildItem c:\users\bobbi\current_data -Recurse -Depth 1

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

Example: Use Get-ChildItem and Limit Recursion Depth Specific Items 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 -Recurse

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

We can see that this directory contains the following subfolders:

  • c:\users\bobbit\current_data
    • c:\users\bobbit\current_data\data1
      • c:\users\bobbit\current_data\data1\athletes
      • c:\users\bobbit\current_data\data1\coaches

Suppose that we would like to limit the recursion depth to just one folder down.

We can use the following syntax to do so:

Get-ChildItem c:\users\bobbi\current_data -Recurse -Depth 1

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

PowerShell Get-ChildItem recurse depth

We can see that this returns the following subfolders:

  • c:\users\bobbit\current_data
    • c:\users\bobbit\current_data\data1

Since we specified -Depth 1, we told PowerShell to only go one folder down.

Note: Feel free to include whatever number you would like after the -Depth operator to go down as many folders as you’d like. For example, you could use -Depth 3 to only go three folders down.

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 with Multiple Filters
PowerShell: How to Use Get-ChildItem to Get Full Path of Files
PowerShell: How to Use Get-ChildItem to Return Files Only

Leave a Reply