Search code examples
powershelltexttrimming

Programmatically edit file names to remove leading text


I have a variety of files with names in the directory that look like this:

first_file_123456.jpg
5 * second_file_246531 (2).jpg

What I am looking to do is lay my hands on a PowerShell script that can take these files and rename them like this:

123456.jpg
246531 (2).jpg

I am looking to strip the last underscore and all text leading up to it to rename my files so they can match item numbers in my enterprise resource planning system. This system is much older (2004 technology) so automating from that side is out.

What i have tried to wire up so far and does not seem to work properly is as follows:

    Get-ChildItem -Recurse -filter *_*  | `
    Foreach-Object {
    $oldName = $_.Name
    $pos = $oldName.LastIndexOf("_")
    $newName = $oldName.Substring($pos + 1)
    if (Test-Path $newName) {
        # This is where I get lost - if it runs into a duplicate file name
        # how can I make the name unique
    }        
    #write-host $_.fullname
    write-host $oldName renamed To: $newName | Out-File renamelog.txt
    #rename-item $_.FullName -NewName $newName
}

I commented out the commands that actually do something to see what the output is.


Solution

  • Enumerate your files, filter for filenames containing an underscore, then rename them with everything up to and including the last underscore removed.

    $re = '^.*_'
    
    Get-ChildItem 'C:\some\folder' |
        Where-Object { $_.Name -match $re } |
        Rename-Item -NewName { $_.Name -replace $re }