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

PowerShell递归遍历文件夹时如何输出文件的相对路径

解决方案

直接替换原脚本中仅取文件名的逻辑,获取文件相对于源目录的路径后输出即可,以下是两种可直接运行的实现:

方法1:使用.NET内置API(推荐,兼容性强)

PowerShell 5.1及以上版本均支持[System.IO.Path]::GetRelativePath()方法,可自动处理路径斜杠、大小写、末尾斜杠差异,不会出现匹配错误:

$srcpth = "C:\Users\Mark\Desktop\dummy\"
# 先将源路径转为标准绝对路径,避免格式差异导致的问题
$srcFullPath = (Resolve-Path $srcpth).Path
$files = Get-ChildItem -Path $srcpth -File -Recurse 

foreach ($f in $files) {
    # 计算文件相对于源目录的路径
    $relativePath = [System.IO.Path]::GetRelativePath($srcFullPath, $f.FullName)
    $filesize = $f.Length
    # 需要\前缀就保留拼接的反斜杠,不需要就直接写$relativePath
    Write-Output "\$relativePath $filesize"
}

方法2:字符串截断法(适配老版本PowerShell)

如果使用不支持上述API的老旧PowerShell版本,可以直接从文件全路径中截掉源路径前缀得到相对路径:

$srcpth = "C:\Users\Mark\Desktop\dummy\"
# 统一源路径格式,确保末尾带单个反斜杠
$srcFullPath = (Resolve-Path $srcpth).Path.TrimEnd('\') + '\'
$files = Get-ChildItem -Path $srcpth -File -Recurse 

foreach ($f in $files) {
    $relativePath = $f.FullName.Substring($srcFullPath.Length)
    $filesize = $f.Length
    Write-Output "\$relativePath $filesize"
}

两种方法运行后的输出完全匹配预期效果,针对你给出的示例目录结构,输出结果如下:

\file00.txt 9
\folder01\file01_01.txt 10
\folder01\file01_02.txt 12
\folder01\file01_03.txt 12
\folder02\file02_01.txt 15
\folder02\file02_01.txt 14
\folder03\file03_01.txt 11
\folder03\file03_02.txt 15
\folder03\file03_03.txt 13
\folder03\file03_04.txt 12

如果不需要根目录文件前的反斜杠,删掉输出语句中拼接的\即可。

内容的提问来源于stack exchange,提问作者HTWingNut

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 22:01:06