You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让PowerShell的Get-ChildItem按深度优先格式化输出?

如何让PowerShell的Get-ChildItem以深度优先方式输出内容

PowerShell的Get-ChildItem -Recurse默认采用广度优先遍历,会先输出当前目录的所有项(文件和子目录),再依次输出各子目录的内容,就像你给出的示例那样。要实现深度优先输出,有以下可行方法:

方法一:自定义递归函数实现深度优先遍历

写一个自定义函数,先输出当前目录的所有文件,再逐个遍历子目录,递归处理每个子目录的内容(先输出目录本身,再深入处理其内部的文件和子目录):

function Get-ChildItemDepthFirst {
    param(
        [string]$Path = $PWD.Path
    )
    # 输出当前目录下的所有文件
    Get-ChildItem -Path $Path -File
    # 遍历当前目录下的子目录,递归处理
    foreach ($dir in Get-ChildItem -Path $Path -Directory) {
        $dir  # 输出子目录本身
        Get-ChildItemDepthFirst -Path $dir.FullName
    }
}

调用该函数并提取完整路径:

Get-ChildItemDepthFirst | Select-Object -ExpandProperty FullName

执行后就能得到你期望的深度优先输出格式:

C:\dev\stack-overflow-question\my.csv
C:\dev\stack-overflow-question\special-tree.ps1
C:\dev\stack-overflow-question\foo
C:\dev\stack-overflow-question\foo\bar
C:\dev\stack-overflow-question\foo\bar\baz
C:\dev\stack-overflow-question\foo\bar\baz\hw.txt
C:\dev\stack-overflow-question\quz
C:\dev\stack-overflow-question\quz\empty-dir

补充说明

如果需要包含隐藏项,可以在Get-ChildItem命令中添加-Force参数;如果要调整输出顺序(比如先目录后文件),只需调换函数中输出文件和遍历目录的顺序即可。

内容的提问来源于Stack Exchange,提问作者display-name

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 20:34:55