改进脚本以获得前一周的工作日

时间:2014-12-15 10:23:23

标签: powershell

我在这里找到了一个小型的PowerShell脚本,找到了前一天。 目前我正在做 - 如果它是星期一然后减去3天,如果它的星期日减去2天,如果它在任何其他日减去1.这似乎有点愚蠢......有更好的方法吗?

$prevWD =
if ((Get-Date).DayOfWeek -eq 1) #Monday
{ (get-date).AddDays(-3) }
elseif ((Get-Date).DayOfWeek -eq 0) #Sunday
{ (get-date).AddDays(-2) }
ELSE { (get-date).AddDays(-1) } #Any other day

1 个答案:

答案 0 :(得分:2)

您可以像这样计算上一个工作日:

$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

但是,做这样的事情可能更简单:

$d = Get-Date

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

演示:

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