r/PowerShell • • Jun 07 '18

WSUS management with PowerShell

http://www.happysysadm.com/2018/06/wsus-management-with-powershell.html
161 Upvotes

24 comments sorted by

View all comments

3

u/Beablebeable Jun 07 '18 edited Jun 07 '18

Nice article, thank you.

For fun, here's what I came up with awhile ago to find Patch Tuesday:

function Get-MicrosoftPatchDay
{
	[CmdletBinding()]
	param([Parameter(Mandatory=$False)] [int] $month = -1)
	
	$now = Get-Date
	
	if ($month -eq -1) { $month = $now.Month }
	
	# BUG: this uses the current minute, hour, second to construct the date.
	#        keep that in mind for comparison (worse), or set it to a specific time (safer)
	$startofmonth = Get-Date -Year $now.Year -Month $month -Day 1
	$tempdate = $startofmonth
	$tuesdays = 0
	
	if ($tempdate.DayOfWeek -eq "Tuesday") {$tuesdays++}
	
	while ($tuesdays -lt 2)
	{
		$tempdate = $tempdate.AddDays(1)
		if ($tempdate.DayofWeek -eq "Tuesday") { $tuesdays++ }
	}
	
	$tempdate
} 

4

u/Beablebeable Jun 07 '18

Rewrote this because it was bothering me that the tuesday thing was hardcoded:

# This helper function will find the $nth $day of a certain month.
#  For instance, the second Tuesday for Microsoft Patch Day
# If no month or year are passed in, we use the current month and/or year
#  Return $null if there is no valid answer (for example the 8th Tuesday will not be in the current month)
function Get-NthDayOfMonth
{
	[CmdletBinding()]
	param(
		[Parameter(Mandatory=$True)]  [string] $dayname,                # The Day of Week we will be counting (ex: Monday)
		[Parameter(Mandatory=$True)]  [int] $nthday,                    # The nth $dayname (ex: 2 means second $dayname)
		[Parameter(Mandatory=$False)] [int] $month = (Get-Date).Month,  # The month we will be using for our constructed date
        [Parameter(Mandatory=$False)] [int] $year = (Get-Date).Year     # The year we will be using for our constructed date
		)
		
	# TODO: validate $dayname as a valid dayname
	
	$numfound = 0
	$tempdate = $null
	
	# Construct the date object for the month we'll be examining
	try
	{
		$tempdate = Get-Date -Year $year -month $month -Day 1
		
		if ($tempdate.DayOfWeek -eq $dayname) { $numfound++ }
	
		while (($numfound -lt $nthday) -and ($tempdate.month -eq $month))
		{
			$tempdate = $tempdate.AddDays(1)
			if ($tempdate.DayOfWeek -eq $dayname) { $numfound++ }
		}
	}
	catch { Write-Output "Invalid date." }
	
	# Verify that we found the right number (prevent going into next month)
	if ($numfound -ne $nthday) { $tempdate = $null }
	
	$tempdate
}

function Get-MicrosoftPatchDay
{
	[CmdletBinding()]
	param(
		[Parameter(Mandatory=$False)] [int] $month = (Get-Date).Month,
        [Parameter(Mandatory=$False)] [int] $year = (Get-Date).Year
		)
		
	Get-NthDayOfMonth -dayname "Tuesday" -nthday 2 -month $month -year $year
}

function Get-HappysysadmPatchDay
{
	[CmdletBinding()]
	param(
		[Parameter(Mandatory=$False)] [int] $month = (Get-Date).Month,
        [Parameter(Mandatory=$False)] [int] $year = (Get-Date).Year
		)
		
	Get-NthDayOfMonth -dayname "Monday" -nthday 4 -month $month -year $year
}

Get-NthDayOfMonth -dayname "Monday" -nthday 8
Get-NthDayOfMonth -dayname "Wednesday" -nthday 3 -year 1995
Get-NthDayOfMonth -dayname "Tuesday" -nthday 2 -month 4
Get-NthDayOfMonth -dayname "Friday" -nthday 3 -month 9 -year 2012

Get-MicrosoftPatchDay
Get-HappysysadmPatchDay

3

u/clevertwain Jun 07 '18

I guess everyone has their own Get-NthWeekDay.... Heres mine

