首页 > 解决方案 > Powershell - 嵌套 IF 在 Do-While 循环中无法正确执行

问题描述

我注意到,如果执行此脚本时存在正确的时间,它会在 Do-While 循环中正常运行。如果脚本启动时的时间不正确,它将永远停留在 while 循环中,并且永远不会重新检查 IF 语句。

我确实将它们作为 else-ifs,但将其更改为进行故障排除。不工作。

有谁知道为什么嵌套的 IF 语句在时间正确时不会执行,即使 do-while 设置为无限循环?

我知道实际的 IF 条件确实有效,并且我已经对其进行了测试。

该脚本正在测试它是否是 31 天月、30 天月、28 天月、星期五 arvo 以及一周中的任何一天下午 5 点之后的结束。

我想每 10 分钟检查一次这些条件,但您会看到我使用 5 秒进行测试

$WShell = New-Object -com "Wscript.Shell"
$Time=(Get-Date -Format HH:mm)
$Month=(Get-Date -Format MMMM)
$Day =(Get-Date -Format dd)
$Minute=(Get-Date -Format mm)
$DayName =(Get-Date -Format dddd)
$SleepTime = 10

DO{

if ($Month -eq "August" -or $Month -eq "January" -or $Month -eq "March" -or $Month -eq "May" -or $Month -eq "July" -or $Month -eq "October" -or $Month -eq "December" -and $Day -eq "31" -and $Time -gt "15:30" -and $Time -lt "15:49" )
{#for months with 31 days

"It's the end of a 31 day month, please save and submit your timesheets"
 Start-Process "Do something"
 Start-Sleep -Seconds $SleepTime
 
}
if ($Month -eq "April" -or $Month -eq "June" -or $Month -eq "September" -or $Month -eq "November" -and $Day -eq "30" -and $Time -gt "15:30" -and $Time -lt "15:49" )
{# for months with 30 days

"It's the end of a 30 day month, please save and submit your timesheets"
Start-Process "Do something"
Start-Sleep -Seconds $SleepTime

}
if ($Month -eq "February" -and $Day -eq "28" -and $Time -gt "15:30" -and $Time -lt "15:49" )
{#for February

"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 $Time -gt "15:30" -and $Time -lt "15:49" )
{# For Friday's

"It's the end of the week, please submit and save your timesheet"
Start-Process "Do something"
Start-Sleep -Seconds $SleepTime

}
if($Time -gt "08:26"-and $Time -lt "17:14"){

"It's not the end of the week or month, no need to submit"
Start-Process "Do something"
Start-Sleep -Seconds $SleepTime

}

#"is it time to do timesheets? Not yet"
#"Checking again in 10 Minutes"

"testing while loop" 

Start-Sleep -Seconds 5

}while($true)

标签: windowspowershellif-statementdo-while

解决方案


在开始 Do/While 循环之前,您只会获得一次日期/时间,因此日期/时间变量总是相同的。

您需要将以下内容移动到 Do 块中,以便这些变量在每个循环中随当前时间更新。

$Time=(Get-Date -Format HH:mm)
$Month=(Get-Date -Format MMMM)
$Day =(Get-Date -Format dd)
$Minute=(Get-Date -Format mm)
$DayName =(Get-Date -Format dddd)

推荐阅读