Powershell Golf: Next Business Day

How to find the next business day with powershell?

+3
source share
4 answers

This is also pretty short (but uses aliases):

,(1,2-eq7-(date).dayofweek)|%{(date)+"$(1+$_[0])"}

In one statement:

(date)+"$(1+$(@(1,2-eq7-(date).dayofweek)))"

A few notes about this approach:

  • In Powershell (at least v1), comparisons with collections return elements where the condition is true, for example:

    PS> 1,2 -eq 1
    PS> 1

  • I use the fact that the actual exceptions to the rule today + 1for calculating the next business day are only Friday (+3 days) and Saturday (+2 days).

+8
source

Okay, my phone allows me to set which days are working days, but Windows / .NET will not, so I guess Monday through Friday.

. "", , script. .

- , , :

PS> $d = [DateTime]::Now.AddDays(1); while ($d.DayOfWeek -eq "Saturday" -or $d.DayOfWeek -eq "Sunday") { $d = $d.AddDays(1) }; $d
Montag, 22. Juni 2009 19:50:27

:

PS> $d=(Get-Date)+"1";for(;6,0-contains$d.DayOfWeek){$d+="1"}$d
Montag, 22. Juni 2009 19:52:31

-, . - , , , :

PS> @(1..3|%{(Get-Date).AddDays($_)}|?{$_.DayOfWeek -ge "Monday" -and $_.DayOfWeek -le "Friday"})[0]
Montag, 22. Juni 2009 22:11:19

:

PS> @(1..3|%{(Get-Date)+"$_"}|?{1..5-contains$_.DayOfWeek})[0]
Montag, 22. Juni 2009 19:55:53

4, , @, :

PS> (1..4|%{(Get-Date)+"$_"}|?{1..5-contains$_.DayOfWeek})[0]
Montag, 22. Juni 2009 20:24:06
+11

:

(@(1..4) | foreach { if (([datetime]::Now.AddDays($_)).DayOfWeek -ne "Sunday" -and ([datetime]::Now.AddDays($_)).DayOfWeek -ne "Saturday") {[datetime]::Now.AddDays($_); }})[0]

, (1..4) (1..3).

+3

I found the sample code in the first answer really difficult to follow, so I rewrote it to find out a little what is going on. I still use the -eq behavior, where -eq test will return the corresponding value.

$date = get-date "2013 Apr 24"

write-host "Based on your date"
$date

write-host "next business day (skipping saturday and sunday)"
$Date.AddDays(1 + $(1,2 -eq 7 - [int]$date.dayofweek) )

write-host "Next week monday"
$Date.AddDays(1 + $(0,1,2,3,4,5,6,7 -eq 7 - [int]$date.dayofweek) )
0
source

Source: https://habr.com/ru/post/1657457/


All Articles