PowerShell实现按前缀匹配将文件移动至对应目标文件夹
修正后的PowerShell脚本解决方案
针对你的需求,需要先在目标目录下查找名称以6位前缀开头的子文件夹,再定位到对应的Correspondence(或你示例中的Corres,注意拼写一致性)子目录,确认路径存在后再移动文件。以下是修正后的脚本:
$sourceDirectory = "C:\Directory\Source" $destinationRoot = "C:\Directory\Destination" $corresSubfolderName = "Correspondence" # 若实际是示例里的"Corres",请修改此处 # 获取源目录下所有文件 $files = Get-ChildItem -File -Path $sourceDirectory foreach ($file in $files) { # 提取文件名前6位作为前缀 $prefix = $file.Name.Substring(0, 6) # 在目标根目录下查找名称以当前前缀开头的子文件夹 $targetParentFolder = Get-ChildItem -Directory -Path $destinationRoot | Where-Object { $_.Name.StartsWith($prefix) } | Select-Object -First 1 # 确保只取第一个匹配的文件夹(你说明每个文件对应唯一目标) if ($targetParentFolder) { # 拼接最终的目标子目录路径(对应Correspondence/Corres文件夹) $folderPath = Join-Path -Path $targetParentFolder.FullName -ChildPath $corresSubfolderName # 检查目标子目录是否存在,不存在则跳过(不创建) if (Test-Path -Path $folderPath -PathType Container) { $destinationPath = Join-Path -Path $folderPath -ChildPath $file.Name Move-Item -Path $file.FullName -Destination $destinationPath -ErrorAction SilentlyContinue Write-Host "已移动文件: $($file.Name) 到 $destinationPath" } else { Write-Warning "未找到对应子目录: $folderPath,跳过文件 $($file.Name)" } } else { Write-Warning "未找到以前缀 $prefix 开头的目标文件夹,跳过文件 $($file.Name)" } }
关键修改说明:
- 匹配前缀文件夹:通过
Get-ChildItem -Directory获取目标根目录下的所有子文件夹,再用Where-Object { $_.Name.StartsWith($prefix) }筛选出名称以6位前缀开头的文件夹 - 避免创建不存在的文件夹:用
Test-Path -PathType Container检查目标子目录是否存在,仅当存在时才执行移动操作 - 容错处理:增加了
Write-Warning提示未找到对应文件夹/子目录的情况,避免脚本报错中断 - 拼写一致性:将
Correspondence设为变量,方便你根据实际目录名称修改(比如示例中的Corres)
内容的提问来源于stack exchange,提问作者memphreblues
相关产品推荐
相关产品推荐

