Search code examples
powershellcmdcommand-prompt

Batch renaming files by PowerShell?


How can I rename files in a folder that have random names and random extensions to a sequence like the example below: 0001.pdf 0002.pdf ..... 0100.png and continue.

And if possible then generate a .txt file with the names and extensions generated.

For the .txt file if not possible Powershel could be another application.

Searching I got the code below, but I can't fix it for the task I need.

Dir | Rename-Item –NewName { $_.name –replace " - ","0" }


Solution

  • Wrap the call to Rename-Item in ForEach-Object then maintain a counter in a variable:

    $fileNumber = 1
    Get-ChildItem path\to\folder\containing\random\files -File |ForEach-Object {
        # Construct new file name
        $newName = '{0:0000}{1}' -f $fileNumber,$_.Extension
    
        # Perform rename
        $_ |Rename-Item -NewName $newName
    
        # Increment number
        $fileNumber++
    }