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...


Solution 1:

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
}