当我们在Powershell中给出今天的日期时,以获得上个月的最后一个工作日 [英] To get the last working day of the previous month when we give today's date in Powershell

查看:196
本文介绍了当我们在Powershell中给出今天的日期时,以获得上个月的最后一个工作日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Powershell代码或批处理脚本中使用上个月的最后一个工作日创建一个文件夹

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

例如-如果我今天要运行一个日期为09/14/2017的批处理,则该文件夹应创建一个日期为08312017的日期

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

这是我的代码段

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

有人可以帮忙吗?

推荐答案

以下是作为可重用函数呈现的可能解决方案:

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')

该函数的工作方式是获取每个月最后7天的日期,过滤掉周六或周日中的任何一个,然后选择该列表中的第一个日期(这将是最新的).然后,它对所得的Date对象使用ToString方法将其转换为所需的字符串格式.

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.

这篇关于当我们在Powershell中给出今天的日期时,以获得上个月的最后一个工作日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