Friday Fun: Get Friday the 13th

I thought it might be fun today to use PowerShell to discover all the Friday the 13ths in a given year. So I put together a simple PowerShell one-liner. To make it flexible I’ll use a variable for the year, using the current year as my value.

Because there can only be one Friday the 13th per month, I can use code like this to build a datetime object for the 13th of every month.

But this will only give me the integers for the matching months. So I’ll take this a step further and get the actual datetime object.

If you try this code you’ll see two results for 2013. I can take this idea a step further. Suppose I want to find the last Friday of every month. Here’s one way I might do it:

All I’ve done is taken my outer monthly loop, and added an inner ForEach loop to test each day of the month for a Friday and then select the last one for each month. I’ll let you try it on your own to see the results.

As for today, don’t worry. It’s just another day and a Friday at that!

4 thoughts on “Friday Fun: Get Friday the 13th”

  1. Instead of testing if each day of the month is Friday, how about testing if each 13th of the month is a Friday:

    1950..2050 | ForEach-Object { $year = $_ ; 1..12 | ForEach-Object { $month = $_ ; If (([DateTime] “$year/$month/13″).DayOfWeek -Eq ‘Friday’) { Write-Output “$year/$month/13″ } } }

  2. Actually, that is exactly what I’m doing, although only for the current year. The code at the end of the post is to find the last Friday of the month, not the 13th.

    1. Here are some other ways to test for multiple years. Here’s a variation on Terry’s code that defines a function in the Begin scriptblock with ForEach-Object.

      2013..2023| foreach -begin {
      Function Test-Date {
      1..12 | foreach {
      ([datetime]"$_/13/$Year")} | where {$_.DayofWeek -eq "Friday"
      } #foreach month
      } #function
      } -process {
      Test-Date $_

      Or even better and faster, create a filtering function to test all the months in a single year for Friday the 13ths.

      Filter Test-Date {
      Param (
      1..12 | foreach {
      ([datetime]"$_/13/$Year")} | where {$_.DayofWeek -eq "Friday"
      } #foreach month

      PS C:\> 2013..2015 | Test-Date
      Friday, September 13, 2013 12:00:00 AM
      Friday, December 13, 2013 12:00:00 AM
      Friday, June 13, 2014 12:00:00 AM
      Friday, February 13, 2015 12:00:00 AM
      Friday, March 13, 2015 12:00:00 AM
      Friday, November 13, 2015 12:00:00 AM

Comments are closed.