在Powershell中获取假期的最后一个工作日

时间:2017-12-26 16:54:35

标签: powershell

我有以下Powershell脚本可以正常工作以获得最后的业务/工作日,但是我试图考虑(美国)假期。可以通过改进以下脚本来完成吗?

$DateOffset = If ((get-date).dayofweek.value__ -eq 1) {-3} Else {-1}

2 个答案:

答案 0 :(得分: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

假期列表可以来自任何地方。

答案 1 :(得分:0)

在计算工作日时,假期很难处理。我使用来自scriptAlan 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