Chinh Do

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

13th September 2014

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

posted in PowerShell, Programming |

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)
    }    
}
This entry was posted on Saturday, September 13th, 2014 at 12:09 am and is filed under PowerShell, Programming. You can follow any responses to this entry through the RSS 2.0 feed. You can skip to the end and leave a response. Pinging is currently not allowed.

There is currently one response to “Finding the Last Friday (or any weekday) of the Month in PowerShell”

  1. 1 On August 30th, 2016, Martijn said:

    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

Leave a Comment

  • Calendar

  • September 2014
    M T W T F S S
    « Apr   Nov »
    1234567
    891011121314
    15161718192021
    22232425262728
    2930