PowerShell Function: Get-WeekDayInMonth

Often, IT admins need to workout the first/second/third/fourth Mon/Tue/Wed/Thur/Fri/Sat/Sun of any given month. some good examples are:

  • Prepare themselves for Microsoft’s patching Tuesday of each month
  • Planning for any admin tasks caused by Day Light Saving time change

So I wrote this simple function today to calculate the date for any given month & year.

Here’s the function:

Function Get-WeekDayInMonth ([int]$Month, [int]$year, [int]$WeekNumber, [int]$WeekDay)
{

$FirstDayOfMonth = Get-Date -Year $year -Month $Month -Day 1 -Hour 0 -Minute 0 -Second 0
#First week day of the month (i.e. first monday of the month)
[int]$FirstDayofMonthDay = $FirstDayOfMonth.DayOfWeek
$Difference = $WeekDay - $FirstDayofMonthDay
If ($Difference -lt 0)
{
$DaysToAdd = 7 - ($FirstDayofMonthDay - $WeekDay)
} elseif ($difference -eq 0 )
{
$DaysToAdd = 0
}else {
$DaysToAdd = $Difference
}
$FirstWeekDayofMonth = $FirstDayOfMonth.AddDays($DaysToAdd)
Remove-Variable DaysToAdd
#Add Weeks
$DaysToAdd = ($WeekNumber -1)*7
$TheDay = $FirstWeekDayofMonth.AddDays($DaysToAdd)
If (!($TheDay.Month -eq $Month -and $TheDay.Year -eq $Year))
{
$TheDay = $null
}
$TheDay
}

the $weekday variable represents the week day you after:

0 Sunday
1 Monday
2 Tuesday
3 Wednesday
4 Thursday
5 Friday
6 Saturday
Usage:
Example #1: to query the 2nd Tuesday of October 2012:
Get-WeekDayInMonth –month 10 –year 2012 –Weeknumber 2 –Weeday 2
OR
Get-WeekDayInMonth 10 2012 2 2
image
Example #2: to query the 1st Sunday of May 2013:
Get-WeekDayInMonth –month 5 –year 2013 –Weeknumber 1 –Weeday 0
OR
Get-WeekDayInMonth 5 2013 1 0

image

2 comments

  1. Thanks for the nice functions.
    I have made some small changes to the functions. We (in the Netherlands) use
    monday as the first day of the week, so Sunday is numbered as 7.

    adapted function:
    Function Get-WeekDayInMonth {
    ## .Synopsis Date of n-week in Month on WeekDay
    [CmdletBinding()]
    Param([int]$Month,
    [int]$year,
    [int]$WeekNumber,
    [int]$Weekday
    )

    $FirstDayOfMonth = Get-Date -Year $year -Month $Month -Day 1 -Hour 0 -Minute 0 -Second 0
    #First week day of the month (i.e. first monday of the month)
    [int]$FirstDayofMonthDay = @(7,1,2,3,4,5,6)[$FirstDayOfMonth.DayOfWeek]
    $DaysToAdd = –$WeekNumber * 7 + $weekday – $FirstDayofMonthDay
    $TheDay = $FirstDayOfMonth.AddDays($DaysToAdd)
    #If (!($TheDay.Month -eq $Month -and $TheDay.Year -eq $Year)) { $TheDay = $null }
    $TheDay
    }

    As you see I commented the line for a to high chosen weeknumber: now we get the date
    of n-weeks and weekday from the first of Month

  2. you have error here “$DaysToAdd = –$WeekNumber * 7 + $weekday – $FirstDayofMonthDay”, the right code is “$DaysToAdd = $WeekNumber * 7 + $weekday – $FirstDayofMonthDay”, without “-” before $WeekNumber

Leave a Reply

%d bloggers like this: