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

如何删除文件名包含.txt文件中指定file_id的文件

问题:批量删除文件名包含指定ID的文件

我在外接SSD的一个文件夹中有2000多个文件,同文件夹内还有一个.txt文件,其中包含特定的文件名片段;文件命名格式为“file_title-file_id.json”,而.txt文件中包含近2000个此类“file_id”。我需要删除该文件夹中所有文件名包含.txt文件内所列“file_id”的文件。我基本没有脚本编写经验,网上找到的所有“解决方案”似乎都不起作用,比如:

第一段无效代码:

gc .\MyListOfFilesIWantToDelete.txt | %{gci $_ -Recurse | Remove-Item -WhatIf}

第二段无效代码:

$TargetFolder = “Pathofyourfolder”
$Files = Get-ChildItem $TargetFolder -Recurse| Where Name -in (gc List.txt) 
foreach ($File in $Files)
{ 
    write-host “Deleting File $File” -foregroundcolor “Red”; 
    Remove-Item $File | out-null
}

最终有效解决方案

结合建议调整后,我得到了一段能按预期仅删除.txt文件中包含的ID对应文件的代码:

$folder_path = "D:\ambra"    # 替换为你的文件夹路径
$file_path = ".\list.txt"  # 替换为你的.txt文件路径

# 读取.txt文件中的file_id并存储到数组
$file_IDs = Get-Content -Path $file_path

# 初始化已删除文件计数器
$deleted_count = 0

# 获取文件夹中所有文件
$files = Get-ChildItem -Path $folder_path -File

# 遍历文件,删除匹配ID的文件
foreach ($file in $files) {
    $file_title, $file_id, $file_extension = $file.BaseName -split '-', 3
    if ($file_id -in $file_IDs) {
        # 计数器加1
        $deleted_count++
        Write-Host -ForegroundColor Red "匹配到file_id: $file_id"
        Remove-Item -Path $file.FullName -Force
    }
}
# 显示已删除文件总数
Write-Host "已删除文件总数: $deleted_count"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 16:13:38