Powershell - Find the next Friday

别来无恙 提交于 2020-01-03 17:36:30

问题


Hoping this won't be too difficult but I am writing a script that queries user information from the domain and exports to CSV.

The script is run by our administrative staff and all they need to input into the script is the username.

The tricky part is that I need the CSV to be named based on the coming Friday.

Note: I am in Australia so my date format is DD-MM-YYYY

The way I am currently looking at going about it is as below:

# Grab the Script Run Timestamp
$ScriptRuntime = Get-Date -Day 4 -Month 5 -Year 2013

# Grab the next Friday (including today)
$NextFriday = $ScriptRuntime.AddDays(0 + $(0,1,2,3,4,5,6 -eq 5 - [int]$ScriptRuntime.dayofweek))

Write-Host "Script Run:  "$ScriptRuntime
Write-Host "Next Friday: "$NextFriday

This works OK with all days except Saturday.

  • If i run the day as Day 26, Month 5, Year 2013 it returns 31/05/2013
  • If i run the day as Day 27, Month 5, Year 2013 it returns 31/05/2013
  • If i run the day as Day 28, Month 5, Year 2013 it returns 31/05/2013
  • If i run the day as Day 29, Month 5, Year 2013 it returns 31/05/2013
  • If i run the day as Day 30, Month 5, Year 2013 it returns 31/05/2013
  • If i run the day as Day 31, Month 5, Year 2013 it returns 31/05/2013
  • If i run the day as Day 1, Month 6, Year 2013 it returns 31/05/2013 (this should be 07/06/2013)
  • If i run the day as Day 2, Month 6, Year 2013 it returns 07/06/2013

What am i doing wrong?


回答1:


I'm not sure I'm following you but here's I would get next Friday:

$date = Get-Date

for($i=1; $i -le 7; $i++)
{        
    if($date.AddDays($i).DayOfWeek -eq 'Friday')
    {
        $date.AddDays($i)
        break
    }
}



回答2:


This finds the next Friday:

$date = Get-Date
while ($Date.DayOfWeek -ne "Friday") {$date = $date.AddDays(1)}



回答3:


Here's a one-liner that'll do the trick too:

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

And if you need a specific time:

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



回答4:


You can get the date of the Friday of this week, regardless of what date you run the code, using the following:

$today = (Get-Date).Date    
$nextfriday = $today.AddDays([int][dayofweek]::Friday - $today.DayOfWeek)    

If you want to always get the next Friday (so, next week's Friday if you run on a Saturday), you just need an extra modifier at the end:

if ($today -ge $nextfriday) {$nextfriday = $nextfriday.AddDays(7)}



回答5:


Try this to find next friday:

$ScriptRuntime = Get-Date -Day 4 -Month 5 -Year 2013
$i= switch ( [int][dayofweek]::Friday - [int] $ScriptRuntime.dayofweek )
    { 
       -1 { 6 }
       default { $_ }
    } 
$ScriptRuntime.adddays($i)



回答6:


A bit late to the party, but here's my take (no loops, no conditionals):

    [datetime] $MyDate =  get-date
    [DayOfWeek] $NextDayOfWeek = 'Friday'

    $MyDate.AddDays( (7 - [int] $MyDate.DayOfWeek + [int] $NextDayOfWeek )%7 )

If you want to verify it for a larger number of dates:

    [datetime] $MyDate =  get-date
    [DayOfWeek] $NextDayOfWeek = 'Friday'

    1..30 | ForEach-Object {
                            [PSCustomObject]@{ 
                                DayOfWeek = $MyDate.DayOfWeek ;
                                Date = $MyDate; 
                                $("Next$NextDayOfWeek") = $MyDate.AddDays((7 - [int] $MyDate.DayOfWeek + [int] $NextDayOfWeek )%7)   
                            }; 
                            $MyDate = $MyDate.AddDays(1)  
                        } 



回答7:


I would do it like this:

$Date = Get-Date
$targetDay = [int][dayofweek]::Friday
# I use this logic to figure out the next Friday
# else we would get Friday of this week
$intToday = if([int]$Date.DayOfWeek -le [int][dayofweek]::Friday ){
                [int]$Date.DayOfWeek 
            } else { 
                [int]$Date.DayOfWeek - 7
            }
$nextFriday = $date.AddDays($targetDay - $intToday)

I came across the same issue, but I thought using a loop was a little too much. I found an article about PowerShell Find Date of a previous day in any week but the values where hard coded for the days and depending on your windows environment the Sunday may not be index 0 (zero). So, I used the logic as inspiration and figured the one above.

Hope it helps next guy.




回答8:


I put Shay's example into the extended function, so you can also target the exact time of the date that you are looking for.

Function Find-NextDate {
[CmdletBinding()]
param (
    # Parameter help description
    [Parameter(Mandatory=$true,
    Position=1)]
    [validatenotnullorempty()]
    [ValidateSet("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")]
    [string]$Day,
    [Parameter(Mandatory=$false,
    Position=2)]
    [validatenotnullorempty()]
    [string]$Time
)
process {
    if ($Time) {
        $Date = (Get-Date $Time)
        for($i=1; $i -le 7; $i++) {        
            if ($Date.AddDays($i).DayOfWeek -eq "$Day") {
                $Date.AddDays($i)
                break
            }
        }
    }
    else {
        $Date = (Get-Date)
        for($i=1; $i -le 7; $i++) {        
            if ($Date.AddDays($i).DayOfWeek -eq "$Day") {
                $Date.AddDays($i)
                break
            }
        }
    }
}

}




回答9:


You could install ProductivityTools.PSGetDayInGivenWeek module from PowerShell Gallery

Install-Module -Name ProductivityTools.PSGetDayInGivenWeek

It exposes method Get-RequestedDayOfWeek which allows, to define what day of week are you looking for and if you are looking it before or after given day. So to find next Monday

Get-RequestedDayOfWeek '2018.03.03' -Monday -After

Module in PowerShell Gallery can be found here, and code for it here.



来源:https://stackoverflow.com/questions/16785241/powershell-find-the-next-friday

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!