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

问题描述 投票:0回答:2

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

$DateOffset = If ((get-date).dayofweek.value__ -eq 1) {-3} Else {-1}
powershell
2个回答
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

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


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
© www.soinside.com 2019 - 2024. All rights reserved.