PowerShell Find Date of a previous day in any week


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
002

003
004
005
006
007
008
009
010
011
012

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

Advertisements
  1. #1 by xxx on September 18, 2011 - 10:15

    Thanks.. Awesome

  2. #2 by arnold on November 21, 2011 - 09:46

    Thanks Sir !

  3. #4 by Herschelle42 on September 9, 2012 - 17:30

    Thank you. I needed Sunday and your example gave me the answer.

  4. #6 by Aleksandr on May 10, 2014 - 15:10

    Thank you. I needed a date for Monday of current week! it really works 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: