如何在PowerShell中使用tree命令显示文件及隐藏目录
在PowerShell中显示完整项目树形结构(含文件、隐藏文件夹)
方法1:利用cmd的tree命令(快速兼容)
PowerShell里默认调用的tree是cmd的tree命令,默认仅展示目录,要同时显示文件和隐藏文件夹需组合参数:
- 显示目录+文件:执行
tree /f - 显示目录+文件+隐藏文件夹(如.git):由于cmd的tree默认不遍历隐藏目录,需先通过PowerShell枚举所有项(含隐藏项)再传给tree,命令如下:
Get-ChildItem -Recurse -Force | Out-String -Stream | tree /f /a
其中-Force用于包含隐藏项,/a让tree用ASCII字符绘制树形线,避免部分终端显示乱码。
方法2:PowerShell原生命令(灵活可控)
如果想要定制化的树形输出,用Get-ChildItem结合自定义格式:
基础纯文本版
Get-ChildItem -Recurse -Force | ForEach-Object { # 计算当前项的层级深度 $depth = ($_.FullName.Split([System.IO.Path]::DirectorySeparatorChar).Count) - ($PWD.Path.Split([System.IO.Path]::DirectorySeparatorChar).Count) $indent = ' ' * $depth # 区分目录与文件输出 if ($_.PSIsContainer) { Write-Host "$indent[DIR] $($_.Name)" -ForegroundColor Cyan } else { Write-Host "$indent[FILE] $($_.Name)" -ForegroundColor Gray } }
该命令用颜色区分目录和文件,同时包含所有隐藏项。
图标直观版(终端支持Unicode时可用)
Get-ChildItem -Recurse -Force | ForEach-Object { $depth = ($_.FullName.Split([System.IO.Path]::DirectorySeparatorChar).Count) - ($PWD.Path.Split([System.IO.Path]::DirectorySeparatorChar).Count) $indent = ' ' * $depth if ($_.PSIsContainer) { Write-Host "$indent📂 $($_.Name)" -ForegroundColor Cyan } else { Write-Host "$indent📄 $($_.Name)" -ForegroundColor Gray } }
补充说明
Get-ChildItem的-Recurse参数用于递归遍历所有子目录,-Force参数强制显示隐藏项和系统项(包括.git文件夹)- 若不需要树形结构,仅需列出所有项完整路径,可直接执行
Get-ChildItem -Recurse -Force | Select-Object FullName
内容的提问来源于stack exchange,提问作者Stefan Glova
相关产品推荐
相关产品推荐

