PowerShell: Batch Renumber Files
The task: files are numbered 01–50 and you need to insert a new file at position 15, so files 15–50 must become 16–51. Here's a PowerShell script that does the shift correctly, and the three traps that break naive versions.
The script
# Shift every file whose name starts with a number >= 15 up by one.
# Run from the folder containing the files.
$from = 15 # first number to shift
Get-ChildItem -File |
Where-Object { $_.Name -match '^(\d+)' -and [int]$Matches[1] -ge $from } |
Sort-Object { [int][regex]::Match($_.Name, '^\d+').Value } -Descending |
ForEach-Object {
$numText = [regex]::Match($_.Name, '^\d+').Value
$newNum = ([int]$numText + 1).ToString("D$($numText.Length)")
$newName = $_.Name -replace '^\d+', $newNum
Rename-Item -LiteralPath $_.FullName -NewName $newName
}To preview the renames without executing them, add -WhatIf to the Rename-Item line, run it once, and read the output. Remove it when you're satisfied.
The three traps it avoids
- Rename collisions. Processing in ascending order renames 15 → 16 while a real file 16 still exists.
Sort-Object … -Descendingrenames from the top down (50 → 51 first), so a target name is always free. - Lost zero-padding.
09 + 1naively becomes10, but099must become100and05must become06, not6. The script measures each filename's own digit count and re-pads withToString("D<width>"). - Unnumbered files. The
Where-Objectfilter skips anything that doesn't start with digits, so a straynotes.txtin the folder is untouched.
What the script can't see
It assumes the number is at the start of the filename and that your set is consistent. Mixed conventions — 1. Contract.pdf next to 01_Contract.pdf, or an "Exhibit 15" prefix — need the regex adjusted, and duplicate numbers in the source folder will silently produce wrong results.
If you'd rather not maintain the script, Renumber Files does the same job from a pasted file list: it auto-detects the numbering style, warns about duplicates, previews every rename, and handles multiple insertion points in one pass — locally in your browser, on Windows and macOS.
Same result, no regex
Paste up to 10 filenames and try it free — no sign-in required.