【问题标题】:why does my number comparing alway become true?为什么我的数字比较总是成真?
【发布时间】:2023-02-26 22:47:27
【问题描述】:

每当我运行脚本时,即使时间低于 12:03,它也总是像时间超过 12:03 一样运行,我不明白为什么。我想将一天中的时间与自动关机的设定时间进行比较,但它总是返回超过我设定的时钟的时间,即使它不是。

这是代码:

@echo off
timeout /t 30
:RunAgain
set HH=12
set MM=03

set ThisHour=%TIME:~0,2%
set ThisMinute=%TIME:~3,2%

echo time: %ThisHour%:%ThisMinute%

if ThisHour GEQ HH (
    echo Hour is over %HH%
    if ThisMinute GEQ MM (
        goto Shutdown
        
    ) ELSE (
        echo time is under %HH%:%MM%
        timeout /t 30
        goto RunAgain )
) ELSE (
    echo time is under %HH%:%MM%
    timeout /t 30
    goto RunAgain )

:Shutdown
echo Shutting down
pause

【问题讨论】:

  • 您可以使用 Windows 任务计划程序在特定时间关闭计算机。无需创建持续运行的脚本,循环直到达到特定时间。

标签: batch-file


【解决方案1】:

这里的问题是变量没有正确传递给 if 语句。

您可以将脚本更改为:

@echo off
timeout /t 30
:RunAgain
set /A HH=12
set /A MM=03

set /A ThisHour=%TIME:~0,2%
set /A ThisMinute=%TIME:~3,2%

echo time: %ThisHour%:%ThisMinute%

if %ThisHour% GEQ %HH% (
    echo Hour is over %HH%
    if %ThisMinute% GEQ %MM% (
        goto Shutdown
        
    ) ELSE (
        echo time is under %HH%:%MM%
        timeout /t 30
        goto RunAgain )
) ELSE (
    echo time is under %HH%:%MM%
    timeout /t 30
    goto RunAgain )

:Shutdown
echo Shutting down
pause

声明中的 /A 强制变量为 int。 然后将它们传递给 if 时,您应该将 %% 添加到变量中。

进行这些更改后,脚本将按预期工作:

screenshot output for less than 12

screenshot output for greater equal than 12

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多