Search code examples
powershellpowershell-4.0

Batch Renaming - Again


I'm helping a charity out with some IT issues they're having. Part of it is to tidy up their documents and work. I am trying to script some renaming without much luck!

They have lots of video blogs, audio files and word type docs all with bad files names. Bad as in, The Old Man and his dog.mp4

There is a lot the start with "The" "i" "A" etc. I've sorted into folders based on types of files now. But still would like to update the file names to read more like

Old Man and His Dog (The).mp4

Could you help a little here as I am still new to Powershell and learning on the job.

I've been able to remove the first part of the file name, but don't know how to add it to the end of the file name.

Get-ChildItem The*.* |Rename-Item -NewName {$_.name -replace "The ",''}

I need to search all sub folders and find all files AND FOLDERS beginning with "The " for example.

So before:- The Old Man and his dog.mp4

and keep the file in that folder

and rename it too Old Man and His Dog (The).mp4


Solution

  • You could combine the different words that should be removed from the beginning of the filename and put between brackets at the end of the name using something like this:

    # create an array of words that start the file name and should be moved towards the back
    $words = 'The', 'i', 'a'
    
    # create a regex pattern where all possible words are separated by the regex OR (|) sign
    $re = '^({0})[ ,]+' -f ($words -join '|')
    
    Get-ChildItem -Path 'D:\' -File | Where-Object { $_.Name -match $re } | ForEach-Object {
        $newName = '{0} ({1}){2}' -f ($_.BaseName -replace $re), $matches[1], $_.Extension
        $_ | Rename-Item -NewName $newName -WhatIf
    }
    

    Example output

    D:\The Old Man and his dog.mp4   --> D:\Old Man and his dog (The).mp4
    D:\A Nightmare on Elm Street.mp4 --> D:\Nightmare on Elm Street (A).mp4
    D:\I, Robot.mkv                  --> D:\Robot (I).mkv
    

    Remove the -WhatIf switch if the console output looks OK