In October 2012, I published a function to find the last Sunday or another day of a month and based on some comments, I decided to revisit the code and improve it.
I started to improve the discovery of expected values by some parameters like the day, the month and year.
To achieve this I started to use a Dynamic parameter block and had the following code:
I wasn’t satisfied although it worked as expected. It’s hard to read, there are too many variables…
I remember I’ve already seen someone who wrote helper functions to avoid writing so many redundant code in the dynamic parameter block. (I cannot remember who. If you do, please post a link in the comments).
I wrote a quick helper function. I didn’t want to go further in order to keep the complexity quite low.
It’s around 50 lines.
Here’s an example to create a ValidateRange parameter attribute for the “Month” parameter.
Let’s see how this helper function is used in practice:
I first create the Dictionary object in the dynamic parameter block.
I load the helper function.
I then create the 3 dynamic parameters for the day, month and year.
Notice that I’ve also used some hash-table and splatting separated by a semicolon inside the same script block for a better readability.
There are only two variables left my dynamic parameter block ($Dictionary and $HT).
Now, let’s see how this function performs.
I’ve added a new feature where you can actually tell what day position in the month you want.
You can get the First, Second, Third, Fourth or Last.
You might be scratching your head why such options.
Well, let’s take a concrete example to illustrate why.
Let’s say Sunday.
In February 2016, you’ve got 4 Sundays but in April 2017, you’ve got 5.
One of the purpose of this function is to find out the last Sunday in a month to run a scheduled task.
Or you may want to run your task every fourth Sunday in a month.
Sometimes, the fourth Sunday is the last Sunday like it’s in February 2016.
But that’s not true in April 2017
I’ve got another code snippet to demo how this function can be used:
I can display the first, last, fourth Sunday in every month in 2016 and the number of days between the first and last 😎