PowerShell: Determine The Last Day of a Month (incl. the Day of the Week)

Except for February, it is possible to hard-code the last day of each month since the number of days is fixed. However, you still have to determine the day of the week separately.

Rather than doing this manually, the code snippet below should do the trick:

#determine the last day of the first quarter of the year 2020 including the day of the week (Jan to March)

$date = Get-Date "2020-01-01"
$qtr2 = $date.AddMonths(3)
#Mittwoch, 1. April 2020 00:00:00

$qtr2FirstDay = Get-Date -Month $qtr2.Month -Day 1 -Year $qtr2.year;
#Mittwoch, 1. April 2020 23:56:43

$qtr1LastDay = $qtr2FirstDay.AddDays(-1);
#Dienstag, 31. März 2020 23:56:43

Windows PowerShell 5.1, PowerShell Core 6.x & (slipped Jan 2020 GA) PowerShell 7

Windows PowerShellPowerShell Core 6.x (6.0, 6.1 and 6.2) is Microsoft’s initial attempts to bring the veteran Windows PowerShell outside of its core Windows ecosystem to Linux and macOS based platforms. It is designed to run side-by-side (SxS) when installed on supported Windows operating systems where the feature set is not on par with Windows PowerShell due to its high dependency on Windows specific components and the full .NET Framework stack.

This has not stopped PowerShell enthusiasts from writing scripts that already utilize new PowerShell Core functionality (but often not properly “labelled”). Besides breaking backwards compatibility, such code may pose a real risk if not closely inspected first for suitability of use. This is because many are either delivered with sparse or incomplete documentation and neither follow good software development practices nor have security baked right in i.e. lack of safety nets* due to “fire fighting” nature in the real world, for instance.

Although it now looks like the planned January 2020 GA of PowerShell 7 per the PowerShell team has slipped – with a possible yet unannounced Release Candidate 2 (RC2) – you can start preparing for the transition to the “harmonized” P7 version based on the .NET Core 3.1 LTS by working on the last Release Candidate v7.0.0-rc.1 (2019-12-16) posted on GitHub.

* version check, try/catch blocks, advanced functions, etc.