PowerShell递归获取目录列表 按父子层级紧邻排序输出方法
实现方案
Get-ChildItem搭配-Depth参数默认走广度优先遍历逻辑,会先返回当前层级所有目录,再统一返回下一层级目录,无法实现父目录条目后紧跟直属子目录的效果。通过自定义递归函数走深度优先遍历,即可匹配预期输出顺序,还可按需增加文件计数功能。
基础版本(仅按父子层级输出目录路径)
执行以下代码即可,遍历深度可自行调整:
function Get-DirTree { param( [Parameter(Mandatory)] [string]$TargetPath, [int]$Depth = 3, [int]$CurrentLevel = 0 ) $curDirs = Get-ChildItem -Path $TargetPath -Directory foreach ($dir in $curDirs) { $dir.FullName if ($CurrentLevel -lt $Depth - 1) { Get-DirTree -TargetPath $dir.FullName -Depth $Depth -CurrentLevel ($CurrentLevel + 1) } } } # 替换为你实际要查询的路径调用即可 Get-DirTree -TargetPath "C:\Users\Moshe\onedrive\pictures\" -Depth 3
该逻辑每读取到一个目录就立刻输出,紧接着遍历该目录的直属子级,输出顺序和预期完全一致:先展示35mm_Film,再展示Camera imports,紧接着列出其下的Folder1、Folder2、Folder3,之后展示Camera Roll,紧跟其下的2014、2016子目录。
增强版本(附带目录文件计数)
需要在目录条目后展示文件数量的话,用以下版本,默认统计目录下直属文件数:
function Get-DirTreeWithCount { param( [Parameter(Mandatory)] [string]$TargetPath, [int]$Depth = 3, [int]$CurrentLevel = 0 ) $curDirs = Get-ChildItem -Path $TargetPath -Directory foreach ($dir in $curDirs) { # 统计直属文件数,要统计包含子目录的总文件数就给Get-ChildItem加-Recurse参数 $fileCount = (Get-ChildItem -Path $dir.FullName -File -ErrorAction SilentlyContinue | Measure-Object).Count [PSCustomObject]@{ FullPath = $dir.FullName DirectFileCount = $fileCount } if ($CurrentLevel -lt $Depth - 1) { Get-DirTreeWithCount -TargetPath $dir.FullName -Depth $Depth -CurrentLevel ($CurrentLevel + 1) } } } # 调用示例 Get-DirTreeWithCount -TargetPath "C:\Users\Moshe\onedrive\pictures\" -Depth 3
注意事项
- 遍历无权限访问的系统目录时会抛出错误,可在所有
Get-ChildItem命令后追加-ErrorAction SilentlyContinue参数跳过无权限路径 - 若需要调整目录缩进展示层级,可在输出时根据
$CurrentLevel参数值拼接对应数量的缩进空格即可
内容的提问来源于stack exchange,提问作者Moshe Yalovsky
相关产品推荐
相关产品推荐

