Irfan
Irfan

Reputation: 33

To get the last working day of the previous month when we give today's date in Powershell

I have a requirement to create a folder with last working day of the previous month in powershell code or batch script

for example - if I am running a batch today with the date 09/14/2017 then the folder should create a date with 08312017

here is my code snippet

filename.ps1

$MonthEndDate= ((get-date -day 1).adddays(-1)).ToShortDateString()

Monthenddate.bat

@echo on

FOR /F %%i IN ('powershell "%~dp0filename.ps1" //Nologo') do SET MYDATE=%%i
echo %MYDATE%

 MKDIR %MYDATE%

 :END

Can someone help on this please?

Upvotes: 1

Views: 1859

Answers (3)

user6811411
user6811411

Reputation:

Since there is always another alternative in PowerShell coding :

$LWDPM = (Get-Date -Day 1).AddDays(-1)
While (!([int]$LWDPM.DayOfWeek % 6)){$LWDPM=$LWDPM.AddDays(-1)}

  • of course LWDPM means LastWorkingDayPreviousMonth ;-)
  • The formula [int]$LWDPM.DayOfWeek % 6 returns zero for Sunday=0 and Saturday=6
  • the ! negates this, so while weekend .AddDays(-1)

Wrapped in a batch:

:: Q:\Test\2017\09\14\SO_46218430.cmd
@Echo off
For /f %%A in (
  'powershell -NoP -C "$DT=(Get-Date -Day 1).AddDays(-1);While (!([int]$DT.DayOfWeek %% 6)){$DT=$DT.AddDays(-1)};$DT.ToString(\"MMddyyyy\")"'
) do Set MyDate=%%A
Echo MyDate=%MyDate%

Sample output:

> SO_46218430.cmd
MyDate=08312017

Upvotes: 0

Mark Wragg
Mark Wragg

Reputation: 23355

Here's a possible solution presented as a reusable function:

Function Get-LastWorkingDayPrevMonth ($Date = (Get-Date)) {
    (-1..-7 | ForEach-Object { (Get-Date $Date -day 1).AddDays($_) } | Where-Object DayOfWeek -notin 'Saturday','Sunday') | Select -First 1
}

#Uses current date by default to return the last working day of the previous month
(Get-LastWorkingDayPrevMonth).ToString('ddMMyyyy')

#Based on specific date
(Get-LastWorkingDayPrevMonth 05/2017).ToString('ddMMyyyy')

The function works by getting the dates of the last 7 days of any month, filtering out any that are Saturday or Sunday and then selecting the first date in that list (which will be the latest). It then uses the ToString method on the resultant Date object to convert it to the string format you wanted.

Upvotes: 1

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

Use a do{}while() loop to subtract one day until the DateTime variable is not on a Saturday or Sunday:

# Define non-workdays
$weekend = [System.DayOfWeek]::Saturday,[System.DayOfWeek]::Sunday

# Get first day of current month
$date = Get-Date -Day 1
do{
    # Subtract one day
    $date = $date.AddDays(-1)
} while($weekend -contains $date.DayOfWeek) # until a weekday is reached

Upvotes: 0

Related Questions