批处理脚本:双位数小于单位数

时间:2018-01-24 21:25:30

标签: batch-file numbers compare

我是批处理脚本的新手,并且不明白为什么双位数的评估值低于单个数字?

回显时,

%weekdayOffPeakEnd%变量为7。

我在FOR循环中调用了这个sleepUntilOffPeak函数(未显示),但我认为没有任何影响,因为我不在脚本中的任何其他位置使用此函数的任何变量。此功能只检查当前小时并“休眠”,直到电费再次低。

THX

rem if not currently off-peak hours, wait (timeout) until electricity rates are lowest
:sleepUtilOffPeak
rem set DayofWeek and Hour variables
for /f %%a in ('wmic path win32_localtime get DayOfWeek /format:list ^| findstr "="') do (set %%a)
for /f %%a in ('wmic path win32_localtime get Hour /format:list ^| findstr "="') do (set %%a)
rem echo Day of week^: %DayOfWeek%
echo Hour^: %Hour%

rem set OffPeak variables
set /a weekdayOffPeakEnd=07
echo weekdayOffPeakEnd^: %weekdayOffPeakEnd%
set /a weekdayOffPeakStart=23
set /a weekendOffPeakEnd=15
set /a weekendOffPeakStart=19

set weekday=true
if "%DayOfWeek%" EQU "0" set weekday=false
if "%DayOfWeek%" EQU "6" set weekday=false
rem echo weekday^: %weekday%

if %weekday% equ true (
    echo Today is a weekday
    if Hour LSS weekdayOffPeakEnd (
        echo %Hour% is less than off-peak end^:  %weekdayOffPeakEnd%. Returning...
        exit /B 0
    ) else (
        if Hour GEQ weekdayOffPeakStart (
            echo %Hour% is greater than or equal to off-peak start^: %weekdayOffPeakStart%. Returning...
            exit /B 0
        ) else ( rem Hour is between 07 and 23
            rem sleep until offPeak then return
            set /a sleepTime=23-%Hour%
            set /a sleepSeconds=%sleepTime%*3600
            echo Going to sleep for %sleepSeconds% seconds
            timeout /t %sleepSeconds%
            exit /B 0
        )
    )
) else ( rem weekday equ false
    echo Today is a weekend
    if Hour LSS weekendOffPeakEnd (
        echo %Hour% is less than off-peak end^: %weekendOffPeakEnd%. Returning...
        exit /B 0
    ) else (
        if Hour GEQ weekendOffPeakStart (
            echo %Hour% is greater than or equal to off-peak start^: %weekendOffPeakStart%. Returning...
            exit /B 0
        ) else ( rem Hour is between 15 and 19
            rem sleep until offPeak then return
            set /a sleepHours=%weekendOffPeakStart%-%Hour%
            echo sleepHours^: %sleepHours%
            set /a sleepSeconds=%sleepHours%*3600
            echo Going to sleep for %sleepSeconds% seconds
            timeout /t %sleepSeconds%
            echo All done sleeping. Returning...
            exit /B 0
        )
    )
)

1 个答案:

答案 0 :(得分:1)

你有很多这样的例子:

if Hour LSS weekdayOffPeakEnd (

这会将文字Hour与文字weekdayOffPeakEnd

进行比较

你需要

if %Hour% LSS %weekdayOffPeakEnd% (

此外,如果更改 代码块(带括号的代码)中任何变量的值,则需要检索已更改的值使用!var!调用delayed expansion(使用search查找多个SO项目)

另外,您发现set /a var=07会将变量设置为7,而不是07。了解set /aset之间的区别非常重要。 set /a解析要分配的值,然后将该值作为字符串分配给变量,从而抑制前导零。 set指定包含前导零的文字。

这会导致两种后果。首先,0set/a分配的值为 OCTAL 值,因此0809 无效。第二,if %var% op val将尝试将运算符的两个参数转换为数字以执行比较,如果两个转换成功,则执行比较作为数字比较,否则它作为字符串比较执行,其中字符从左边串行匹配。