Skip to content

Instantly share code, notes, and snippets.

@FooBartn
Created August 19, 2016 23:37
Show Gist options
  • Select an option

  • Save FooBartn/59408685f2f0543156b2f8fd087dbe50 to your computer and use it in GitHub Desktop.

Select an option

Save FooBartn/59408685f2f0543156b2f8fd087dbe50 to your computer and use it in GitHub Desktop.
<#
Author: Joshua Barton
Version: 1.0
Version History:
Purpose: Get last expected reboot time for a server that reboots on Nth Xday of the Month
#>
function Get-MonthlyReboot () {
param(
[ValidateSet(1,2,3,4,'Last')]
$Nth,
[ValidateSet('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday')]
[string]
$Day,
[ValidatePattern('[0-9]:[0-9][0-9]$')]
[string]
$Time
)
$CurrentDate = Get-Date
# Check for last Xday of the month. Step backwards until found.
if ($Nth -eq 'Last') {
$DaysInMonth = [DateTime]::DaysInMonth($CurrentDate.Year, $CurrentDate.Month)
$LastDayOfMonth = Get-Date -Day $DaysInMonth -Date $Time
do {
$DateFound = $LastDayOfMonth
# Find First Iteration of Day
while ($DateFound.DayOfWeek -ne $Day) {
$DateFound = $DateFound.AddDays(-1)
}
# Set back a month in case $DateFound -gt $CurrentDate
$LastDayOfMonth = $LastDayOfMonth.AddMonths(-1)
} until ($DateFound -le $CurrentDate)
# Check for Nth Xday of the month. Step forward until found.
} else {
$FirstDayOfMonth = Get-Date -Day 1 -Date $Time
$WeekNum = 1
do {
$DateFound = $FirstDayOfMonth
# Find First Iteration of Day
while ($DateFound.DayOfWeek -ne $Day) {
$DateFound = $DateFound.AddDays(1)
}
# Find Expected Iteration of Day
while ($WeekNum -ne $Nth) {
$DateFound = $DateFound.AddDays(7)
$WeekNum++
}
# Set back a month in case $ExpectedDate -gt $CurrentDate
$FirstDayOfMonth = $FirstDayOfMonth.AddMonths(-1)
$WeekNum = 1
} until ($DateFound -le $CurrentDate)
}
$DateFound
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment