Powershell |仅在每月的第一个星期四运行

时间:2020-04-21 15:13:44

标签: powershell

完全不确定从哪里开始。非常卡住。尝试了一些类似于This Post

的事情

这个想法是,如果它是本月的第一个星期四,则继续进行其他操作。

1 个答案:

答案 0 :(得分:5)

您可以执行以下操作:

$d = Get-Date # Get Current Date
# Check if today is Thursday and the day number is less than 8
if ($d.DayOfWeek -eq 'Thursday' -and $d.Day -lt 8) {
    "First Thursday"
}
else { 
    "Not First Thursday"
}

您可以通过创建一个函数来使其更加动态,以便您可以输入任何日期和星期几。

function Check-FirstDay {
    param([datetime]$Date,[DayOfWeek]$DayOfWeek)

    if ($Date.DayOfWeek -eq $DayOfWeek -and $Date.Day -lt 8) {
        "It is first $DayOfWeek"
    }
    else {
        "It is not first $DayOfWeek"
    }
 }

使用该功能的示例:

# Example when it is not first Tuesday
$d = Get-Date
$d
Check-FirstDay -Date $d -DayOfWeek Tuesday

# Output
Tuesday, April 21, 2020 11:32:45 AM
It is not first Tuesday

# Example when it is first Thursday
$d = (Get-Date).AddDays(16)
$d
Check-FirstDay -Date $d -DayOfWeek Thursday

# Output
Thursday, May 7, 2020 11:35:34 AM
It is first Thursday

在2020年10月1日(星期四)进行测试:

$d = Get-Date -Month 10 -Year 2020 -Day 1
Check-FirstDay -Date $d -DayOfWeek Thursday

# Output
It is first Thursday