我试图找出这个问题,并进行了广泛的搜索,看看其他人是否找到了以前的解决方案,但找不到任何东西。我对 powershell 还很陌生,所以请跟我讲。
我有数百个标题相似的文件,唯一 ID 位于标题开头:
unique ID_2024 Details.pdf
。我想将这个目录C:\F\2024 Detailed Letters
中的PDF文件移动到这个文件夹C\:F\Individual Folders\XXX_XXXX [unique ID]
中的各个文件夹。唯一ID包含8个字符。
各个文件夹中有数千个文件夹,因此每个字母都需要发送到末尾具有唯一 ID 的文件夹。
我在使用 Substring 时遇到问题,因为我无法弄清楚如何将 PDF 名称开头的唯一 ID 与文件夹标题末尾的唯一 ID 相匹配。我无法选择重命名文件夹或文件。
谢谢!
$FilesToMove = 'C:\F\2024 Detailed Letters'
$TargetPath = 'C\:F\Individual Folders'
$Files = Get-ChildItem -Path $FilesToMove -File
foreach ($File in $Files) {
$PathToMove = Get-ChildItem -Path $TargetPath -Directory -Filter "$(($File.Basename).Substring(0,8))*" | Select-Object -First 1
Write-Output "Moving File $File to $PathToMove"
Move-Item -Path $File.FullName -Destination "$($PathToMove.Fullname)\$($File.Name)"
}
当然,唯一的 ID 确实是唯一的,并且不会与其他文件夹名称中的任何其他内容匹配,我认为这应该可以。不过,请先尝试批量测试:)
这将获取输入文件名的前 8 个字符,并找到一个名称包含唯一 ID 的文件夹(但不是明确以唯一 ID 结尾的文件夹 - 我现在懒得找到 100% 精确的正则表达式,抱歉)
$FilesToMove = 'C:\F\2024 Detailed Letters'
$TargetPath = 'C:\F\Individual Folders'
$Files = Get-ChildItem -Path $FilesToMove -File
$DestinationFolders = Get-ChildItem -Path $TargetPath -Directory
foreach ($File in $Files) {
$DestinationFolderPath = $null
foreach($Folder in $DestinationFolders){
if($Folder.Name -match "$(($File.Basename).Substring(0,8))"){
$DestinationFolderPath = $Folder.FullName
}
}
if($DestinationFolderPath){
Write-Output "Moving File $($File.Name) to $DestinationFolderPath"
Move-Item -Path $File.FullName -Destination $DestinationFolderPath
}else{
Write-Host "Could not find destination folder for $($File.Name)"
}
}
看来您走在正确的道路上。我现在才弄清楚过滤器是如何工作的。 为了提高速度,最好将目标文件夹的
Get-ChildItem
分开,然后使用该对象,而不是为正在处理的每个文件重新运行该命令。这样就不必每次扫描数千个文件夹。
希望这有帮助:)干杯