基于PowerShell Group-Object输出批量重命名并保留唯一PDF文件的技术求助
Fixing Your PowerShell Duplicate PDF Cleanup Script
Hey there, let's get this script working right! Your approach to mark, delete, and restore is solid, but your code was missing the actual rename logic for the files you want to keep, plus a few syntax tweaks. Here's the corrected version with step-by-step explanations:
Corrected PowerShell Script
# Remove duplicate files - based on core name matching # Set the root folder to process $dir = 'O:\UKCH-DATA\Contact Centre\04 - Main\14 - DVLA\_case_files_archive\M10001662' # Step 1: Mark the first file of each core group by renaming it to .new Get-ChildItem -Path $dir -Filter "*.pdf" -File | Group-Object -Property {$_.BaseName.Split('_archived', 2)[0]} | ForEach-Object { # Grab the first file in each core name group (this is the one we'll keep) $fileToRetain = $_.Group | Select-Object -First 1 # Rename the file to use .new extension Rename-Item -Path $fileToRetain.FullName -NewName ($fileToRetain.FullName -replace '\.pdf$', '.new') -WhatIf } # Step 2: Delete all remaining .pdf files (these are the duplicates) Get-ChildItem -Path $dir -Filter "*.pdf" -File | Remove-Item -WhatIf # Step 3: Restore the retained files back to .pdf extension Get-ChildItem -Path $dir -Filter "*.new" -File | Rename-Item -NewName {$_.Name -replace '\.new$', '.pdf'} -WhatIf
Key Fixes & Explanations
- Target only files: Added
-FiletoGet-ChildItemto avoid accidentally processing folders. - Accurate core name grouping: Changed the split to use
_archivedinstead of justarchived—this ensures we get a clean core name (e.g.,M10001662_3269506_DVLA_Original_Completefor your sample files). - Actual rename execution: We now store the selected "keep" file in a variable (
$fileToRetain) and useRename-Itemwith the full file path to avoid path issues. - Safety first: The
-WhatIfflag lets you preview all changes without modifying files. Run the script with this flag first to verify operations are correct, then remove it when you're ready to apply changes.
Important Notes
- Test first: Always run with
-WhatIfenabled to confirm the script is targeting the right files. - Backup: If possible, make a backup of a small subset of your folders to test the script before running it on all 150 folders.
- Scale to all folders: If you want to run this across all 150 subfolders under a parent directory, just adjust the
Get-ChildItemin Step 1 to use-Recurse(but test this carefully!).
内容的提问来源于stack exchange,提问作者Simon Bruce
相关产品推荐
相关产品推荐

