Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function Get-NthDayOfWeekInMonth
- {
- <#
- .SYNOPSIS
- Short description
- .DESCRIPTION
- L-o-n-g
- d-e-s-c-r-i-p-t-i-o-n
- .PARAMETER NthDayNumber
- Which day instance you want. There are usually 4 of any given day, but sometimes there are 5.
- The default is 2.
- .PARAMETER DayOfWeek
- The day of the week to seek. This can be a day name OR a [System.DayOfWeek] object OR a number in 0..6 inclusive.
- The default is Tuesday.
- .PARAMETER MonthNumber
- The number of the month to work on.
- The default is the current month.
- .PARAMETER YearNumber
- The year number to work on.
- The default is the current year.
- .EXAMPLE
- Get-NthDayOfWeekInMonth
- Gets the 2nd Tuesday of the current month of the current year.
- .EXAMPLE
- Get-NthDayOfWeekInMonth -NthDayNumber 3 -DayOfWeek Monday
- Gets the 3rd Monday of the current year & month.
- .INPUTS
- Accepts [int32] for the *Number items, and a day name OR [DayOfWeek] enum value.
- .OUTPUTS
- Sends out a [DateTime] object.
- .NOTES
- Source = the ISE snippets
- Version = 0.0.0.1
- #>
- [CmdletBinding ()]
- [Alias()]
- [OutputType([DateTime])]
- Param (
- # NthDayNumber help description goes here
- [Parameter (
- Position = 0,
- ValueFromPipeline,
- ValueFromPipelineByPropertyName
- )]
- [ValidateRange (1,5)]
- [int]
- $NthDayNumber = 2,
- # DayOfWeek help description goes here
- [Parameter (
- Position = 1,
- ValueFromPipelineByPropertyName
- )]
- [System.DayOfWeek]
- $DayOfWeek = [System.DayOfWeek]::Tuesday,
- # MonthNumber help description goes here
- [Parameter (
- Position = 2,
- ValueFromPipelineByPropertyName
- )]
- [ValidateRange (1,12)]
- [int]
- $MonthNumber = (Get-Date).Month,
- # YearNumber help description goes here
- [Parameter (
- Position = 3,
- ValueFromPipelineByPropertyName
- )]
- [ValidateRange (1950, 2199)]
- [int]
- $YearNumber = (Get-Date).Year
- )
- begin {}
- process
- {
- $FirstDayOfMonth = Get-Date -Year $YearNumber -Month $MonthNumber -Day 1
- # i have no idea what the logic behind the ofset number is
- # i just fiddled with it until it came out right [*grin*]
- $Offset = (($DayOfWeek.value__ - $FirstDayOfMonth.DayOfWeek.value__ + 7) % 7) + (7 * ($NthDayNumber - 1))
- $TargetWeekDay = $FirstDayOfMonth.Date.AddDays($Offset)
- # correct for "5th weekday overflow"
- if ($TargetWeekDay.Month -ne $MonthNumber)
- {
- $TargetWeekDay = $TargetWeekDay.AddDays(-7)
- }
- $TargetWeekDay
- }
- end {}
- }
Add Comment
Please, Sign In to add comment