Recursing a Given Depth

by Jul 25, 2014

PowerShell 3.0 and newer

When you use Get-ChildItem to list folder content, you can add the –Recurse parameter to dive into all subfolders. However, this won’t let you control the nesting depth. Get-ChildItem will now search in all subfolders, no matter how deeply they are nested.

Get-ChildItem -Path $env:windir -Filter *.log -Recurse -ErrorAction SilentlyContinue

Sometimes, you see solutions like this one, in an effort to limit the nesting depth:

Get-ChildItem -Path $env:windir\*\*\* -Filter *.log -ErrorAction SilentlyContinue

However, this would not limit nesting depth to three levels. Instead, it would search in all folders three level deeper. It would not, for example, search any folder in level 1 and 2.

The only way to limit nesting depth would be to implement recursion yourself:

function Get-MyChildItem
    [Parameter(Mandatory = $true)]
    $Filter = '*',
    $MaxDepth = 3,
    $Depth = 0

  Get-ChildItem -Path $Path -Filter $Filter -File 
  if ($Depth -le $MaxDepth)
    Get-ChildItem -Path $Path -Directory |
      ForEach-Object { Get-MyChildItem -Path $_.FullName -Filter $Filter -Depth $Depth -MaxDepth $MaxDepth}

Get-MyChildItem -Path c:\windows -Filter *.log -MaxDepth 2 -ErrorAction SilentlyContinue |
  Select-Object -ExpandProperty FullName

This call would get you all *.log files from your Windows folder up to two levels deep.

Twitter This Tip! ReTweet this Tip!