As we are approaching the holiday season at the end of the year, dates are very important. Everything from counting down the days to the new year to creating those end of the year reports.
With that said, how many times have you had to create a report for the previous month, but it’s parameters are only StartDate and EndDate? Now, you have to remember how many days are in that month and consider if it’s a leap year or not. And sometimes the first of the month is on a weekend, Holiday, or a day you took PTO so you have to make sure your code doesn’t just go back 30 days as then it may or may not get the whole previous month. And let’s say for reasons you can’t control, you can’t have it as a scheduled task to always run on the first of the month?
This one liner(technically 2 one for StartDate and one for EndDate), is the solution you need. It will check which month your in, go to the previous month then find the first and last day of that month. That’s it!
$StartDate = (Get-Date -Day 1).AddMonths(-1).ToString("yyyy-MM-dd")
$EndDate = (Get-Date -Day 1).AddDays(-1).ToString("yyyy-MM-dd")
If you wanted the past 6 months you could change the -1 to -6 in Start Date. Now you don’t have to manually enter the month date range every time you need a report for the previous month. You could set this as the default parameter, but give yourself the option to change it if you need a different date range.
Documentation:
Get-Date:
Microsoft Learn
Leave a Reply