Categories: PowerShellProgramming

Finding the Last Friday (or any weekday) of the Month in PowerShell

If there are less than 7 days left in the month, then it’s the last weekday of this type in this month.

function Is-LastWeekDayOfMonth([DateTime] $d) {
    return [DateTime]::DaysInMonth($d.Year, $d.Month) - $d.Day -lt 7
}

Similarly, finding the last specific weekday of the month involves finding the last weekday, and the difference between that weekday and the target weekday:

function Get-LastFridayOfMonth([DateTime] $d) {
    $lastDay = new-object DateTime($d.Year, $d.Month, [DateTime]::DaysInMonth($d.Year, $d.Month))
    $diff = ([int] [DayOfWeek]::Friday) - ([int]
    $lastDay.DayOfWeek)
    if ($diff -ge 0) {
        return $lastDay.AddDays(- (7-$diff))
    }
    else
    {
        return $lastDay.AddDays($diff)
    }
}

Chinh Do

I occasionally blog about programming (.NET, Node.js, Java, PowerShell, React, Angular, JavaScript, etc), gadgets, etc. Follow me on Twitter for tips on those same topics. You can also find me on GitHub. See About for more info.

View Comments

  • Hi Chinh Do,
    I stumbled upon your script today.
    I was looking for something like this.
    There is just one minor thing about your script.
    In your If statement, you should use -gt in stead of -ge to return the correct value.

    Much appreciated!
    Martijn

Recent Posts

How to switch to a different Kubernetes context or namespace?

To list available contexts: kubectl config get-contexts To show the current context: kubectl config current-context…

2 years ago

How to ssh into Kubernetes pod

kubectl exec -it <podname> -- sh To get a list of running pods in the…

2 years ago

How to Create a Soft Symbolic Link (symlink) in Unix/Linux

# Create a soft symbolic link from /mnt/original (file or folder) to ~/link ln -s…

3 years ago

How to Configure Git Username and Email Address

git config --global user.name "<your name>" git config --global user.email "<youremail@somewhere.com>" Related Commands Show current…

3 years ago

Getting the Last Monday for Any Month with TypeScript/JavaScript

TypeScript/JavaScript function getLastMonday(d: Date) { let d1 = new Date(d.getFullYear(), d.getMonth() + 1, 0); let…

4 years ago

How to View Raw SMTP Email Headers in Outlook

I had to do some SMTP relay troubleshooting and it wasn't obvious how to view…

5 years ago