0

I have a PowerShell script which allows me to rename a bunch of files within a folder.

How do I adjust the script to include the week number starting from a specific date?

For example, I don't want week 1 to being from January 1st. I want it to start on April 1st.

From:

  • C001.mp4
  • C002.mp4
  • C003.mp4

To:

  • SONYA7 - 2020-04-01 - 17-33-32 - WK1.mp4
  • SONYA7 - 2020-04-09 - 13-48-20 - WK2.mp4
  • SONYA7 - 2020-04-09 - 13-51-46 - WK2.mp4

Here is my current script:

Get-ChildItem *.mp4 | Rename-Item -newname {“SONYA7 - “ + $_.LastWriteTime.toString("yyyy-MM-dd - HH-mm-ss") + ".mp4"}
Punkrock760
  • 51
  • 1
  • 1
  • 7
  • 1
    Does this answer your question? [Calculate date from week number](https://stackoverflow.com/questions/662379/calculate-date-from-week-number) Here's [PowerShell version](https://social.technet.microsoft.com/Forums/en-US/f65c80b0-f74f-4234-870c-c5ffe8d9b1ea/powershell-get-date-from-week-number-of-year?forum=ITCG). – JosefZ Jun 12 '20 at 20:50

2 Answers2

0

Use this "get-date -UFormat %V" and concatenate with your code.

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

  • 2
    that gives the week-of-year number with the `V` offset instead of the `W` offset. the OP wants to be able to define a different starting point - not "from start of year". so i don't think your solution quite works. you likely need to get the number you generated and subtract that from the one for the desired start date [or the other way around]. [*grin*] – Lee_Dailey Jun 12 '20 at 21:23
0

Since you want to set your own starting point for Week 1 (April first), you need to calculate the weeknumber from that.

This should do what you want:

Get-ChildItem -Path 'D:\Test' -Filter '*.mp4' -File | Rename-Item -NewName {
    $week1 = Get-Date -Year $_.LastWriteTime.Year -Month 4 -Day 1
    if ($_.LastWriteTime.Month -lt 4) { $week1 = $week1.AddYears(-1) }
    $weekNumber = [math]::floor(($_.LastWriteTime - $week1).Days / 7) + 1
    # combine it all to form the new filename
    'SONYA7 - {0:yyyy-MM-dd - HH-mm-ss} - WK{1}{2}' -f $_.LastWriteTime, $weekNumber, $_.Extension
} -WhatIf

The -WhatIf switch at the end makes the code only display what would be changed without actually renaming the files. If you are satisfied with that info, remove the -WhatIf switch

Theo
  • 57,719
  • 8
  • 24
  • 41