Search code examples
powershellrecursionbatch-rename

Windows 10, Rename all *.jpg files in all subdirectories, with number starting from 1


I want a solution for the same problem, but in Windows 10. Recursively rename .jpg files in all subdirectories

I tried with following powershell command, Get-ChildItem -Recurse -Include *.jpg | % { Rename-Item $_ -NewName ('{0:D1}.jpg' -f $i++)}

but it renames the files in sequential order without resetting the index to 1 in every sub folder.


Solution

  • I think you need two separate Get-ChildItem cmdlets for this. The first will gather all subdirectories and when looping though that, the second will gather the files in each directory:

    Get-ChildItem -Path 'X:\RootFolder\where\the\files\are' -Recurse -Directory | ForEach-Object {
        $count = 1   # reset the counter for this subdir to 1
        Get-ChildItem -Path $_.FullName -Filter '*.jpg' -File | ForEach-Object {
            $_ | Rename-Item -NewName ('{0:D1}.jpg' -f $count++) -WhatIf
        }
    }
    

    Remove the -WhatIf if you are satisfied with the results shown in the console.

    P.S. the title says *.png, but your code deals with *.jpg. Doesn't matter, as long as you set your filter to the correct extension and adjust the new name in the code accordingly