Get-ChildItem -Recursive with a limit

Today I had the need to use Get-ChildItem in recursive mode, but I also needed to be able to stop the recursion at a specific level.
Unfortunately the Get-ChildItem doesn’t have the capability to do this.
Luckily there are others around which had the same problem already and found a solution:
function Get-ChildItemToDepth {
  param(
    [String]$Path = $PWD,
    [String]$Filter = "*",
    [Byte]$ToDepth = 255,
    [Byte]$CurrentDepth = 0,
    [Switch]$DebugMode
  )
 
  $CurrentDepth++
  if ($DebugMode) { $DebugPreference = "Continue" }
 
  Get-ChildItem $Path | ForEach-Object {
    $_ | Where-Object { $_.Name -like $Filter }
 
    if ($_.PsIsContainer) {
      if ($CurrentDepth -le $ToDepth) {
        # Callback to this function
        Get-ChildItemToDepth -Path $_.FullName -Filter $Filter -ToDepth $ToDepth -CurrentDepth $CurrentDepth
      } else {
        Write-Debug $("Skipping GCI for Folder: $($_.FullName) " +
          "(Why: Current depth $CurrentDepth vs limit depth $ToDepth)")
      }
    }
  }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s