JParish
JParish

Reputation: 11

Powershell file rename to remove a number of characters before a specific position or character

I have almost 8,000 files that have a file/path name that is too long for Windows. I need to keep the folder structure, so I need to short the file names.

File name examples:

File description that is waaay too long for Windows ABCD [General_123].doc
File description that is waaay too long for Windows AB123 [General_456].docx
Spreadsheet for Year 2023 with a too long name [General_159].xls

All file names end with [General_xxx], not always in the same position from the beginning of the file name. I want to remove about 20 characters or so from the end of the file name, while keeping the [General_xxx] and the file extension. And yes, the file names are using the square brackets [].

I started with this script, but can't figure out a way to remove characters from where I need them to be deleted from.

Get-ChildItem | rename-item -newname { $_.name.substring(0,$_.name.length-20) + $_.Extension }

Upvotes: 1

Views: 532

Answers (2)

jeremywat
jeremywat

Reputation: 1045

This will get the files, get the first portion of the filename before the [General_*] pattern, remove the last 20 characters, and then add the [General_*] string and extension back on.

Get-ChildItem | Rename-Item -NewName { $split = $_.basename -split '(?=\[General_.+\])' ; $split[0].substring(0, ($split[0].length - 20)) + $split[1] + $_.extension }

Upvotes: 0

Santiago Squarzon
Santiago Squarzon

Reputation: 60903

The following regex pattern might do what you're after, if the string has 20 characters before [....], then it will remove those 20 characters:

@'
File description that is waaay too long for Windows ABCD [General_123].doc
File description that is waaay too long for Windows AB123 [General_456].docx
Spreadsheet for Year 2023 with a too long name [General_159].xls
'@ -split '\r?\n' |
    Where-Object { $_ -match '.{20}(?=\[.+?\])' } |
    ForEach-Object { $_.Replace($Matches[0], '') }

# Outputs:

# File description that is waaay too lo[General_123].doc
# File description that is waaay too lon[General_456].docx
# Spreadsheet for Year 2023 w[General_159].xls

If you consider this works for your use case, then applied to the Rename-Item logic:

Get-ChildItem -File |
    Where-Object Name -match '.{20}(?=\[.+?\])' |
    Rename-Item -NewName { $_.Name.Replace($Matches[0], '') }

For details on the regex pattern you can check: https://regex101.com/r/Gqqq4t/1.

Upvotes: 2

Related Questions