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.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
$year = (Get-date).Year
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.
1..12 | where { ([datetime]"$_/13/$year").DayOfWeek -eq 'Friday'}
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.
1..12 | foreach { ([datetime]"$_/13/$year") } | where { $_.DayOfWeek -eq 'Friday'}
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:
$year = (Get-date).Year 1..12 | foreach { $month=$_ $moDays = [datetime]::DaysInMonth($year,$_) 1..$moDays | foreach { ([datetime]"$month/$_/$year") }| where { $_.DayOfWeek -eq 'Friday'} | Select -Last 1 }
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!
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” } } }
That would certainly work as well.
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.
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 {
Param([int]$Year)
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 (
[Parameter(ValueFromPipeline=$True)]
[int]$year=(Get-Date).Year
)
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