powershell - 基于时间的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
解决方案
您的 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))
{
}
推荐阅读
- css - 如何更改 Prime NG 的原色
- python - Python 从 CSV 完整地址分类并创建新列
- java - 字节数组到文件对象而不保存到磁盘
- javascript - 获取 TypeError:使用 API 测试用户添加时,用户不是构造函数
- python - 如何通过 tcp 从 python 向节点 js 发送 base64 编码图像?
- c# - Protobuf.net 如何使用 Any 数据类型?
- material-ui - Material-UI 主题 const 连接
- python - Django Rest Framework:如何使用 APIView 或 GenericAPIView 调用 check_object_permissions()
- unity3d - 我不能同时跳跃和移动 unity2d
- laravel - 未定义的属性:stdClass::$Blanch