Search code examples
powershellrename-item-cmdlet

Rename-Item : add unique numeric sequence to prevent duplicate file names


I need a way to rename files in a directory that would result in an error with a simple Rename-Item. The files need the same 10 digit code followed by 4 digit place holder (numbers only please).

Current file names:

01_img_0028.JPG
01_img_0029.JPG
02_img_0028.JPG
02_img_0029.JPG

Considering the files above, renaming the files with a split (using the 4 digit in the original name) would fail because there will be files with the same name:

B0000000000.0028.JPG
B0000000000.0029.JPG
B0000000000.0028.JPG
B0000000000.0029.JPG

Does anyone have an idea to get around this? The 4 digits can be any sequence of numbers but it would be great if we could make the end result look like:

B0000000000.0001.JPG
B0000000000.0002.JPG
B0000000000.0003.JPG
B0000000000.0004.JPG

Here is my current code that will rename all unique files and the first of duplicates, but error out on files that would then be duplicate names:

$jpgToRename = GCI -Path $pathToRename -Filter '*.jpg' -R
foreach ($jpg in $jpgToRename) {
    $splitPath = $jpg.FullName.Split("\\")
    $newName = -join ($splitPath[7], ".", $jpg.BaseName, ".PC_850.jpg")
    Rename-Item $jpg.FullName -NewName $newName
}

Solution

  • Using a counter here would keep this simple for your need:

    $jpgToRename = GCI -Path $pathToRename -Filter '*.jpg' -R
    $counter = 1
    foreach($jpg in $jpgToRename){
        $splitPath = $jpg.FullName.Split("\\")
        $formattedCounter = $counter.ToString("0000")
        $newName =  -Join($splitPath[7], ".",$formattedCounter, $jpg.BaseName, ".PC_850.jpg")
        Rename-Item $jpg.FullName -NewName $newName
        $counter++
    }