首页 > 解决方案 > 基于时间的while循环

问题描述

我一直在尝试让 while 和 If 循环正确读取时间,但是在正确的时间到来时它不会结束程序。我尝试使用单引号''和双引号"",以及不同的语法(如 ( -eq, -match, -ne) 来查看其中任何一个是否有效......但它们没有。

程序目标:循环直到到达上午 07:00

# While the value is 1.
while ($value -ne 2)
{   
    # Value should be 1 in order to stay in loop.
    $value = 1

    # Get's the time in 24hr format
    $time = get-date -Format HH:mm:ss

    # For Debugging; Writes out Time
    Write-Output $time

    # Creates a Pop-Up Windows that prevents the computer from timing out; runs every 15 minutes.
    $wshell = New-Object -ComObject Wscript.Shell

    $wshell.Popup("Operation Completed",0,"Done",0x1)

    # Causes the Program to wait to send the Enter Keystroke.
    Sleep 4

    # Sends the Enter Keystroke.
    $wshell.sendkeys('~')

    # Causes the Program to wait to send the Enter Keystroke in seconds (900sec = 15 Minutes).
    Sleep 4

    # If Condition; If the time is over 2am then the program quits.
    If ($time -eq "02:03:00")
    {
        # While Loop End Condition
        $value = 2

        # "Debugging Output"
        Write-Output $value
        Write-Output $time
    }

    Else
    {
        # While Loop Condition
        $value = 1

        # "Debugging Output"
        Write-Output $value
        Write-Output $time
    }
}

# "Debugging Output"
Write-Output "End"
Write-Output $time
Write-Output $value

标签: powershell

解决方案


您的 if 语句成为真的可能性非常低。因为您的 while 循环至少需要 8 秒(2x Start-Sleep 和其他工作)秒才能重新开始。这意味着 $time 变量可能永远不会正好是 02:03:00。在这种情况下,我不会去确切的时间。相反,我会检查它是否是 02:03:00 或更晚。试试看:

$time = Get-Date

if ($time -ge (Get-Date -Hour 02 -Minute 03 -Second 00))
{
}

推荐阅读