Search code examples
powershellpowershell-5.0rename-item-cmdlet

How can I renumber lots of files?


Current state

I have a list of files which are numbered. This is an example (there are a lot more files in reality):

01 File.sql
02 File.sql
02 another_file.sql
02 a_third_file.sql
03 File.sql
04 File.sql
.....

Desired outcome

As you can see the files are numbered, but some of the files has the same number. What I want to do is to loop through them all and re-number them to make the list look something like this:

01 File.sql
02 File.sql
03 another_file.sql
04 a_third_file.sql
05 File.sql
06 File.sql
07 File.sql
.....

What I've tried

I have come up with this powershell script that allmost works:

$x = 1
Get-ChildItem "*.sql" | Rename-Item -NewName {$_.Name -replace '[0-9][0-9] ', "$x "}

What this script does is it goes through all the files and removes their current number and replaces it with what I have stored in $x. As of now the only error with my script is that all of the files get's the number 1 since I dont increment it anywhere.

So to the actual question

Where in my script can I increment $x? Or maybe I have to rewrite this as a loop somehow to be able to increment it efter each rename?


Solution

  • I would say a quick and easy way to do this would be :

    $x = 0
    foreach ( $item in $( Get-ChildItem "PATH" "*.txt" ) ){
        $x++
        Rename-Item $item.fullName -newname $( $item.Name -replace '[0-9][0-9] ', "$x " )
    }
    

    This however performs no error checking, so if a file name already exists then it'll error for that item.

    Maybe do two sweeps if you hit any errors? Or throw in an IF ( Test-Path ...) after $x++

    *Edit - Changed $x to 0 so the first rename is 1