Weekend Scripter: Use PowerShell to Explore Dates

Weekend Scripter: Use PowerShell to Explore Dates

  • Comments 3
  • Likes

Summary: Microsoft Scripting Guy, Ed Wilson, shows how to use Windows PowerShell to explore dates in the future.

Microsoft Scripting Guy, Ed Wilson, is here. This afternoon, I am sipping a nice cup of Kwai Flower Organic Oolong tea. It is a slightly sweet, mild tea that goes well with jasmine blossoms. It makes for a nice relaxing afternoon, and the slightly woody flavor goes well with Macadamia nuts.

Now contrast a nice relaxing afternoon with Friday the 13th. If I want to be prepared for the next Friday the 13th, how can I use Windows PowerShell to get that information for me? Well, it literally took me less than five minutes to come up with an answer.

The key to finding dates in the future is to use the DateTime object. I am lucky because the Get-Date cmdlet returns a DateTime object. I can then directly call the AddDays method to it. I create an array of 1000 numbers and pipe it to the AddDays method to create a thousand days in the future. That should give me enough warning. If not, I can easily change it to ten thousand days.

To get my thousand numbers to the AddDays method, I need to use the Foreach-Object cmdlet. I pipe my array of numbers to the Foreach-Object cmdlet, and I use the $_ automatic variable to represent the individual number as it comes across. I then store the newly create DateTime object in a variable I call $dte. This is shown here:

1..1000 |

ForEach-Object {

       $dte = (Get-Date).AddDays($_)

Now all I need to do is to use two properties from the DateTime object. The first is the DayOfWeek property. This returns the day name, and I am interested in Friday. I am only interested in Friday if the Day property is also 13. This is a simple IF statement:

If ($dte.DayOfWeek -eq 'Friday' -AND $dte.Day -eq 13)

If I find a match for the two conditions of a DayOfWeek of Friday and a Day equal to 13, all I need to do is to print the DateTime object for that date. This is shown here:

{ $dte }

And that is all there is to the script. When I run it in the Windows PowerShell ISE, I see the following in the output pane.

Image of command output

Surprisingly, according to my Windows PowerShell script, Friday the 13th only occurs two or three times a year. Sometimes less. In 2016, it only occurs once, but in 2015, it occurs three times. Dude, better start making plans now.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment