Home > Enterprise >  Get previous workday (weekday) from today with Powershell
Get previous workday (weekday) from today with Powershell

Time:07-19

Every day I run script which downloads couple of files by ftp to lets say C:\files\ directory with names like:

sampl_position_20220714
sampl_position_20220715 
sample1_newposition_20220715

etc.

All files comes with timestamp and files generating only at workdays (all days except Saturday and Sunday). I need to get file which starts with sampl_position_ and last_workday from today

I know how to get next workday:

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

But failed to get last workday Spent couple of days trying to find solution but still couldnt get what I want (

Maybe someone could help me with that?

CodePudding user response:

# Get the most recent weekday preceding today's date
# (Mon-Fri, not holiday-aware)
$mostRecentWeekDay = 
  ($dt = Get-Date).AddDays(
    $(switch ($dt.DayOfWeek) { 'Monday' { -3 } 'Sunday' { -2 } default { -1 } })
  )

# Synthesize the file name
'sampl_position_{0:yyyyMMdd}' -f $mostRecentWeekday

Note: Despite the use of strings (e.g, 'Monday'), this solution is not culture-dependent. Because .DayOfWeek is of type [System.DayOfWeek], a comparison value of, say, 'Monday', is implicitly interpreted as the symbolic name of the equivalent enumeration value, [System.DayOfWeek]::Monday. You're free to use the latter instead, but it is obviously more verbose.

CodePudding user response:

Adding another answer that doesn't rely on names (names are language specific I think? sorry, monolingual here).

if(($date.DayOfWeek-1) -gt 0){$date.AddDays(-1)}else{$date.AddDays(-3-($Date.DayOfWeek-1))}

This checks to see if the previous day's day of week value is 1 or greater, if not jump back 3 days offset by the remaining days in the weekend from the day before. That sounds complicated, but I think I'm just explaining it poorly.

  • Related