Punkrock760
Punkrock760

Reputation: 51

PowerShell Script Bulk Rename Files with Date and Month

Does anyone know how I can change the below PowerShell script to also include month and year:

Get-ChildItem *.mp4 | Rename-Item -newname {“SONYA7 - “ + $_.LastWriteTime.toString("yyyy-MM-dd - HH-mm-ss") + ".mp4"}

For example the above script will produce:

SONYA7 - 2020-05-01 - 15-50-35.mp4

But I need it to produce:

SONYA7 - 2020-05-01 (May 2020).mp4

It's probably a really a simple fix but I've tried a few different methods but all I get is error messages. Would really appreciate your help.

Upvotes: 0

Views: 1132

Answers (1)

Theo
Theo

Reputation: 61068

Continuing from my comments

If you want the file named SONYA7 - 2020-05-01 (May 2020).mp4, then use $_.LastWriteTime.toString("yyyy-MM-dd (MMM yyyy)").

However, as you have noticed, this will lead to name collisions, where files modified on the same day will get equal filenames. To overcome that, you need to keep the file Time part aswell.

Perhaps a format of "yyyy-MM-dd (MMM yyyy HH-mm-ss)" would be a better choice, although it does create long filenames..

Then, there is a gotcha to consider here too:
When using code like Get-ChildItem *.mp4 | Rename-Item ..., the Get-ChildItem cmdlet will pick up files that have already been renamed aswell, performing the operation multiple times.

To stop it from iterating already renamed files, either

  • capture the collection of files from Get-ChildItem first in a variable and loop through that OR
  • surround the Get-ChildItem part with brackets so it will finish complete before sending the items through the pipe
(Get-ChildItem -Filter '*.mp4' -File) | 
 Rename-Item -NewName { 'SONYA7 - {0:yyyy-MM-dd (MMM yyyy HH-mm-ss)}.mp4' -f $_.LastWriteTime }

Upvotes: 1

Related Questions