使用PowerShell获取一个月的最后一周的一天的日期

时间:2018-04-03 11:39:07

标签: powershell

如何使用PowerShell检索上个星期三的最后一个星期?

1 个答案:

答案 0 :(得分:0)

获取日期的快捷方式,例如本月的最后一个星期三可能是

# Day to match
$day = "Wednesday"   

# First, fetch the last day's date of the current month. 
# I.e. add one month to the current date and remove today's date from the date.
# 3.4.2018 + 1 month - 3 days = 30.4.2018
$lastDay = (Get-Date).AddMonths(1).AddDays(-$(Get-Date).AddMonths(1).Day)

# Next remove one weeks worth of days, one day at a time, 
# from $lastDay until the DayOfWeek is equals to Wednesday
# Finally, do something, e.g. write the date to the console.
1..7 | %{ if($lastDay.AddDays(-$_).DayOfWeek -eq $day) { `
    Write-Host $lastDay.AddDays(-$_) `
}}