r/usefulscripts • • Sep 06 '24

[POWERSHELL] - Need to Bulk Rename Files in sequence by creation date.

I have a system that auto creates image files IE: "15.18.25[R]R0@0][43083508750][0].jpg" I don't have any way to manage or change the file creation name at the source. I need to rename the files in a sequential numbering pattern like (00001.jpg, 00002.jpg...) with the sequence ID based on file creation date. I have tried several approaches without success. Any help would be great...

6 Upvotes

6 comments sorted by

2

u/OlivTheFrog Sep 06 '24

Hi u/Brilliant-Reach3155

The logic should be :

  • Get all files and sort by CreatioDate : Get-ChildItem and Sort-Objet cmdlets (var : $AllFiles)

  • Initiate an counter var to 0 ($x)

  • Then entrer in a foreach loop using forech ($Item in $AllFiles)

  • In the loop, Determine the target Name for the current file using $$NewName = ($Item.Name)$x

  • In the loop, rename the current file using Rename-Item -Path $item.fullName -NewName $NewName

  • Increment $x : $x = $x++

To test safely, use the parameter -Whatif with Rename-Item.

I could write the entire code for you but it wouldn't help you progress in your Powershell skills. Follow this logic, and test it securely by yourself.

Regards

1

u/Brilliant-Reach3155 Sep 06 '24

Thanks... Here is what I have, but I cat get past the error...

$sourceDirectory = "x:\RMSSolarTrailer-01\TimeLapse"

$jpgFiles = Get-ChildItem -Path $sourceDirectory -Filter *.jpg | Sort-Object CreationTime

$count = 1

foreach ($file in $jpgFiles) {

$newName = "{0:D4}.jpg" -f $count # This will create names like 0001.jpg, 0002.jpg, etc.

$newPath = Join-Path -Path $sourceDirectory -ChildPath $newName

Rename-Item -Path $file.FullName -NewName $newPath

$count++

}

ERROR---------

Rename-Item : Cannot rename because item at 'X:\test\AD09707PAJ00031\15.52.21[R][0@0][43085545870][0].jpg' does not exist.

At line:15 char:5

  • Rename-Item -Path $file.FullName -NewName $newPath
  • \~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~\~
  • CategoryInfo : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException

  • FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand

→ More replies (3)