PoshCode Archive  Artifact [bb35b7de6a]

Artifact bb35b7de6a882e4b8e0d41835eecbc028eb367d7195735a558a4387a156071f5:

  • File Get-ChildItemRecurse.ps1 — part of check-in [86f45aa489] at 2018-06-10 12:56:27 on branch trunk — A recursive function that allows the user to do a container search and specify the number of levels they would like to recurse. (Requires v2.0 CTP3 or later) (user: CrazyDave size: 2041)

# encoding: ascii
# api: powershell
# title: Get-ChildItemRecurse
# description: A recursive function that allows the user to do a container search and specify the number of levels they would like to recurse.  (Requires v2.0 CTP3 or later)
# version: 0.1
# type: function
# author: CrazyDave
# license: CC0
# function: Get-ChildItemRecurse
# x-poshcode-id: 1115
# x-archived: 2017-01-24T17:53:26
# x-published: 2010-05-18T23:41:00
#
#
function Get-ChildItemRecurse {
<#
.Synopsis
  Does a recursive search through a PSDrive up to n levels.
.Description
  Does a recursive directory search, allowing the user to specify the number of
  levels to search.
.Parameter path
  The starting path.
.Parameter fileglob
  (optional) the search string for matching files
.Parameter levels
  The numer of levels to recurse.
.Example
  # Get up to three levels of files
  PS> Get-ChildItemRecurse *.* -levels 3

.Notes
  NAME:      Get-ChildItemRecurse
  AUTHOR:    tojo2000
#Requires -Version 2.0
#>
  Param([Parameter(Mandatory = $true,
                   ValueFromPipeLine = $false,
                   Position = 0)]
        [string]$path = '.',
        [Parameter(Mandatory = $false,
                   Position = 1,
                   ValueFromPipeLine = $false)]
        [string]$fileglob = '*.*',
        [Parameter(Mandatory = $false,
                   Position = 2,
                   ValueFromPipeLine = $false)]
        [int]$levels = 0)

  if (-not (Test-Path $path)) {
    Write-Error "$path is an invalid path."
    return $false
  }

  $files = @(Get-ChildItem $path)

  foreach ($file in $files) {
    if ($file -like $fileglob) {
      Write-Output $file
    }

  #if ($file.GetType().FullName -eq 'System.IO.DirectoryInfo') {
    if ($file.PSIsContainer) {
      if ($levels -gt 0) {
          Get-ChildItemRecurse -path $file.FullName `
                               -fileglob $fileglob `
                               -levels ($levels - 1)
      }
    }
  }
}