Advertisement
Tosiaki

Rename numbered files to remove gaps

Apr 26th, 2022
1,263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. $ToNatural = { [regex]::Replace($_, '\d+', { $args[0].Value.PadLeft(20) }) }
  2. Get-ChildItem ./ | Sort-Object $ToNatural |
  3. Foreach-Object { $lastFileName = '0' } {
  4.         $fileName = [System.IO.Path]::GetFileNameWithoutExtension($_)
  5.         $expectedName = [string]([int]$lastFileName + 1)
  6.         if ($expectedName -ne $fileName) {
  7.                 Rename-Item -Path $_ -NewName ($expectedName + [System.IO.Path]::GetExtension($_))
  8.         }
  9.         $lastFileName = $expectedName
  10. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement