PowerShell Scripts, Tips, Expert Advices, Forums, and Resources

image rotation

Welcome to PowerShell.com, the educational and community site for Windows PowerShell People. Get a quick overview.


As a Powershell.com member you will have access to:

  • Daily PowerShell tips written by Microsoft MVPs and other leading Windows PowerShell experts
  • Free Windows PowerShell advice and training provided by Microsoft MVPs and other leading Windows PowerShell experts
  • Access to leading Windows PowerShell blogs
  • A free ebook, Mastering PowerShell, written by Microsoft MVP Dr. Tobias Weltner
PowerTip of the Day

Recursing a Given Depth

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
{
  param
  (
    [Parameter(Mandatory = $true)]
    $Path,
    
    $Filter = '*',
    
    [System.Int32]
    $MaxDepth = 3,
    
    [System.Int32]
    $Depth = 0
  )
  
  $Depth++

  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!

Copyright 2012 PowerShell.com. All rights reserved.