Calculate the number of working days between two values

…this post was published on 2015 October 18.

Bollow is the script to calculate working days between to date values, removing Sundays and Saturdays and the holidays from the .csv file
( an example of that .csv file attached in this post as well – after you download it, rename in Hollidays.csv, or change file name as presented bellow in green  ).
To download the .csv file click here
This attached files looks like
and if you prefer, you can create your own csv file

 

<#
.Synopsis
Get total number of week days
.Description
Return the number of days between two dates not counting Saturday and Sunday.
.Parameter File
The .csv file with Hollydays
.Parameter Start
The starting date
.Parameter End
The ending date
.Example
PS C:\> Get-TotalWeekDays -file ./Hollydays.csv -start 7/1/2012 -end 7/31/2012
.Inputs
None
.Outputs
Integer
.Author
Romeo Donca mail:romeodonca@outlook.com
#>
[cmdletbinding()]
Param (
[Parameter(Position=0,Mandatory=$True,ValueFromPipeline=$true,HelpMessage=”what is the csv file name?”)]
[ValidateNotNullorEmpty()]
[ValidatePattern(‘(.csv)$’)]
[String]$file,
[Parameter(Position=1,Mandatory=$True,ValueFromPipeline=$true,HelpMessage=”What is the start date?”)]
[ValidateNotNullorEmpty()]
[DateTime]$Start,
[Parameter(Position=2,Mandatory=$True,ValueFromPipeline=$true,HelpMessage=”What is the end date?”)]
[ValidateNotNullorEmpty()]
[ValidateScript({If ($_ -ge $Start) {
$True
} Else {
Throw “$_ Should be greater than $start”
}})]
[DateTime]$End
)
Function Get_TotalWorkingDays()
{ 
    #read the csv file and store it in $hollydays
    $hollydays = Import-Csv $file
    #define new array with working days from hollydays
    $notworkingdays=@()
    #get this array’s elements
    #$notworkingdaysnumber =$notworkingdays.Length
 
    foreach ($data in $hollydays)
    {
    #$data}
        if (([datetime]$data.date).DayOfWeek -notmatch “Sunday|Saturday”)
        {
            $notworkingdays += $data.date
            $notworkingdaysnumber = $notworkingdays.Length
        }
    }
#define a counter
$i=0
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
 
# and if isn’t included in your hollydays file
if ( ($notworkingdays -contains (get-date $d -Format MM.dd.yyyy)) -match $true) { }
else{
# $d.ToShortDateString()
$i++
}
}
 
}
#write the result to the pipeline
“In the interval $($start.ToShortDateString()) – $($End.ToShortDateString()) are: $i working days”
} #end function
. Get–TotalWorkingDays
This entry was posted in csv, Powershell. Bookmark the permalink.