function Get-NthWeekday {

    [CmdletBinding(
    )]
    [Alias()]
    [OutputType([datetime])]
    Param
    (
        [Parameter(
            HelpMessage = 'The ordinal (1st, 2nd, etc.) of the day you would like to get.'
        )]
        [ValidateSet("1st", "2nd", "3rd", "4th", "5th", "First", "Second", "Third", "Fourth", "Fifth", "Previous", "Next", "Last", "Current", "1", "2", "3", "4", "5")]
        [Alias('OccurrenceNumber', 'Number')]
        [string]
        $Ordinal = 'Current',

        [Parameter(
            HelpMessage = 'The name of the weekday to check for.'
        )]
        [ValidateSet("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday","All")]
        [Alias('Day')]
        [string]
        $WeekDay = (Get-Date).DayOfWeek,

        [Parameter(
            HelpMessage = 'The month to use when finding the particular date.'
        )]
        [ValidateSet("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12")]
        [string]
        $Month,

        [Parameter(
            HelpMessage = 'Combined with the month specified when looking for the requested weekday occurrence.'
        )]
        [ValidateRange(0, 9999)]
        [int]
        $Year
    )

    Begin {

        $AllDaysInMonth = @()
        $AllOccurrences = @()
        $Return = $null

        if ($WeekDay -eq 'All') {
            $WeekDay = (Get-Date).DayOfWeek
        }

        if ($Ordinal -in ('Previous', 'Next', 'Current') -and ($Month -or $Year)) {
            Write-Warning -Message "Specific months and/or years are ignored when finding the 'Previous', 'Next', or 'Current' WeekDay"
            $Month = (Get-Date).Month
            $Year = (Get-Date).Year
        }

        Switch ($Ordinal) {
            {$_ -eq 1 -or $_ -eq '1st' -or $_ -eq 'First'} {
                Write-Debug "Ordinal is 1 or 1st or First"
                $Ordinal = 'first'
                $OccurrenceNumber = 1
            }
            {$_ -eq 2 -or $_ -eq '2nd' -or $_ -eq 'Second'} {
                Write-Debug "Ordinal is 2 or 2nd or Second"
                $Ordinal = 'second'
                $OccurrenceNumber = 2
            }
            {$_ -eq 3 -or $_ -eq '3rd' -or $_ -eq 'Third'} {
                Write-Debug "Ordinal is 3 or 3rd or Third"
                $Ordinal = 'third'
                $OccurrenceNumber = 3
            }
            {$_ -eq 4 -or $_ -eq '4th' -or $_ -eq 'Fourth'} {
                Write-Debug "Ordinal is 4 or 4th or Four"
                $Ordinal = 'fourth'
                $OccurrenceNumber = 4
            }
            {$_ -eq 5 -or $_ -eq '5th' -or $_ -eq 'Fifth'} {
                Write-Debug "Ordinal is 5 or 5th or Fifth"
                $Ordinal = 'fifth'
                $OccurrenceNumber = 5
            }
            'Last' {
                Write-Debug "Ordinal is Last"
                $OccurrenceNumber = -1
            }
        }

        Switch ($Month) {
            {$_ -eq 1 -or $_ -eq 'January'} {
                $MonthName = 'January'
                $Month = 1
            }
            {$_ -eq 2 -or $_ -eq 'February'} {
                $MonthName = 'February'
                $Month = 2
            }
            {$_ -eq 3 -or $_ -eq 'March'} {
                $MonthName = 'March'
                $Month = 3
            }
            {$_ -eq 4 -or $_ -eq 'April'} {
                $MonthName = 'April'
                $Month = 4
            }
            {$_ -eq 5 -or $_ -eq 'May'} {
                $MonthName = 'May'
                $Month = 5
            }
            {$_ -eq 6 -or $_ -eq 'June'} {
                $MonthName = 'June'
                $Month = 6
            }
            {$_ -eq 7 -or $_ -eq 'July'} {
                $MonthName = 'July'
                $Month = 7
            }
            {$_ -eq 8 -or $_ -eq 'August'} {
                $MonthName = 'August'
                $Month = 8
            }
            {$_ -eq 9 -or $_ -eq 'September'} {
                $MonthName = 'September'
                $Month = 9
            }
            {$_ -eq 10 -or $_ -eq 'October'} {
                $MonthName = 'October'
                $Month = 10
            }
            {$_ -eq 11 -or $_ -eq 'November'} {
                $MonthName = 'November'
                $Month = 11
            }
            {$_ -eq 12 -or $_ -eq 'December'} {
                $MonthName = 'December'
                $Month = 12
            }
            default {
                $MonthName = Get-Date -Format MMMM
                $Month = (Get-Date).Month
            }
        }

        if (!($Year)) {
            $Year = (Get-Date).Year
        }

        Write-Debug "Ordinal was set to $Ordinal"
        Write-Debug "WeekDay was set to $WeekDay"
        Write-Debug "MonthName was set to $MonthName"
        Write-Debug "Month was set to $Month"
        Write-Debug "Year was set to $Year"

        switch ($Ordinal) {
            'Previous' {
                Write-Verbose "Finding Previous $WeekDay"
                $Counter = -8
            }
            'Current' {
                Write-Verbose "Finding $WeekDay"
                $Counter = -1
            }
            'Next' {
                Write-Verbose "Finding the next $WeekDay starting from $((Get-Date).Month)/$((Get-Date).Day)/$((Get-Date).Year)"
                $Counter = 0
            }
            default {
                $Date = Get-Date -Year $Year -Month $Month -Day 1
                While ($Date.Month -eq $Month) {
                    $AllDaysInMonth += [pscustomobject]@{
                        Date      = $Date.Date
                        DayOfWeek = $Date.DayOfWeek
                    }
                    $Date = $Date.AddDays(1)
                }

                $AllOccurrences = $AllDaysInMonth | Where-Object {$_.DayOfWeek -eq $WeekDay}
                Write-Verbose -Message "There are $($AllOccurrences.Count) occurrences of $WeekDay in $MonthName of $Year.  Selecting the $Ordinal one."
            }
        }

        if ($AllOccurrences) {
            Write-Debug "Choosing from $($AllOccurrences.Date)"
            if ($OccurrenceNumber -eq -1) {
                $Return = $AllOccurrences | Select-Object -Last 1
            }
            else {
                $Return = $AllOccurrences | Select-Object -First 1 -Skip ($OccurrenceNumber - 1)
            }
        }
        else {
            While ($Date.DayOfWeek -ne $WeekDay) {
                ++$Counter
                $Date = (Get-Date).AddDays($Counter)
                $Return = [pscustomobject]@{
                    Date      = $Date
                    DayOfWeek = $Date.DayOfWeek
                }
            }
        }
    }
    End {
        if (! $Return) {
            Write-Verbose "There is no $Ordinal $WeekDay in $MonthName, $Year"
        }
        else {
            Get-Date -Date $Return.Date -DisplayHint Date
        }
    }
}

2

u/Beablebeable Jun 07 '18

Nice. Very polished.