下面的解决方案是您自己构建的,假设您的意图是查找子树超过给定深度的子目录.
如果您想查找给定深度的所有目录路径或更深入,请参阅底部部分。
您的方法无法实现这一点,因为它只查找给定深度的目录,而不是下面的目录。
您自己的基于通配符的巧妙方法原则上应该有效,但是:
(a) 简化您的方法:
$Depth = 3
$Path = '.'
$Levels = '/*' * $Depth
Get-ChildItem -Directory $Path/$Levels
(b) 将输出限制为具有太深子树的不同顶级文件夹集:
$Depth = 3
$Path = '.'
$Levels = '/*' * $Depth
Get-ChildItem -Directory $Path/$Levels |
ForEach-Object { ($_.FullName -split '[\\/]')[-$Depth] } |
Select-Object -Unique
Note: Splitting by [/\\]
- that is, by either /
or \
- makes the solution work on Unix-like platforms too (PowerShell Core); on Windows, -split '\\'
(by an escaped \
) is sufficient.
使用您的示例文件夹层次结构,上面的内容将产生:
folder1
folder2
可选阅读:使文件夹达到、达到或超过一定深度:
Note:
At-a-仅给定深度 logic:
这与上述解决方案中采用的逻辑相同;以下代码列出了深度为 2 的文件夹only,即那些位于孙级的目录(子目录的子目录) - 请注意,与Get-ChildItem -Depth
,深度计数开始于1
, i.e. 1
指子目录:
$depth = 2 # grandchild directories only
Get-ChildItem -Directory -Path ('*/' * $depth)
输出完整路径,将Get-ChildItem
命令输入(...).FullName
或通过管道将其传输到Select-Object -ExpandProperty FullName
.
输出相对路径 (e.g., folder1/test1/test/testsub
),需要额外的工作,因为添加-Name
will not在这种情况下按预期工作(它将仅输出目录names):
$depth = 2 # grandchild directories
# Calculate the length of the path prefix for determining relative paths.
# (Using the current dir ($PWD) as the reference path here.)
$PrefixLen = (Convert-Path -LiteralPath $PWD).Length + 1
$Levels = '/*' * $Depth
Get-ChildItem -Directory -Path ('*/' * $depth) |
ForEach-Object { $_.FullName.Substring($PrefixLen) }
Up-to-给定深度逻辑:
The PSv5+ -Depth
范围limits Get-ChildItem
的递归深度,即,它只查找达到指定深度的项目,但请注意,它是depth 0
, not 1
代表的是直系子女.
请注意,使用-Depth
implies -Recurse
,尽管您也可以指定后者。
例如,要枚举当前目录中的子文件夹和孙文件夹(2 级),请使用:
$depth = 2 # child and grandchild directories
Get-ChildItem -Directory -Depth ($depth - 1)
At-a-给定深度或更深 logic:
将结果限制为级别大于或等于给定深度的项目需要自定义解决方案:
$depth = 2 # grandchild directories and below
Get-ChildItem -Directory -Name -Recurse |
Where-Object { ($_ -split '[/\\]').Count -ge 2 } |
Get-Item -LiteralPath { "$PWD/$_" }
If your input path isn't the (implied) current dir., substitute that path for $PWD
.