gpt4 book ai didi

powershell - 基于时间的while循环

转载 作者:行者123 更新时间:2023-12-03 00:59:12 25 4
gpt4 key购买 nike

我一直在尝试使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

最佳答案

这种情况应该可以起作用:

if ((Get-Date) -gt (Get-Date -Hour 7 -Minute 0 -Second 0)) {
# While Loop End Condition
$value = 2
# more actions
}

它将当前时间与当前日期的 DateTime对象进行比较,但是时间设置为 07:00:00

请记住两件事:
  • 它将允许循环仅在午夜至7AM之间运行。如果要在调整条件的前一天启动脚本。
  • 不使用if,但将条件直接放在while()中,这样可能会更具可读性:

  • while ((Get-Date) -lt (Get-Date -Hour 7 -Minute 0 -Second 0)) {
    # do something
    }

    目前,您正在检查确切的时间,因此从理论上讲可能会满足最终条件。但是,如果它在前后一秒到达该特定行,则不会停止循环。

    关于powershell - 基于时间的while循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58374102/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com