如何在Windows PowerShell中实现带修改日期的tree /f目录树功能?
嘿,这个问题我刚好研究过!Windows自带的tree /f确实只能输出目录结构,没法带上修改日期,不过用系统自带的PowerShell就能轻松解决,甚至比cmd的tree功能更灵活。下面给你几个实用的方案:
方案1:基础列表式输出(快速查看)
如果不需要严格的树状缩进,只是想快速获取所有文件/文件夹及其修改日期,直接用这行PowerShell命令就行:
Get-ChildItem -Path "D:\" -Recurse | Select-Object FullName, LastWriteTime | Format-Table -AutoSize
- 解释:
Get-ChildItem -Recurse会递归遍历指定路径下的所有内容;Select-Object筛选出完整路径和最后修改时间;Format-Table -AutoSize让输出的表格自动调整列宽,看起来更整齐。
方案2:带缩进的树状结构(更直观)
如果想要和tree /f类似的树状缩进效果,同时显示修改日期,可以自定义一个PowerShell函数:
function Get-TreeWithDate { param( [string]$Path = ".", # 默认当前目录,可指定目标路径 [int]$Indent = 0 # 缩进层级,内部递归用 ) $items = Get-ChildItem -Path $Path foreach ($item in $items) { # 根据层级生成缩进空格 $indentStr = " " * $Indent # 标记文件夹和文件,同时格式化修改日期 if ($item.PSIsContainer) { Write-Host "$indentStr[DIR] $($item.Name) - $($item.LastWriteTime.ToString('yyyy-MM-dd HH:mm:ss'))" # 递归遍历子文件夹,缩进层级+1 Get-TreeWithDate -Path $item.FullName -Indent ($Indent + 1) } else { Write-Host "$indentStr[FILE] $($item.Name) - $($item.LastWriteTime.ToString('yyyy-MM-dd HH:mm:ss'))" } } }
使用方法:
- 打开PowerShell,把上面的函数代码粘贴进去回车执行;
- 输入
Get-TreeWithDate -Path "D:\YourTargetFolder",替换成你需要的驱动器或文件夹路径,就能看到带缩进的树状结构+修改日期了。
方案3:导出到文本文件
如果需要把结果保存下来,直接在命令后面加导出指令就行:
比如用方案2的函数导出:
Get-TreeWithDate -Path "D:\YourTargetFolder" | Out-File -FilePath "D:\Tree_With_Dates.txt" -Encoding UTF8
或者用方案1的列表式导出:
Get-ChildItem -Path "D:\" -Recurse | Select-Object FullName, LastWriteTime | Format-Table -AutoSize | Out-File -FilePath "D:\File_List.txt" -Encoding UTF8
另外,你还可以调整日期格式,比如把yyyy-MM-dd HH:mm:ss改成MM/dd/yyyy hh:mm tt(12小时制带AM/PM),或者其他你习惯的格式。
内容的提问来源于stack exchange,提问作者Ben Klein
相关产品推荐
相关产品推荐

