请求编写PowerShell脚本:按文件名特征批量移动文件至对应目录
PowerShell批量匹配目录移动文件解决方案
以下是满足需求的PowerShell脚本,直接运行即可完成批量文件移动:
# 配置源文件目录和目标根目录 $sourceDir = "c:\files" $targetRootDir = "c:\directories" # 获取所有以"November "开头的PDF文件 $files = Get-ChildItem -Path $sourceDir -Filter "November *.pdf" -File # 将目标子目录存入哈希表,提升匹配效率 $existingDirs = @{} Get-ChildItem -Path $targetRootDir -Directory | ForEach-Object { $existingDirs[$_.Name.Trim()] = $_.FullName } # 逐个处理文件 foreach ($file in $files) { # 提取"November "与"["之间的核心名称 if ($file.BaseName -match '^November\s+(.*?)\s+\[') { $targetDirName = $matches[1].Trim() # 匹配到对应目录则移动文件 if ($existingDirs.ContainsKey($targetDirName)) { $destPath = Join-Path -Path $existingDirs[$targetDirName] -ChildPath $file.Name Write-Host "正在移动: $($file.Name) -> $destPath" Move-Item -Path $file.FullName -Destination $destPath -Force } else { Write-Host "无匹配目录,跳过: $($file.Name)" } } else { Write-Host "文件名格式不匹配,跳过: $($file.Name)" } }
关键逻辑说明
- 哈希表存目录:把目标目录的名称和路径存入哈希表,避免每次匹配都遍历目录,处理300个文件时效率会明显提升。
- 正则提取核心名称:用
^November\s+(.*?)\s+\[精准捕获文件名中需要匹配的部分,.*?是非贪婪匹配,确保只取到"["之前的内容,Trim()处理首尾空格,防止因文件名或目录名的空格差异导致匹配失败。 - 容错处理:对格式不符合的文件、无匹配目录的文件都输出提示,方便后续核对未处理的文件。
内容的提问来源于stack exchange,提问作者JackDonaghy
相关产品推荐
相关产品推荐

