Limit Get-ChildItem recursion depth
I can get all sub-items recursively using this command:
Get-ChildItem -recurse
But is there a way to limit the depth? If I only want to recurse one or two levels down for example?
Solution 1:
Use this to limit the depth to 2:
Get-ChildItem \*\*\*,\*\*,\*
The way it works is that it returns the children at each depth 2,1 and 0.
Explanation:
This command
Get-ChildItem \*\*\*
returns all items with a depth of two subfolders. Adding \* adds an additional subfolder to search in.
In line with the OP question, to limit a recursive search using get-childitem you are required to specify all the depths that can be searched.
Solution 2:
As of powershell 5.0, you can now use the -Depth
parameter in Get-ChildItem
!
You combine it with -Recurse
to limit the recursion.
Get-ChildItem -Recurse -Depth 2
Solution 3:
Try this function:
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 | %{
$_ | ?{ $_.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)")
}
}
}
}
source
Solution 4:
I tried to limit Get-ChildItem recursion depth using Resolve-Path
$PATH = "."
$folder = get-item $PATH
$FolderFullName = $Folder.FullName
$PATHs = Resolve-Path $FolderFullName\*\*\*\
$Folders = $PATHs | get-item | where {$_.PsIsContainer}
But this works fine :
gci "$PATH\*\*\*\*"
Solution 5:
This is a function that outputs one line per item, with indentation according to depth level. It is probably much more readable.
function GetDirs($path = $pwd, [Byte]$ToDepth = 255, [Byte]$CurrentDepth = 0)
{
$CurrentDepth++
If ($CurrentDepth -le $ToDepth) {
foreach ($item in Get-ChildItem $path)
{
if (Test-Path $item.FullName -PathType Container)
{
"." * $CurrentDepth + $item.FullName
GetDirs $item.FullName -ToDepth $ToDepth -CurrentDepth $CurrentDepth
}
}
}
}
It is based on a blog post, Practical PowerShell: Pruning File Trees and Extending Cmdlets.