You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell Do-While无限循环中嵌套IF条件满足不执行问题

问题根因
  • 时间变量仅初始化一次:你将$Time、$Month、$Day、$DayName等时间相关变量全部定义在Do-While循环外部,仅在脚本启动时获取了一次当前时间,后续循环全程复用启动时的旧值,自然无法检测到后续时间变化触发对应条件。
  • 逻辑运算符优先级错误:PowerShell中-and的优先级高于-or,你现有的31天/30天月份判断逻辑不符合预期。以31天月份判断为例,实际执行逻辑等效为:($Month -eq "August" -or ... -or $Month -eq "October") -or ($Month -eq "December" -and $Day -eq "31" -and ...),仅12月会校验日期和时间条件,其余31天月份完全没有绑定后续判断规则。
  • 字符串格式兼容性风险:使用-Format输出的字符串做判断,依赖系统语言环境,若系统默认语言不是英文,月份、星期的字符串返回值会和你判断的英文值不匹配,直接导致条件失效。
修复方案

将时间变量的获取移到循环内部,每次循环先拉取最新时间,同时调整逻辑运算符的括号优先级,建议直接使用DateTime对象的属性做判断,规避语言兼容问题:

$WShell = New-Object -com "Wscript.Shell"
$SleepTime = 10

DO{
    # 每次循环先获取最新时间
    $currentDate = Get-Date
    $Month = $currentDate.Month
    $Day = $currentDate.Day
    $DayName = $currentDate.DayOfWeek
    # 定义时间区间,避免字符串比较误差
    $checkStartTime = Get-Date -Hour 15 -Minute 30 -Second 0
    $checkEndTime = Get-Date -Hour 15 -Minute 49 -Second 0
    $workStartTime = Get-Date -Hour 8 -Minute 26 -Second 0
    $workEndTime = Get-Date -Hour 17 -Minute 14 -Second 0

    # 31天月份判断,用括号包裹月份or条件,保证优先级正确
    if (($Month -in 1,3,5,7,8,10,12) -and $Day -eq 31 -and $currentDate -gt $checkStartTime -and $currentDate -lt $checkEndTime )
    {
        "It's the end of a 31 day month, please save and submit your timesheets"
        Start-Process "Do something"
        Start-Sleep -Seconds $SleepTime
    }
    # 30天月份判断
    if (($Month -in 4,6,9,11) -and $Day -eq 30 -and $currentDate -gt $checkStartTime -and $currentDate -lt $checkEndTime )
    {
        "It's the end of a 30 day month, please save and submit your timesheets"
        Start-Process "Do something"
        Start-Sleep -Seconds $SleepTime
    }
    # 2月判断
    if ($Month -eq 2 -and $Day -eq 28 -and $currentDate -gt $checkStartTime -and $currentDate -lt $checkEndTime )
    {
        "It's the end of the month, please save and submit your timesheets"
        Start-Process "Do something"
        Start-Sleep -Seconds $SleepTime
    }
    # 周五判断
    if($DayName -eq "Friday" -and $currentDate -gt $checkStartTime -and $currentDate -lt $checkEndTime )
    {
        "It's the end of the week, please submit and save your timesheet"
        Start-Process "Do something"
        Start-Sleep -Seconds $SleepTime
    }
    # 工作时段判断
    if($currentDate -gt $workStartTime -and $currentDate -lt $workEndTime){
        "It's not the end of the week or month, no need to submit"
        Start-Process "Do something"
        Start-Sleep -Seconds $SleepTime
    }

    "testing while loop" 
    Start-Sleep -Seconds 5

}while($true)

内容的提问来源于stack exchange,提问作者Joseph Quaranta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 14:21:03