Improve script to get previous week day

后端 未结 1 1951
粉色の甜心
粉色の甜心 2021-01-21 23:14

I\'ve got a little powershell script here that finds the last previous day. At the moment I\'m doing - If it\'s monday then subtract 3 days, if it\'s Sunday subtract 2 days and

相关标签:
1条回答
  • 2021-01-21 23:20

    You can calculate the previous workday like this:

    $d = Get-Date
    
    $offset = ($d.DayOfWeek.value__ + 5) % 7
    $delta1 = [math]::Floor([int]$offset / [int]5)
    $delta2 = [math]::Floor([int]$offset / [int]6)
    
    $prevWD = $d.AddDays(-($delta1 + $delta2 + 1)).DayOfWeek
    

    However, it might be simpler to just do something like this:

    $d = Get-Date
    
    if ('Sunday','Monday' -contains $d.DayOfWeek) {
      $prevWD = 'Friday'
    } else {
      $prevWD = $d.AddDays(-1).DayOfWeek
    }
    

    Demonstration:

    PS C:\> $now = Get-Date
    PS C:\> 0..6 | % {
    >>   $wd = $now.AddDays($_)
    >>   $wd | % {
    >>     $offset = ($_.DayOfWeek.value__ + 5) % 7
    >>     $d1 = [math]::Floor([int]$offset / [int]5)
    >>     $d2 = [math]::Floor([int]$offset / [int]6)
    >>     "{0,-10}`t{1}" -f $wd.DayOfWeek, $_.AddDays(-($d1 + $d2 + 1)).DayOfWeek
    >>   }
    >> }
    >>
    Monday          Friday
    Tuesday         Monday
    Wednesday       Tuesday
    Thursday        Wednesday
    Friday          Thursday
    Saturday        Friday
    Sunday          Friday
    0 讨论(0)
提交回复
热议问题