Get WeekDayInMonth - ps1

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 1

Function Get-WeekDayInMonth ([int]$Month, [int]$year, [int]$WeekNumber, [int]$Wee

kDay)
{
$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
}
Get-WeekDayInMonth month 5 year 2014 Weeknumber 2 Weekday 5
$FirstDayOfMonth = Get-Date #-Year 2014 -Month 5 -Day 1 -Hour 0 -Minute 0 -Secon
d 0
[int]$FirstDayofMonthDay = $FirstDayOfMonth.DayOfWeek
$Difference = 5 - $FirstDayofMonthDay
$DaysToAdd = $Difference
$FirstWeekDayofMonth = $FirstDayOfMonth.AddDays($DaysToAdd)
$FirstWeekDayofMonth


if ((get-date).DayOfWeek -eq "Monday" ) { $w = (Get-Date).addDays(-3) } else {$w
= (Get-Date).addDays(-1) }
$w

You might also like