Skip to content

Get number of week days between dates

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
Function Get-TotalWeekDays
{
  [cmdletbinding()]

  Param (
    [Parameter(Position = 0,Mandatory = $True,HelpMessage = 'What is the start date?')]
    [ValidateNotNullorEmpty()]
    [DateTime]$Start,
    [Parameter(Position = 1,Mandatory = $True,HelpMessage = 'What is the end date?')]
    [ValidateNotNullorEmpty()]
    [DateTime]$End
  )

  Write-Verbose -Message "Starting $($myinvocation.mycommand)"
  Write-Verbose -Message "Calculating number of week days between $Start and $End"

  #define a counter
  $i = 0
  #test every date between start and end to see if it is a weekend
  for ($d = $Start;$d -le $End;$d = $d.AddDays(1))
  {
    if ($d.DayOfWeek -notmatch 'Sunday|Saturday') 
    {
      #if the day of the week is not a Saturday or Sunday
      #increment the counter
      $i++
    }
    else
    {
      #verify these are weekend days
      Write-Verbose -Message ('{0} is {1}' -f $d, $d.DayOfWeek)
    }
  } #for

  #write the result to the pipeline
  $i

  Write-Verbose -Message "Ending $($myinvocation.mycommand)"
}