Ever wanted to do a recursive search, but restricted to a certain level of sub-folders? Here is a Get-ChildItem wrapper that let’s you do just that!
function Get-ChildItemRecurse{ | |
<# | |
.SYNOPSIS | |
Wrapper for Get-ChildItem to be able to define how deep you want to search in a directory structure. | |
.DESCRIPTION | |
Wrapper for Get-ChildItem to be able to define how deep you want to search in a directory structure. | |
.PARAMETER Path | |
One or more paths you want to start searching from. Defaults to '.' (Current location). | |
.PARAMETER Filter | |
The filter that defines what you are searching for. Defaults to '*.*' (Everything). | |
.PARAMETER Levels | |
Defines how deep you want your search to be. Defaults to 0 (Current level only). | |
.EXAMPLE | |
Get-ChildItemRecurse . *.txt | |
Description | |
———– | |
Get all files in the current directory with an extension of 'txt' | |
.EXAMPLE | |
Get-ChildItemRecurse . ('*.txt','*.doc') -Levels 1 | |
Description | |
———– | |
Get all files in the current directory and all subdirectories with an extension of 'txt' and 'doc'. | |
This search will be performed 1 level deep, and will not get this file: '.\sub\subsub\file.txt' | |
.NOTES | |
Name: Get-ChildItemRecurse | |
Author: Øyvind Kallstad | |
Date: 20.03.2014 | |
Version: 1.0 | |
#> | |
[CmdletBinding()] | |
param ( | |
[Parameter(ValueFromPipeline = $true, ValueFromPipelinebyPropertyName = $true, Position = 0)] | |
[string[]]$Path = '.', | |
[Parameter(Position = 1)] | |
[string[]]$Filter = '*.*', | |
[Parameter(Position = 2)] | |
[int]$Levels = 0 | |
) | |
PROCESS{ | |
foreach ($thisPath in $Path){ | |
if(-not (Test-Path $thisPath)){ | |
Write-Warning "Cannot find path '$($thisPath)'." | |
} | |
else{ | |
foreach($thisFilter in $Filter){ | |
Write-Output (Get-ChildItem –path $thisPath –Filter $thisFilter) | |
if($Levels -gt 0){ | |
$subFolders = (,(Get-ChildItem –Path $thisPath –Attributes 'Directory')) | |
foreach($subFolder in $subFolders){ | |
Write-Output (Get-ChildItemRecurse –Path ($subFolder.FullName) –Filter $thisFilter –Levels ($Levels – 1)) | |
} | |
} | |
} | |
} | |
} | |
} | |
} |