Search code examples
windowspowershellrecursionfile-rename

Recursively Rename Files In All Subfolders Sequentially


I have a series of folders and subfolders, structured in this way:

  • 001/Fabric/Blue/ (.jpg files, sequentially named)
  • 001/Fabric/Green/ (.jpg files, sequentially named)
  • 002/Fabric/Blue/ (.jpg files, sequentially named)
  • 002/Fabric/Green/ (.jpg files, sequentially named)
  • etc.

The file names have excess string characters that I would like to remove, and I would like to convert their file names into an easier sequential format (0.jpg, 1.jpg, etc.).

I tried working with a few different PowerShell examples to get this to work. I have the recursive searching functionality working, however I receive an error about an InvalidOperationException when trying to rename the files in the ForEach-Object loop. Additionally, I am afraid my sequential numbering is not being 'reset' for each of the folders where it renames files.

$i = 0
Get-ChildItem -Filter "*.jpg" -Recurse | ForEach-Object {
    Rename-Item $_ -NewName ('$i.jpg' -f $i++)
}

So, two questions:

  1. How can I fix the error with Rename-Item?
  2. How can I ensure my variable is reset for each subfolder the script starts renaming files in?

Solution

  • If you take a two step approach, first getting all the folders containing jpg's and then iterating through this list, you have no problem beginning with 1. But I'd always use leading zeroes for such a renumbering.

    $BaseFld = "Q:\Test\"
    $Ext = "*.jpg"
    $jpgFolders = gci $($BaseFld+$Ext) -Recurse | 
       Select -ExpandProperty Directory -Unique |
       select -ExpandProperty Fullname | Sort
    
    ForEach ($Folder in $jpgFolders) {
      Set-location $Folder
      $i = 1
      Get-ChildItem $Ext | %{Ren $_ -NewName ('{0:D4}.jpg' -f $i++) -whatif}
    }
    

    If the ouptut suits you, remove the -whatif in the second last line