-1

We regularly download files, which have repeated parts of a file name. This is an issue as the drive we have to save them to has a 256 character path limit, and they are saved many subfolders deep. At the moment I manually remove repeated parts of the file name that are the same, as per the attached image, deleted parts are highlighted in red: enter image description here

Is there a batch file/quicker way of looking for a duplicate in the file name and removing it? Thanks, Russ.

Appleoddity
  • 11,970

1 Answers1

1

Disclaimer: This PowerShell-code has not been sufficiently tested to know that it will work properly in all environments with all kinds of possibly strange filenames / formats. But, it does work on your provided examples. Use at your own risk or use Rename-Item with the -WhatIf-switch (so it will only show what it would do without actually atering the filename).


Sample folder:

CDS 202 - GLAZING PACKERS_CDS 202 - Glazing Packers_CDS 202 - Glazing Packers.docx
CDS 202 - GLAZING PACKERS_CDS 202 - Glazing Packers_CDS 202 - Glazing Packers.pdf
CDS 202 - GLAZING PACKERS_PX-INA-PD-RP-X-XX-XX-0026.pdf

Here are examples how to accomplish the task:

# Remove all duplicates in filenames in current folder: (Case Sensitive)
Get-ChildItem -Path .\* -File | ForEach-Object {
    Rename-Item $_ -NewName ((($_.Basename.Split("_") | Select-Object -Unique) -Join "_") + $($_.Extension))
}

# Results:
# CDS 202 - GLAZING PACKERS_CDS 202 - Glazing Packers.docx
# CDS 202 - GLAZING PACKERS_CDS 202 - Glazing Packers.pdf
# CDS 202 - GLAZING PACKERS_PX-INA-PD-RP-X-XX-XX-0026.pdf
# Remove all duplicates in filenames in current folder: (Case Insensitive - Drawback: filenames are converted to upper case)
Get-ChildItem -Path .\* -File | ForEach-Object {
    Rename-Item $_ -NewName ((($_.Basename.Split("_").ToUpper() | Select-Object -Unique) -Join "_") + $($_.Extension))
}

# Results:
# CDS 202 - GLAZING PACKERS.docx
# CDS 202 - GLAZING PACKERS.pdf
# CDS 202 - GLAZING PACKERS_PX-INA-PD-RP-X-XX-XX-0026.pdf
# Remove all duplicates in filenames in current folder and all subfolders: (Case Sensitive)
Get-ChildItem -Path .\* -File -Recurse | ForEach-Object {
    Rename-Item $_ -NewName ((($_.Basename.Split("_") | Select-Object -Unique) -Join "_") + $($_.Extension))
}

# Results:
# CDS 202 - GLAZING PACKERS_CDS 202 - Glazing Packers.docx
# CDS 202 - GLAZING PACKERS_CDS 202 - Glazing Packers.pdf
# CDS 202 - GLAZING PACKERS_PX-INA-PD-RP-X-XX-XX-0026.pdf
# Remove all duplicates in filenames in current folder and all subfolders: (Case Insensitive - Drawback: all filenames are converted to upper case)
Get-ChildItem -Path .\* -File -Recurse | ForEach-Object {
    Rename-Item $_ -NewName ((($_.Basename.Split("_").ToUpper() | Select-Object -Unique) -Join "_") + $($_.Extension))
}

# Results:
# CDS 202 - GLAZING PACKERS.docx
# CDS 202 - GLAZING PACKERS.pdf
# CDS 202 - GLAZING PACKERS_PX-INA-PD-RP-X-XX-XX-0026.pdf

Enjoy!

Appleoddity
  • 11,970