Home > Software engineering >  How to print Upcoming 4 Fridays in Powershell
How to print Upcoming 4 Fridays in Powershell

Time:10-30

I am wring a PowerShell to print dates of upcoming 4 Fridays.

$date = Get-Date
for ($num = 1 ; $num -le 4 ; $num  ){ 
while ($Date.DayOfWeek -ne "Friday") {$date = $date.AddDays($num)}
$datestr = $date.ToString('dd-MM-yyyy')
echo $datestr
$SomeVar = "Friday - "   $num   " - "   $datestr
echo $SomeVar
} 

Output :

04-11-2022
Friday - 1 - 04-11-2022
04-11-2022
Friday - 2 - 04-11-2022
04-11-2022
Friday - 3 - 04-11-2022
04-11-2022
Friday - 4 - 04-11-2022

Here I am able to print the single date of upcoming Friday. But, I wanted to print the dates of upcoming 4 Fridays.

Can you please help me out what I am missing or any better way to Print Dates Upcoming Specific day.

Thank you.

CodePudding user response:

You're making this too difficult.

Try

# skip if today happens to be a Friday too, because you want 'upcoming'
$date = (Get-Date).AddDays(1)  
# while $date is not a Friday, keep adding days to it
while ($date.DayOfWeek -ne 'Friday') { $date = $date.AddDays(1) }

# next output the 4 upcoming Fridays
for ($i = 1; $i -le 4; $i  ) {
    Write-Host "$($date.DayOfWeek) - $i - $($date.ToString('dd-MM-yyyy'))"
    $date = $date.AddDays(7)
}

Output:

Friday - 1 - 04-11-2022
Friday - 2 - 11-11-2022
Friday - 3 - 18-11-2022
Friday - 4 - 25-11-2022

CodePudding user response:

Your date variable is being replaced with a string variable. Consider naming the new variable to reflect what it contains:

$dateStr = $date.ToString('dd-MM-yyyy')
  • Related