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

PowerShell:批量处理子文件夹匹配正则的文件并复制重命名至父文件夹

问题解决:批量处理子文件夹内匹配规则的图片文件

原脚本的问题

  • 加了-Recurse会递归遍历所有深层子文件夹,导致处理到的文件可能不在你要的直接子文件夹里,偏离需求
  • PipelineVariable的使用多余,嵌套循环里容易搞混变量指代
  • 同一个子文件夹如果有多个符合规则的文件,复制时会直接覆盖之前生成的目标文件,没做冲突处理

修正后的脚本

Get-ChildItem -Path "D:\principal\where\contains\all\folders" -Directory | ForEach-Object {
    $currentFolder = $_
    Write-Information "开始处理文件夹:$($currentFolder.Name)" -InformationAction Continue
    
    # 只取当前子文件夹下的jpg文件,不递归深层目录
    Get-ChildItem -Path $currentFolder.FullName -Filter *.jpg -File | 
        Where-Object Name -match '^.*6[0-9][0-9].*$' |
        ForEach-Object {
            Write-Information "正在处理文件:$($_.Name)" -InformationAction Continue
            # 用Join-Path拼接路径,避免手动拼错分隔符
            $targetPath = Join-Path -Path $currentFolder.Parent.FullName -ChildPath "$($currentFolder.Name).jpg"
            
            # 检查目标文件是否存在,避免直接覆盖
            if (Test-Path -Path $targetPath) {
                Write-Information "目标文件 $($currentFolder.Name).jpg 已存在,跳过当前文件" -InformationAction Continue
            } else {
                Copy-Item -Path $_.FullName -Destination $targetPath -Force
            }
        }
    
    Write-Information "完成文件夹处理:$($currentFolder.Name)" -InformationAction Continue
}

关键调整说明

  • 删掉-Recurse参数,确保只处理父文件夹下的直接子文件夹里的文件
  • 用Join-Path替代手动拼接路径,避免因系统路径分隔符(比如\或/)导致的错误
  • 新增目标文件存在检查,防止同一子文件夹下多个匹配文件互相覆盖
  • 简化变量引用逻辑,避免嵌套循环里的变量混淆

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 20:00:13