PoshCode Logo PowerShell Code Repository

Get-ChildItemRecurse (modification of post by CrazyDave view diff)
diff | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/1115"></script>download | new post

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)

  1. function Get-ChildItemRecurse {
  2. <#
  3. .Synopsis
  4.   Does a recursive search through a PSDrive up to n levels.
  5. .Description
  6.   Does a recursive directory search, allowing the user to specify the number of
  7.   levels to search.
  8. .Parameter path
  9.   The starting path.
  10. .Parameter fileglob
  11.   (optional) the search string for matching files
  12. .Parameter levels
  13.   The numer of levels to recurse.
  14. .Example
  15.   # Get up to three levels of files
  16.   PS> Get-ChildItemRecurse *.* -levels 3
  17.  
  18. .Notes
  19.   NAME:      Get-ChildItemRecurse
  20.   AUTHOR:    tojo2000
  21. #Requires -Version 2.0
  22. #>
  23.   Param([Parameter(Mandatory = $true,
  24.                    ValueFromPipeLine = $false,
  25.                    Position = 0)]
  26.         [string]$path = '.',
  27.         [Parameter(Mandatory = $false,
  28.                    Position = 1,
  29.                    ValueFromPipeLine = $false)]
  30.         [string]$fileglob = '*.*',
  31.         [Parameter(Mandatory = $false,
  32.                    Position = 2,
  33.                    ValueFromPipeLine = $false)]
  34.         [int]$levels = 0)
  35.  
  36.   if (-not (Test-Path $path)) {
  37.     Write-Error "$path is an invalid path."
  38.     return $false
  39.   }
  40.  
  41.   $files = @(Get-ChildItem $path)
  42.  
  43.   foreach ($file in $files) {
  44.     if ($file -like $fileglob) {
  45.       Write-Output $file
  46.     }
  47.  
  48.   #if ($file.GetType().FullName -eq 'System.IO.DirectoryInfo') {
  49.     if ($file.PSIsContainer) {
  50.       if ($levels -gt 0) {
  51.           Get-ChildItemRecurse -path $file.FullName `
  52.                                -fileglob $fileglob `
  53.                                -levels ($levels - 1)
  54.       }
  55.     }
  56.   }
  57. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me