Home > Software design >  Powershell - Find the latest Friday
Powershell - Find the latest Friday

Time:07-06

How can the following code be modified to identify the latest Friday within the past week (instead of the next one), but with formatting?

$Date = @(@(0..7) | % {$(Get-Date).AddDays($_)} | ? {$_.DayOfWeek -ieq "Friday"})[0]

Source: https://stackoverflow.com/a/23939203/5651418

CodePudding user response:

If I understood correctly, your expected output would be 1 7 2022, I would personally use a do loop that stops as soon as the DayOfWeek Property of the DateTime instance is Friday:

$date = [datetime]::Now
do {
    $date = $date.AddDays(-1)
} until($date.DayOfWeek -eq [DayOfWeek]::Friday)
$date.ToString("d M yyyy")

CodePudding user response:

The post you linked to offers a more elegant solution, which you can adapt as follows:

# Get the most recent Friday relative to the given date,
# which may be that date itself.
$mostRecentFriday = 
  ($date = Get-Date).AddDays((-7 - $date.DayOfWeek   [DayOfWeek]::Friday) % 7)

If you want to create a formatted string representation of the resulting [datetime] instance (all examples below yield something like '07 01 2022':

  • To use Unix-style format specifiers, use Get-Date's -UFormat parameter:

    Get-Date $mostRecentFriday -UFormat '%d %m %Y'    
    
  • To use .NET's format specifiers, use Get-Data's -Format parameter:

    Get-Date $mostRecentFriday -Format 'dd MM yyyy'  
    
    • Alternatively, pass the format string to the [datetime] instance's .ToString() method:

      $mostRecentFriday.ToString('dd MM yyyy')
      

CodePudding user response:

I noticed that some Get-Date -UFormat specifiers didn't seem to work when attempting to incorporate them into an output string.

Should anyone need to incorporate some rarely needed ones (like 'Week of Year' (%G), 'Day of Year (%j), etc) you could preset needed variables and add them to the output string:

$DayOfYear = (Get-Date -UFormat %j)

$WeekOfYear = (Get-Date -UFormat %V)

$Date = @(@(0..7) | % {$(Get-Date).AddDays(-$_)} | ? {$_.DayOfWeek -ieq "Wednesday"})[0].ToString("MM-dd-yyyy|Week $WeekOfYear|'Day' $DayOfYear")

I imagine someone could incorporate all the code into one Powershell command.

Additional Get-Date -UFormat specifiers: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-date?view=powershell-7.2#notes

  • Related