You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于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 -File to Get-ChildItem to avoid accidentally processing folders.
  • Accurate core name grouping: Changed the split to use _archived instead of just archived—this ensures we get a clean core name (e.g., M10001662_3269506_DVLA_Original_Complete for your sample files).
  • Actual rename execution: We now store the selected "keep" file in a variable ($fileToRetain) and use Rename-Item with the full file path to avoid path issues.
  • Safety first: The -WhatIf flag 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

  1. Test first: Always run with -WhatIf enabled to confirm the script is targeting the right files.
  2. Backup: If possible, make a backup of a small subset of your folders to test the script before running it on all 150 folders.
  3. Scale to all folders: If you want to run this across all 150 subfolders under a parent directory, just adjust the Get-ChildItem in Step 1 to use -Recurse (but test this carefully!).

内容的提问来源于stack exchange,提问作者Simon Bruce

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 15:47:28