如何用PowerShell将按文件夹名匹配的PDF文件移动到对应Contracts子文件夹
问题根源
你遇到的报错是Join-Path的参数使用错误导致的:PowerShell 5.1及更早的主流版本中,Join-Path默认仅支持两个路径段拼接,你直接传入3个参数$Folder、$Matches[0]、"Contracts",命令无法识别第三个参数,生成的目标路径不符合预期,因此移动失败。
解决方案
以下两种写法都可以正确生成目标路径,按需选择即可:
写法1:嵌套使用Join-Path(兼容性最好,全版本可用)
把两次Join-Path嵌套,先拼接根目录和匹配到的文件夹名,再拼接Contracts子目录:
$file | Move-Item -Destination (Join-Path (Join-Path $Folder $Matches[0]) "Contracts")
写法2:使用-AdditionalChildPath参数(适用PowerShell 7+)
如果你的运行环境是PowerShell 7及以上版本,可以直接用官方新增的多路径拼接参数:
$file | Move-Item -Destination (Join-Path $Folder $Matches[0] -AdditionalChildPath "Contracts")
优化建议(可选)
可以在移动前增加子目录存在性判断,避免手动创建Contracts目录的操作,自动补全缺失的目录,修改后的完整代码如下:
$Folder = "C:\Users\Bob\Desktop\Scripting\Bronmap" $FileType = "*.pdf" $Files = Get-ChildItem -Path $Folder -Filter $FileType $RE = [regex]((Get-ChildItem -Path $Folder -Directory -Name) -Join '|') ForEach($file in $Files){ if ($file.BaseName -Match $RE){ # 生成目标路径并自动创建不存在的目录 $targetDir = Join-Path (Join-Path $Folder $Matches[0]) "Contracts" if (-not (Test-Path $targetDir)) { New-Item -ItemType Directory -Path $targetDir | Out-Null } $file | Move-Item -Destination $targetDir } else { $file | Move-Item -Destination (Join-Path $Folder "No_Folder") } }
内容的提问来源于stack exchange,提问作者Bob Verbrugge
相关产品推荐
相关产品推荐

