Search code examples
powershellget-childitem

Reset Filenumber for new folder in Recurse Filerename Powershell


I am working on a powershell batch file.

I want to rename all the files in a certain amount of folders. I need to rename it to a certain part of the folder name followed by an incremental number. So far i managed to create a rename command in powershell that also add numbers to the files.

Get-ChildItem -recurse -filter "*.jpg" | %{$x=1} {Rename-Item $_.FullName -NewName ('{0}-{1}.jpg' -f ($_.FullName.substring(18,8) -replace("-","")) ,$x++)}

This works well how ever i want to reset the number back to 1 for each separate folder. At the moment i keep numbering up trough different folders. How do i reset $x back to 1 when i change folder?


Solution

  • As you can't be sure that each directory is enumerated at ones, I would create a hashtable to keep track of the index. Something like:

    $Directories = @{}
    Get-ChildItem -recurse -filter "*.jpg" | ForEach {
        Rename-Item $_.FullName -NewName ('{0}-{1}.jpg' -f ($_.FullName.substring(18,8) -replace("-","")) ,++$Directories[$_.DirectoryName])
    }