Powershell获得每月的第n天
我有这个脚本,可以在互联网上找到该脚本来计算每个月的第三个星期二-但我需要对其进行修改,以简单地给我每个月的第7天,也可以是相同的天数,再加上任意天数).
I have this script which I found on the internet to calculate the third Tuesday of every month - but I need to modify it to simply give me the 7th day of the month, and the same but plus any number of days).
$FindNthDay=3
$WeekDay='Tuesday'
[datetime]$Today=[datetime]::NOW
$todayM=$Today.Month.ToString()
$todayY=$Today.Year.ToString()
[datetime]$StrtMonth=$todayM+'/7/'+$todayY
while ($StrtMonth.DayofWeek -ine $WeekDay ) { $StrtMonth=$StrtMonth.AddDays(1) }
$StrtMonth.AddDays(7*($FindNthDay-1))
$NextUpdate = $StrtMonth.AddDays(7*($FindNthDay-1))
我不理解这里的逻辑,我想我不需要$ Weekday.有任何想法吗?我想尽可能保留相似的结构和变量名,以使其与其他脚本保持一致.
I'm not understanding the logic here, I guess I don't need $Weekday. any ideas? I'd like to keep to the similar structure and variable names where possible in order to keep it consistent with the other scripts.
谢谢
这实际上还不错.
首先,让我们将指向今天日期的指针存储在变量中,我们将其称为$ date.
First, let's store a pointer to todays date in a variable, let's call it $date.
$date = Get-Date
接下来,我们需要确定月份中的数字天(如数字部分).我们可以使用 $ date.Day
.
Next, we'll need to figure out what numerical day of the month is (like the numerical portion of it). We can do that using $date.Day
.
$date.day
19
现在,让我们使用 .AddDays()
方法从日期中减去今天的日期,为我们提供指向月初的指针.
Now, let's use the .AddDays()
method to subtract today's date from the date, to give us a pointer to the first of the month.
$date.AddDays(-($date.Day-1))
>Thursday, September 1, 2016 11:46:36 AM
最后,我们可以将另一个 .AddDays()
链接到此长字符串的末尾,以向其中添加天数.对于您的情况,您想查找该月的第七天.我们将再增加六天来做到这一点.
Finally, we can chain another .AddDays()
to the end of this long string, to add the number of days to it that you'd like to. In your case, you'd like to find the seventh day of the month. We'll do that by adding six more days.
$date.AddDays(-($date.Day-1)).AddDays(6)
>Wednesday, September 7, 2016 11:48:15 AM