# Calculate x previous working days (exclude weekends)

101 Reputation points
2022-05-30T11:52:04.443+00:00

Hi,

I am looking for a way to get the date of the previous business day (without weekends - count only weekdays).

For example :

30/05/2022 -10 days = 16/05/2022.

I found this script :

\$enddate = Get-Date

\$difference = New-TimeSpan -Start \$startdate -End \$enddate
\$difference.Days

\$days = [Math]::Ceiling(\$difference.TotalDays)+1

1..\$days | ForEach-Object {
\$startdate
} |
Where-Object { \$_.DayOfWeek -gt 0 -and \$_.DayOfWeek -lt 6}

The result :

Could someone help me?

Thank you

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,478 questions

1. 33,066 Reputation points
2022-05-31T02:59:13.043+00:00

I'm confused. I don't see how "\$_.DayOfWeek -gt 0" is working because on my pc (Win11, PS5.1) that is an alpha value.

DateTime    : Wednesday, May 25, 2022 12:00:00 AM
Date        : 5/25/2022 12:00:00 AM
Day         : 25
DayOfWeek   : Wednesday
DayOfYear   : 145
Hour        : 0
Kind        : Unspecified
Millisecond : 0
Minute      : 0
Month       : 5
Second      : 0
Ticks       : 637890336000000000
TimeOfDay   : 00:00:00
Year        : 2022

As to the question; 10 business days is the known value and the problem is to solve for the calendar date. Correct?

Here is what I came up with.

\$days = 10                           # number of past business days to calculate
\$weekend = 'Saturday','Sunday'
\$startdate = Get-Date
\$busdays = @()                          # array of business days
while(\$true) {
if (\$weekend -notcontains \$startdate.DayOfWeek) {
\$busdays += \$startdate
}
if (\$busdays.count -ge \$days) {
break
}
}
cls
"Here are the prior \$days business days."
\$busdays
""
"Here is the date you are looking for."
\$busdays[\$days - 1]        # because the array in relative to zero

1. 45,911 Reputation points
2022-05-31T01:52:22.887+00:00

Try this:

\$startdate = (Get-Date "5/16/2022").Date        # midnight -- START of day on Monday
\$enddate =   \$startdate.Date.AddDays(10)        # midnight -- START of workday on the following Thursday (i.e., the END of Wednesday)

\$difference = New-TimeSpan -Start \$startdate -End \$enddate  # should be 10 days (Monday .. Wednesday)
\$days = \$difference.Days

1..\$days | ForEach-Object {
\$startdate