Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading