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

如何通过PowerShell按filelist.txt指定路径递归删除对应文件

问题根因

原脚本中使用的Get-ChildItem的-Include参数仅会匹配文件/目录的名称字段,无法识别带层级的相对路径,因此当filelist.txt中写入带路径的条目时匹配失败,无法执行删除。

调整后脚本

$TargetFolder = "C:\folder"
$fileList = "C:\folder\filelist.txt"

# 逐行读取文件列表,拼接绝对路径后执行删除
Get-Content $fileList | ForEach-Object {
    # 替换路径分隔符为Windows兼容的反斜杠,拼接绝对路径
    $targetPath = Join-Path -Path $TargetFolder -ChildPath ($_ -replace '/', '\')
    if (Test-Path -Path $targetPath -PathType Leaf) {
        Remove-Item -Path $targetPath -Verbose
    }
}

改动说明

  • 抛弃了原有的递归遍历+通配匹配逻辑,直接根据filelist.txt的指定路径定位文件,完全避免不同目录下同名文件误删的问题
  • 自动兼容filelist.txt中的正斜杠/、反斜杠\两种路径分隔符写法
  • 增加路径存在判断,避免目标文件不存在时抛出冗余报错

如果有需要保留递归扫描逻辑的场景,也可以使用如下写法,通过匹配文件的FullName属性实现路径校验:

$TargetFolder = "C:\folder"
$fileList = "C:\folder\filelist.txt"
# 先把所有要删除的相对路径转成绝对路径后缀的匹配规则
$matchRules = Get-Content $fileList | ForEach-Object {
    ($_ -replace '/', '\').TrimStart('\') + '$'
}
Get-ChildItem -Path $TargetFolder -Recurse -File | Where-Object {
    $relativePath = $_.FullName.Substring($TargetFolder.Length).TrimStart('\')
    $relativePath -match ($matchRules -join '|')
} | Remove-Item -Verbose

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 12:24:05