有点奇怪。我一直在搞 Windows 批处理和时间比较来安排任务。现在我知道有一百万种更好的方法可以做到这一点,但是我们的工作机器相当锁定,因此批处理脚本似乎是真正实现我所需要的最简单的方法,而无需一些疯狂的解决方法。我也很清楚这背后的想法是相当恶心的。我在这里并不追求完美,我只是希望它能发挥作用。
基本上在11月23日17:00,我需要将文件从一个地方移动到另一个地方。问题是,由于其他一些 promise ,我当时实际上不会在场,所以我想出了一个批处理脚本,该脚本陷入了无循环状态,直到某个日期/时间起作用为止。因此,我在前一天晚上快速拼凑了以下内容:
:dateloop
if %date% LSS 23/11/2019 goto dateloop
:timeloop
if %time% LSS 17:00 goto timeloop
<xcopy operation goes here>
并运行了一夜。因此,想象一下,当我第二天早上来到我的机器前查看电子邮件并发现文件已被移动时,我会感到多么惊讶。值得庆幸的是,我能够恢复该文件并重新安排我的时间来手动执行此操作。
我昨晚运行了一些测试,确保脚本在完成后不会退出,以便我可以读取回显输出。事实证明,一切都运行良好,直到 2:00,此时脚本决定“是的,这是 17:00 之后”。
今晚我可以再次测试它,我确实计划这样做,时间格式写得很长(17:00:00:00),但我想知道是否有人可以在我之前确认,因为这是一个很好的离开时,这是否是我问题的原因?
最佳答案
如果您在命令提示符下键入 IF/?
,帮助文本将包含以下内容:
If Command Extensions are enabled IF changes as follows: IF [/I] string1 compare-op string2 command IF CMDEXTVERSION number command IF DEFINED variable command where compare-op may be one of: EQU - equal NEQ - not equal LSS - less than LEQ - less than or equal GTR - greater than GEQ - greater than or equal and the /I switch, if specified, says to do case insensitive string compares. The /I switch can also be used on the string1==string2 form of IF. These comparisons are generic, in that if both string1 and string2 are both comprised of all numeric digits, then the strings are converted to numbers and a numeric comparison is performed.
如您所见,比较是针对字符串进行的,除非要比较的字符串仅包含数字。由于时间包含非数字字符“:”和“.”,因此时间被视为字符串,当然“2”位于“17:00”中的“1”之后。
但是,使用命令 echo [%time%]
您会注意到,如果时间小于 10,它会在前面添加一个空格。因此,只要考虑到空格,就可以通过字符串比较得到正确的结果。因此,请用以下语句替换有问题的语句:
if "%time%" LSS "17:00" goto timeloop
这应该可以解决问题。
关于Windows Batch 认为凌晨 2 点是下午 5 点之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59017187/