Determine the Last Day of the Previous Month with PowerShell

I recently had a need to determine the last day of the previous month with PowerShell. Unless I’m overlooking something, PowerShell doesn’t natively have a way to determine this.

Luckily, the System.Time class in the .NET Framework has a DaysInMonth method that returns the number of days in a specific month which effectively gives you the last day of the month. The command to determine what I needed was simple enough:


I went ahead and created a well documented and reusable function that is more dynamic to use in similar scenarios in the future:

I’ll work through the examples of the function so you can see how it can be used. Running it without any parameters causes it to default to finding the last day of the previous month:


The second example shows providing parameter input to get the last day for next month:


The third example shows determining the last day of the month, three months ago:


And the final example shows determining the last day of the month for the previous six months via pipeline input:


I actually figured out another way to accomplish this task in PowerShell between the time I wrote this blog and the time I published it, but I thought I would leave the previous content intact as well.

You know the first of a month is always going to be number 1 so you can actually subtract one millisecond from the first to receive the last day of the month:


And for a more dynamic version of the previous one-liner, you could do something crazy like this:


I don’t normally publish commands with aliases on my blog, but since that previous command is fairly cryptic already, I’ll make an exception in this scenario:


Whatever you do, please don’t use aliases or positional parameters in your scripts!



  1. Dirk

    Hi Mike,

    here is another way to get the last day of the previous month without using .net:

  2. scriptips777

    Thanks Mike and here is a slightly different approach and similar to Dirk’s approach (Great Tip by the way).

    #PowerShell: Desired dates
    first Date of the current month: (Get-Date -Day 1)
    last Date of the previous month: (Get-Date -Day 1).AddDays(-1)

  3. Kerry Webster

    Last date of current month:
    (Get-Date -day 1 -hour 0 -minute 0 -second 0).AddMonths(1).addseconds(-1)


    $x=(Get-Date -day 1 -hour 0 -minute 0 -second 0)

  4. Arnold

    Hi Sir,

    Please can you rectify my probleme?


    $date = [datetime]::Today # date to send mail
    $startofmonth = Get-Date $date -day 1 -hour 0 -minute 0 -second 0
    $endofmonth = (($startofmonth).AddMonths(1).AddSeconds(-300))

    if([datetime]::Today -eq $endofmonth.DayOfYear -and $endofmonth.Minute -gt 55 -and $endofmonth.Minute -lt 59)
    {” ”
    C:\MailFolder\mail.ps1 }
    else { ” ” }

    Thanks for your help


Leave a Reply

%d bloggers like this: