Creating Calendars (and Lists of Dates)

by Oct 10, 2013

Here's a code snippet that creates DateTime ranges. Just specify a year and a month, and the script produces a DateTime object for each day in that month:

$month = 8
$year = 2013

1..[DateTime]::DaysInMonth($year,$month) |
  ForEach-Object { (Get-Date -Day $_) } 

This can be pretty useful: just add a day filter, and you get working days only. This will list all Mondays through Fridays in the given month (because it excludes weekday 0 (Sunday) and weekday 6 (Saturday):

$month = 8
$year = 2013

1..[DateTime]::DaysInMonth($year,$month) |
  ForEach-Object { Get-Date -Day $_ } |
  Where-Object { 0,6 -notcontains $_.DayOfWeek } 

Likewise, this will count all Wednesdays and Fridays in a given month:

$month = 8
$year = 2013

$days = 1..[DateTime]::DaysInMonth($year,$month) |
  ForEach-Object { Get-Date -Day $_ } |
  Where-Object { 3,5 -contains $_.DayOfWeek } 

$days
"There are {0} Wednesdays and Fridays" -f $days.Count 

Twitter This Tip! ReTweet this Tip!