Tuesday, May 20, 2014

Counting the Days with PowerShell

Being a PowerShell addict means finding excuses to do something fun when the task at hand is pretty boring.

This little snippet just finds the number of working days in a given month, something handy when estimating time and materials contracts.

 

### Capture the holidays in a HashTable

### Could have used an array but thought I might need the name of the holiday eventually

$Holidays = @{

"New Year's Day"              = Get-Date 'Jan 1'

"Martin Luther King, Jr. Day" = Get-Date 'Jan 21'

"Presidents' Day"             = Get-Date 'Feb 18'

"Memorial Day"                = Get-Date 'May 27'

"Independence Day"            = Get-Date 'Jul 4'

"Labor Day"                   = Get-Date 'Sep 2'

"Thanksgiving Day"            = Get-Date 'Nov 28'

"Day After Thanksgiving"      = Get-Date 'Nov 29'

"Christmas Day"               = Get-Date 'Dec 25'

}

 

### PowerShell Loves Puppies

$VerbosePreference = 'Continue'

 

### Initialize the number of working days (this turns out to be my ideal)

$workingDays = 0

 

### Set the Month

$Month = 7

 

### Get the number of days in the month

$DaysInMonth = [DateTime]::DaysInMonth([DateTime]::Today.Year,$Month)

 

### Count the days in the month, excluding weekends and holidays

for ($day = 1; $day -le $DaysInMonth; $day++)

{    

    if (([DateTime]"$Month $day").DayOfWeek -in @('Saturday','Sunday'))

    {

        Write-Verbose "Weekend! $Month $day"

    }

    elseif($Holidays.ContainsValue([DateTime]"$Month $day"))

    {

        Write-Verbose "Holiday! $Month $day"

    }

    else

    {

        $workingDays++

    }

}

 

### Spew the output

$workingDays

 

No comments: