Rename and Increment Integer File Names

I have a bunch of files with integers that range from 30.pdf to 133.pdf as filenames. What I am trying to do is increment each filename, so 30.pdf should become 31.pdf, ..., and 133.pdf should become 134.pdf.

Does anybody know how I can achieve this?

I know I can loop through the directory with foreach ($f in dir) or display and even sort the filenames with get-childitem | sort-object, but this latter method obviously has issues sorting numerically.

No idea why something so simple is so difficult to figure out. Cannot find this anywhere online...

2 answers

  • answered 2022-01-23 02:27 Santiago Squarzon

    This should work assuming the BaseName of the files contains only digits as you have shown on your question. First you would need to sort the files descending to avoid collision and after that you can pipe them to Rename-Item using the -NewName script block:

    Get-ChildItem path/to/files -File | Sort-Object { [int]$_.BaseName } -Descending |
    Rename-Item -NewName {
        [int]$n = $_.BaseName; '{0}{1}' -f (++$n), $_.Extension
    }
    

  • answered 2022-01-23 02:34 John Glenn

    We can take some shortcuts to make this easier since your file names are literally just integers. Start by using this statement to get a collection of integers that represents your files ($files is the output of Get-ChildItems from the parent directory):

    $integersFromNames = $files | Select -ExpandProperty BaseName | foreach { $_ -as [int] } | sort ‐Descending
    

    Now you have all of the existing files sorted from largest to smallest. You can use Rename-Item in a foreach loop to get you the rest of the way:

    foreach ($oldNumber in $integersFromNames) {
        $newNumber = $oldNumber + 1
        Rename-Item -Path "$oldNumber.pdf" -NewName "$newNumber.pdf"
    }
    

    Please excuse any typos. I'm on my phone. Hopefully the concept comes across clearly.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum