Christian
Christian

Reputation: 3

Remove Sections of File Names w/PowerShell

I'm not super knowledgeable when it comes to coding but I'm trying to use PowerShell to find a way to remove the first X number of characters and Last X number of characters from multiple files. Hence, only keeping the middle section.

Ex) INV~1105619~43458304~~1913216023~0444857 , where 1913216023 is the invoice #. Anything before and after that needs to be removed from the file name.

I used: get-childitem *.pdf | rename-item -newname { string.substring(22) } to remove the first 22 characters but cannot manage to create a code to remove the remaining half. All files have the same number of characters but various numbers before and after the invoice number (every file name is different).

Any help/advice is greatly appreciated!

Upvotes: 0

Views: 814

Answers (2)

Theo
Theo

Reputation: 61068

There are several methods of doing this.
If you are sure you won't run into naming collisions (so all files have a different invoice number), here's how with three extra alternatives:

(Get-ChildItem -Path 'D:\Test' -Filter '*~~*~*.pdf' -File) | 
    Rename-Item -NewName { 
        # my favorite method
        '{0}{1}' -f ($_.BaseName -split '~')[-2], $_.Extension

        # or
        # '{0}{1}' -f ($_.BaseName -replace '^.*~~(\d{10})~.+$', '$1'), $_.Extension

        # or this one
        # '{0}{1}' -f ([regex]'~~(\d+)~').Match($_.BaseName).Groups[1].Value, $_.Extension

        # or if you are absolutely sure of the position and length of the invoice number
        # '{0}{1}' -f $_.BaseName.Substring(22,10), $_.Extension
    }

The Get-ChildItem line is between brackets to make sure the gathering of the FileInfo objects is complete before carrying on. If you don't do that, chances are you wil try and rename items multiple times

Upvotes: 0

js2010
js2010

Reputation: 27423

Assuming the target substring always has the same length, there's an overload to substring() that has a length parameter.

'INV~1105619~43458304~~1913216023~0444857'.substring

OverloadDefinitions
-------------------
string Substring(int startIndex)
string Substring(int startIndex, int length)


$startIndex, $length = 22, 10
'INV~1105619~43458304~~1913216023~0444857'.substring($startIndex, $length)

1913216023


dir ('?'*40) | rename-item -newname { $_.name.substring(22,10) } -whatif

What if: Performing the operation "Rename File" on target 
      "Item: C:\users\admin\foo\INV~1105619~43458304~~1913216023~0444857 
Destination: C:\users\admin\foo\1913216023".

Upvotes: 0

Related Questions