Skip to content

Instantly share code, notes, and snippets.

@TomasBouda
Last active March 16, 2020 15:50
Show Gist options
  • Save TomasBouda/7a60c0f273d82c05321e51c7999b708c to your computer and use it in GitHub Desktop.
Save TomasBouda/7a60c0f273d82c05321e51c7999b708c to your computer and use it in GitHub Desktop.
Returns n-th workday in given month(skipping weekends and us holidays).
function Get-WorkDay {
param(
[Parameter(Mandatory = $true)]
[int]$Day,
[Parameter(Mandatory = $false)]
[ValidateRange(1, 31)]
[int]$Month = (Get-Date).Month,
[Parameter(Mandatory = $false)]
[int]$Year = (Get-Date).Year,
[Parameter(Mandatory = $false, DontShow)]
[int]$Index = 1
)
begin {
$USHolidays = @(
"01/01", # New Year's Day
"01/20", # Martin Luther King Jr. Day
"02/17", # Presidents' Day
"05/25", # Memorial Day
"06/03", # Independence Day observed
"06/04", # Independence Day
"09/07", # Labor Day
"10/12", # Columbus Day
"11/11", # Veterans Day
"11/26", # Thanksgiving Day
"12/25" # Christmas Day
)
$holidays = @($USHolidays |
ForEach-Object { [DateTime]::ParseExact("$_/$($Year)", 'MM/dd/yyyy', [System.Globalization.CultureInfo]::InvariantCulture) } |
Where-Object { $_.Month -eq $Month })
}
process {
# Handle month owerflow
if ($Index -gt [DateTime]::DaysInMonth($Year, $Month)) {
if ($Month -eq 12) {
$Month = 1
$Year++
}
else {
$Month++
}
$Day = $Day - $Index + 1
$Index = 1
}
$date = Get-Date -Year $Year -Month $Month -Day $Index
if ($date.DayOfWeek -eq 'Saturday') {
return Get-WorkDay -Day ($Day + 2) -Year $Year -Month $Month -Index ($Index + 2)
}
elseif ($date.DayOfWeek -eq 'Sunday') {
return Get-WorkDay -Day (++$Day) -Year $Year -Month $Month -Index (++$Index)
}
elseif ($holidays.Length -gt 0 -and ($holidays | Where-Object { $_.Day -eq $date.Day }).Length -gt 0) {
return Get-WorkDay -Day (++$Day) -Year $Year -Month $Month -Index (++$Index)
}
elseif ($Index -lt $Day) {
return Get-WorkDay -Day $Day -Year $Year -Month $Month -Index (++$Index)
}
else {
$date
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment