在Powershell中获取假期的最后一个工作日
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在Powershell中获取假期的最后一个工作日相关的知识,希望对你有一定的参考价值。
我有以下Powershell脚本,可以正常工作,以获得最后的业务/工作日,但我试图考虑(美国)假期。可以通过改进以下脚本来完成吗?
$DateOffset = If ((get-date).dayofweek.value__ -eq 1) -3 Else -1
答案
你可以这样做:
function Get-LastBusinessDay
[CmdletBinding()]
param (
[Parameter(Position = 1)]
[System.DateTime]$Date = [System.DateTime]::Today,
[Parameter(Position = 2)]
[System.DateTime[]]$Holidays
);
$Weekends = @([System.DayOfWeek]::Saturday, [System.DayOfWeek]::Sunday);
$LastBusinessDay = $Date.AddDays(-1);
while (($LastBusinessDay.DayOfWeek -in $Weekends) -or ($LastBusinessDay.Date -in $Holidays))
$LastBusinessDay = $LastBusinessDay.AddDays(-1);
return $LastBusinessDay;
$HolidayTable = @(
# 2018 US Federal Holidays
'January 1, 2018',
'January 15, 2018',
'February 19, 2018',
'May 28, 2018',
'July 4, 2018',
'September 3, 2018',
'October 8, 2018',
'November 12, 2018',
'November 22, 2018',
'December 25, 2018'
);
Get-LastBusinessDay -Date '2018-12-26' -Holidays $HolidayTable
# Returns December 24
Get-LastBusinessDay -Date '2018-09-04' -Holidays $HolidayTable
# Returns Aug 31
假期列表可以来自任何地方。
另一答案
在计算工作日时,假期很难处理。我使用来自script的Alan Kaplan that pulls holidays from TimeAndDate.com任何一年和任何国家作为PowerShell对象。
有了它,应该很容易根据需要调整计算。
#Example. Get US National Holidays for 2015, display in two columns with Holiday and Date with day.
$holidays =Get-Holidays 2015
#$holidays now is an object with the holidays for 2015, which you can manipulate
$holidays | where $_.type -like "National Holiday" |
select @Name="Holiday"; Expression = $_.holidayName, @Name="Date"; Expression = Get-Date($_.date) -format D |
ft -AutoSize
以上是关于在Powershell中获取假期的最后一个工作日的主要内容,如果未能解决你的问题,请参考以下文章