I often need to name a file with a date as part of the file name like:
ServerInventory12-18-2009.csv
A simple $date = $(get-date).ToString(“MM-dd-yyyy”) works great for today, but I recently had a need to create a file once a week, with a file name of the previous Saturday.
I had come across Arul Kumaravel’s WebLog post “How Can I Determine the Beginning and Ending Date of the Previous Month?” (http://blogs.msdn.com/arulk/archive/2006/11/22/how-can-i-determine-the-beginning-and-ending-date-of-the-previous-month.aspx) when I was trying to find the first and last days of a month for a SQL query, and so I grabbed that bit of code and created this:
001
002 003 |
([System.Datetime] $date = $(get-date))
$NumDaysSinceSaturday = $date.DayOfWeek.value__ + 1 $PreviousSaturday = ` $date.AddDays(– $NumDaysSinceSaturday).ToString(“MM-dd-yyyy”) |
That worked great, but it’s good only for the previous Saturday. I could envision needing to get the previous Monday, or Friday, or even a day several weeks prior.
This function will do that:
001 003 013 014 015 |
Function GetPreviousDate
{ param([STRING]$WeekDay = ` $(Throw ‘WeekDay is required’), [Int]$NumberOfWeeks = 0) $DayNumber = @{ “Saturday” = 1; “Sunday” = 0; “Monday” = -1; “Tuesday” = -2; “Wednesday” = -3; “Thursday” = -4 “Friday” = -5} ([System.Datetime] $Today = $(get-date)) |Out-Null $NumDaysSincePreviousDate = ` $Today.DayOfWeek.value__ + $DayNumber[$WeekDay] ([System.Datetime] $PreviousDateThisWeek ` = $Today.AddDays(– $NumDaysSincePreviousDate)) |Out-Null $PreviousDate =` $PreviousDateThisWeek.AddDays(–($NumberOfWeeks *7)).ToString(“MM-dd-yyyy”) } |
Usage
. GetPreviousDate Friday 1
$PreviousDate Would show 12-11-2009 if I ran it the week of December 18th, 2009
. GetPreviousDate Friday
$PreviousDate Would show 12-18-2009 if I ran it the week of December 18th, 2009
. GetPreviousDate Wednesday 35
$PreviousDate Would show 04-15-2009 if I ran it the week of December 18th, 2009
#1 by xxx on September 18, 2011 - 10:15
Thanks.. Awesome
#2 by arnold on November 21, 2011 - 09:46
Thanks Sir !
#3 by Karl Mitschke on November 21, 2011 - 10:57
You are welcome.
#4 by Herschelle42 on September 9, 2012 - 17:30
Thank you. I needed Sunday and your example gave me the answer.
#5 by Karl Mitschke on December 4, 2012 - 08:15
Glad you found this helpful.
#6 by Aleksandr on May 10, 2014 - 15:10
Thank you. I needed a date for Monday of current week! it really works 🙂
#7 by Karl Mitschke on January 5, 2015 - 15:54
You are welcome.
Glad I could help.
Karl
#8 by ludwig on August 24, 2022 - 09:11
Not Working for me..
Wednesday 24.08.2022: . GetPreviousDate Thursday 0
gives me as $PreviousDate the date of tomorrow: 08-25-2022
#9 by Karl Mitschke on August 24, 2022 - 09:24
Hello,
Thanks for pointing that out.
If you’re looking for last Thursday you’d use:
. GetPreviousDate thursday 1
Or better, change [Int]$NumberOfWeeks = 0 to [Int]$NumberOfWeeks = 1 in the param section.