Patch Tuesday with PowerShell

Determine Patch Tuesday Date with PowerShell

A PowerShell function to determine Patch Tuesday based on the many examples you find on the internet but changed to support the month and year parameters you can supply the -Verbose parameter for Verbose output however in this specific function that output is quite limited.

I use this function combined with others to define the moments that Windows Updates are allowed to be installed on the managed server environment. The update moments are all based on a fixed cycle of x days after patch Tuesday for Pilot and xx days for Production servers.

NOTE: By including the SYNOPSIS and other information you can use get-help on the function to find out what parameters you can specify or read what this function actually can be used for. I can highly recommended to always include this information in your PowerShell function(s) so that anybody can understand it.

Examples:
Get-PatchTuesday No Parameters Example
Get-PatchTuesday Parameter(s) Example
Get-PatchTuesday Pipeline Example
Get-PatchTuesday Verbose Example

Code:

Function Get-PatchTuesday
{
  <#
    .SYNOPSIS
    Returns the patch Tuesday date for current month and year or based on supplied parameters.

    .EXAMPLE
    Get-PatchTuesday -Month 1 -Year 2018  
    .EXAMPLE
    Get-PatchTuesday -Month 9
    
   .PARAMETER Month
    The month parameter can be used to specify a specific month.
    .PARAMETER Year
    The year parameter can be used to specify a specific year.
  #>
  Param(
    [Parameter(Mandatory=$false,ValueFromPipeline=$true)] 
    [int]$Month = (Get-Date).Month,
    [Parameter(Mandatory=$false)]
    [int]$Year = (Get-Date).Year
  )
  Write-Verbose "Patch Tuesday Month                : $($Month)"
  Write-Verbose "Patch Tuesday Year                 : $($Year)"
  $FindNthDay = 2
  $WeekDay = "Tuesday"
  $WorkingDate = Get-Date -Month $Month -Year $Year
  $WorkingMonth = $WorkingDate.Month.ToString()
  $WorkingYear = $WorkingDate.Year.ToString()
  [datetime]$StrtMonth = $WorkingMonth + "/1/" + $WorkingYear
  while ($StrtMonth.DayofWeek -ine $WeekDay)
  {
    $StrtMonth = $StrtMonth.AddDays(1)
  }
  $PatchTuesday = $StrtMonth.AddDays(7*($FindNthDay-1))
  return $PatchTuesday
}
Posted in Patch Tuesday, PowerShell, Windows Updates.

2 Comments

    • Hi Fabian,

      Not sure what the best license would be for this code but I guess GNU GPL v3 seems like a good match. You can use it in your blog post and I would appreciate it if you would share the link to your blog post and add a source link in it to this code.

      Soon I will try and add some more code etc. to my blog since I wrote many more scripts and modules also for Configuration Manager, just been a bit busy at work and privately.

Leave a Reply

Your email address will not be published. Required fields are marked *