Testing for End of Month in PowerShell
This is one of those blog posts you write so that 2 years later, you can look it up to remind yourself how to do something.
I found myself needing to figure out if “today” was the end of the month in PowerShell. In T-SQL, this is easy, as we have the EOMONTH()
function. But PowerShell (the .NET System.DateTime
struct) doesn’t have the same thing.
Fortunately, the lack of a .NET EOMONTH()
function is easily remedied with the DaysInMonth()
method. I just need to check the day of month against the number of days in the month.
$CurrentDate = Get-Date;
$IsEndOfMonth = $CurrentDate.Day -eq [System.DateTime]::DaysInMonth($CurrentDate.Year,$CurrentDate.Month) ? $true : $false;
This will work for any date by passing (for example) -Date 1955-11-05
to Get-Date
.
In the past, I haven’t been a big fan of ternary operators but they’re growing on me, especially for quick hits like this.
Important note for formatting here - the spaces around the :
operator are mandatory. If you use a formatter, it will probably not correct this because there are cases where <string>:<string>
is valid (like $Using:variablename
or -Verbose:$VerbosePreference
). Your editor (assuming it understands PowerShell, like VSCode) will flag the lack of spaces as an error here because it’s not valid in this context. My recommendation: just get in the habit of putting spaces around both the ?
and :
.