获取上个月的最后一天,如果不是星期六,则将所有日期提前至星期六(包括周六)

时间:2016-09-02 02:19:04

标签: powershell

  1. 获取上个月的最后一天。
  2. 如果不是星期六(那个星期)那么从最后一天(无论是哪一天)获得所有日期,直到那周的星期六(以yyyymmdd格式)
  3. 例如:

    如果我在2016年9月7日和14日运行脚本,那么我的脚本应该首先找到上个月的最后一天,即20160831(星期三)。

    现在它应该让我知道从那一周的最后一天到周六(包括星期六)的所有日期

    20160901 20160902 20160903

    我会将每个日期存储在不同的变量中,以便稍后在脚本中使用。

    我已经想到了如何获得上个月的最后一天(格式正确),但我无法弄清楚如何获取从那天到周六的日期。

    这个脚本需要是动态的,因为我想安排它每个月运行一次。

    Param ([system.Datetime] $date = $(get-date)) $numdays = $date.Day $lastday = $date.AddDays(-$numdays) $lastday = $date.AddDays(-$numdays).DayOfWeek

2 个答案:

答案 0 :(得分:2)

# Get the first day of this month at midnight, and step back a day to the last day of the previous month
${Date Stepper} = (Get-Date -Day 1 -Hour 0 -Minute 0 -Second 0 -Millisecond 0).AddDays(-1)

# Step forward, one day at a time, output the last day of the month until the following Saturday
$Counter = 1
Do
{

    ${Date Stepper} = ${Date Stepper}.AddDays(1)
    Set-Item -Path "Variable:Var$Counter" -Value ${Date Stepper}.ToString("yyyyMMdd")
    $Counter++

} While ([System.DayOfWeek]::Saturday -gt ${Date Stepper}.DayOfWeek)

# Test Outputs
Write-Host "Var1 = $Var1"
Write-Host "Var2 = $Var2"
Write-Host "Var3 = $Var3"
Write-Host "Var4 = $Var4"
Write-Host "Var5 = $Var5"
Write-Host "Var6 = $Var6"
Write-Host "Var7 = $Var7"

答案 1 :(得分:1)

调整以下代码以满足您的需求。

function Get-PreviousMonthEndToSaturday
{
    [CmdletBinding()]
    param (
    [DateTime]
    $LookbackDate
    )

    $retDates = @()

    Write-Verbose "LookbackDate: $($LookbackDate.ToLongDateString())"

    # prior month
    $date = $LookbackDate.AddMonths(-1)
    # all months have 28 days
    $date = [DateTime]::new($date.Year, $date.Month, 28)

    # while in current month...
    while ($date.Month -eq $date.AddDays(1).Month)
    {
        $date = $date.AddDays(1)
    }

    # while day is not Sunday...
    while ($date.DayOfWeek -ne [System.DayOfWeek]::Sunday)
    {
        $retDates += $date
        $date = $date.AddDays(1)
    }

    # return desired dates
    return $retDates
}

Get-PreviousMonthEndToSaturday ([DateTime]::Now) -Verbose
Get-PreviousMonthEndToSaturday ([DateTime]::Parse("2016/7/15")) -Verbose
# April ends on a Saturday
Get-PreviousMonthEndToSaturday ([DateTime]::Parse("2016/5/3")) -Verbose

输出:

VERBOSE: LookbackDate: Thursday, September 1, 2016
Wednesday, August 31, 2016 12:00:00 AM
Thursday, September 1, 2016 12:00:00 AM
Friday, September 2, 2016 12:00:00 AM
Saturday, September 3, 2016 12:00:00 AM
VERBOSE: LookbackDate: Friday, July 15, 2016
Thursday, June 30, 2016 12:00:00 AM
Friday, July 1, 2016 12:00:00 AM
Saturday, July 2, 2016 12:00:00 AM
VERBOSE: LookbackDate: Tuesday, May 3, 2016
Saturday, April 30, 2016 12:00:00 AM