解决你的核心问题:
对于给定的$path,您可以在其子树中找到最大目录深度 - 表示为路径分隔符的数量(Windows 上为\,Unix 上为/)加一在$path 内嵌套最深的子目录的完整路径中 - 如下:
# Outputs the number of path components of the most deeply nested folder in $path.
(Get-ChildItem $path -Recurse -Directory |
Measure-Object -Maximum { ($_.FullName -split '[\\/]').Count }
).Maximum
注意:如果您想知道 relative 深度 - 相对于 $path,请将 -Name 添加到 Get-ChildItem 调用并在脚本块内将 $_.FullName 替换为 $_ ({ ... }) 传递给Measure-Object。 0 的结果则意味着 $path 根本没有子目录,1 意味着只有直接子目录,2 意味着直接子目录本身(只有)子目录,...
-
Get-ChildItem -Recurse -Directory $path输出目录$path的(-Recurse)的整个子树中的所有子目录(-Directory);添加-Force 以包含隐藏的子目录。 - 见Get-ChildItem。
-
Measure-Object -Maximum { ($_.FullName -split '[\\/]').Count } 在每个目录的完整路径 ($_.FullName) 中计算路径分隔符的数量([\\/] 是一个匹配单个 \ 和 / 字符的正则表达式。) - 使用 脚本块 {...} 作为(隐含的)-Property 参数,其中$_ 代表手头的输入路径 - 并确定最大值(-Maximum);假设Measure-Object 输出一个Microsoft.PowerShell.Commands.GenericMeasureInfo 实例,则可以通过.Maximum 属性访问原始最大值。
所有附带的任务 - 将此计算应用于多个服务器,将结果写入服务器特定的文件 - 可以使用常用的 cmdlet(Get-Content、ForEach-Object、Set-Content 或 Out-File / > )。
更快的选择:
上述命令简洁且符合 PowerShell 习惯,但速度有些慢。
下面是一个直接使用 LINQ 和 .NET API 的明显更快的替代方案:
# Note: Makes sure that $path is a *full* path, because .NET's current
# directory usually differs from PowerShell's.
1 + [Linq.Enumerable]::Max(
([System.IO.Directory]::GetDirectories(
$path, '*', 'AllDirectories'
) -replace '[^\\/]').ForEach('Length')
)
注意:以上内容也总是包含隐藏目录。在 .NET Core / .NET 5+ 中,[System.IO.Directory]::GetDirectories() 现在提供了一个 additional overload,它提供了对枚举的更多控制。
列出最大深度的目录:
如果您不仅要计算最大深度,还想列出所有具有最大深度的目录(注意可以有多个):
# Sample input path.
# Note: Makes sure that $path is a *full* path, because .NET's current
# directory usually differs from PowerShell's.
$path = $PWD
# Extract all directories with the max. depth using Group-Object:
# Group by the calculated depth and extract the last group, which relies on
# Group-Object outputting the results sorted by grouping criteria.
$maxDepthGroup =
[System.IO.Directory]::GetDirectories($path, '*', 'AllDirectories') |
Group-Object { ($_ -split '[\\/]').Count } |
Select-Object -Last 1
# Construct the output object.
[pscustomobject] @{
MaxDepth = $maxDepthGroup.Values[0] # The grouping criterion, i.e. the depth.
MaxDepthDirs = $maxDepthGroup.Group # The paths comprising the group.
}
输出是一个自定义对象,具有.MaxDepth 和.MaxDepthDirs(具有最大深度的那些目录的完整路径的数组)属性。如果你将它通过管道发送到Format-List,你会得到类似的东西:
MaxDepth : 6
MaxDepthDirs : {/Users/jdoe/Documents/Ram Dass Audio Collection/The Path of Service, /Users/jdoe/Documents/Ram Dass Audio Collection/Conscious Aging,
/Users/jdoe/Documents/Ram Dass Audio Collection/Cultivating the Heart of Compassion, /Users/jdoe/Documents/Cheatsheets/YAML Ain't
Markup Language_files}