Get-Tree 是一个 PowerShell 函数,用于以树状格式显示目录结构。它提供类似 Unix
tree 命令的功能,也可以返回适合继续处理的对象结构。
- 🌳 树状显示: 以直观的树状格式显示目录结构
- 🎨 彩色输出: 不同类型的文件和目录使用不同颜色显示
- 📁 深度控制: 可自定义显示的最大深度
- 🔍 文件过滤: 可选择是否显示文件,或排除特定文件
- 👁️ 隐藏文件: 可选择是否显示隐藏文件和目录
- 📊 数量限制: 可限制每个目录显示的最大项目数
- 🚀 跨平台: 支持Windows、macOS和Linux
Get-Tree [[-Path] <String>] [-MaxDepth <Int32>] [-ShowFiles <Boolean>] [-ShowHidden <Boolean>] [-Exclude <String[]>] [-MaxItems <Int32>] [-UseGitignore <Boolean>] [-AsObject <Boolean>]| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
Path |
String | "." | 要显示树状结构的目录路径 |
MaxDepth |
Int32 | 3 | 最大显示深度,0 表示无限深度 |
ShowFiles |
Boolean | $true | 是否显示文件 |
ShowHidden |
Boolean | $false | 是否显示隐藏文件和目录 |
Exclude |
String[] | @() | 要排除的文件或目录名称模式(支持通配符) |
MaxItems |
Int32 | 50 | 每个目录中显示的最大项目数 |
UseGitignore |
Boolean | $true | 是否读取 .gitignore 并过滤匹配项 |
AsObject |
Boolean | $false | 是否返回目录树对象而不是写入彩色控制台输出 |
# 显示当前目录的树状结构(默认3层深度)
Get-Tree
# 显示指定目录的树状结构
Get-Tree -Path "C:\Users"# 显示2层深度
Get-Tree -MaxDepth 2
# 显示所有层级(无限深度)
Get-Tree -MaxDepth 0# 只显示目录,不显示文件
Get-Tree -ShowFiles $false# 排除所有.tmp文件和node_modules目录
Get-Tree -Exclude @("*.tmp", "node_modules")
# 排除多种文件类型
Get-Tree -Exclude @("*.log", "*.tmp", "*.cache")# 显示包括隐藏文件在内的所有文件
Get-Tree -ShowHidden $true# 每个目录最多显示10个项目
Get-Tree -MaxItems 10# 组合多个参数
Get-Tree -Path "./src" -MaxDepth 4 -ShowFiles $true -Exclude @("*.min.js", "node_modules") -MaxItems 20# 返回可继续筛选或转换为 JSON 的目录树对象
$tree = Get-Tree -Path './src' -MaxDepth 2 -AsObject $true
$tree | ConvertTo-Json -Depth 20
# 忽略当前目录的 .gitignore 规则
Get-Tree -Path './src' -UseGitignore $false- 🔵 蓝色: 目录
- ⚪ 白色: 普通文件
- 🔘 深灰色: 隐藏文件
- 🟢 绿色: 可执行文件(.exe, .bat, .cmd, .ps1, .sh等)
- 🟡 黄色: 压缩文件(.zip, .rar, .7z等)
C:\MyProject
├── src/
│ ├── components/
│ │ ├── Header.js
│ │ └── Footer.js
│ ├── utils/
│ │ └── helpers.js
│ └── index.js
├── tests/
│ └── app.test.js
├── package.json
└── README.md
- 权限: 如果没有访问某个目录的权限,会显示警告信息但不会中断执行
- 性能: 对于包含大量文件的目录,建议使用
MaxDepth和MaxItems参数来限制输出 - 通配符:
Exclude参数支持PowerShell通配符模式(如*,?) - 路径: 支持相对路径和绝对路径
-
从仓库根目录导入规范 manifest:
Import-Module ./psutils/psutils.psd1 -Force
-
使用函数:
Get-Tree -
查看帮助:
Get-Help Get-Tree -Full
Get-ChildItem: PowerShell内置的目录列表函数tree: Windows/Unix系统的树状目录显示命令