I'm currently writing a PowerShell script for backup tapes and trying to calculate return dates of the tapes. Tapes are picked up and returned by our provider on Fridays. Retention periods are 4 weeks, 12 months and 3 years. Monthly tapesets fall on the first Monday of the month so I'm currently working with a monthly tapeset, which will return 12 months from now. How would I calculate 12 months from Friday 10/08/2021, but make sure the return date is also a Friday?
#Calculate Friday - Vaulting Date
$Friday = (Get-Date).AddDays(5-((Get-Date).DayOfWeek.value__)).ToString("MM/dd/yyyy")
#Calculate Return Dates
$Weekly = (Get-Date).AddDays(5-((Get-Date).DayOfWeek.value__)).AddDays(28).ToString("MM/dd/yyyy")
$Monthly = (Get-Date).AddDays(5-((Get-Date).DayOfWeek.value__)).AddMonths(12).ToString("MM/dd/yyyy")
$Yearly = (Get-Date).AddDays(5-((Get-Date).DayOfWeek.value__)).AddYears(3).ToString("MM/dd/yyyy")
$Monthly currently returns 10/08/2022 which is the Saturday after the date I want. I presume I'd run into the same problem with $Yearly as well, and what if it's a leap year? Any assistance would greatly be appreciated.
CodePudding user response:
First add one year:
$date = Get-Date 10/08/2021
$date = $date.AddYears(1)
Then keep adding one day at a time until you reach a Friday:
while($date.DayOfWeek -ne 'Friday'){
$date = $date.AddDays(1)
}
Finally, convert to the desired string format (don't convert to a string until you're done calculating your date, you won't be able to do datetime math with it :) ):
$date.ToString('MM/dd/yyyy')