PowerShell Diversion #1: Discussion

[Follow-up discussion for PowerShell Diversion #1 ]

So, when did the show take place? 

Well, with the given information, it is impossible to tell for sure.  The 11 November was a Thursday in 1971 and 1976, so it could be either of those.  To confirm this with PowerShell …

The first hint should lead you to the Range Operator, (“..”).  This operator provides a quick way to produce collections of consecutive numbers.  In this example, we can produce all of the years from 1970 to 1979 like this:

1970 .. 1979

This by itself will show you a list of all the dates in this range:

1970

1971

1972

1973

1974

1975

1976

1977

1978

1979

From here, we need some way to check which day of the week the 11 November was in each year.  The second hint was to look at DateTime objects and any cmdlets that can manipulate these.  The key cmdlet here is Get-Date, which returns a DateTime object:

(Get-Date).GetType()

Which returns:

IsPublic IsSerial Name     BaseType
-------- -------- ----     --------
True     True     DateTime System.ValueType

Get-Date can not only return a DateTime object for today’s date, but will do so for any valid date information.  For example:

Get-Date “11 November 2011”

The last thing to know is that DateTime objects have a DayofWeek member which tells you on which day of the week the particular date falls.  For example:

(Get-Date “13 August 2012”).DayofWeek

Which is, of course, a Monday!

Putting this all together, the following simple one-liner can solve the original problem:

1970 .. 1979 | Where-Object{(Get-Date "11 November $_").DayofWeek -eq "Thursday" }

Which gives the solutions:

1971

1976

Applying this same technique with different date ranges yields the answers to the two bonus questions:

  1. From 1970 to 2011, the 11 November fell on a Thursday 7 times
  2. The next time that 11 November will fall on a Thursday is in 2021