我是批处理脚本的新手,不明白为什么两位数的计算结果小于个位数?
%weekdayOffPeakEnd%变量在echo'd时为7。
我从 FOR 循环(未显示)中调用这个 sleepUntilOffPeak 函数,但我认为这没有任何影响,因为我在脚本的其他任何地方都没有使用此函数中的任何变量。此功能只是检查当前小时并"休眠",直到电费再次降低。
感谢
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
)
)
)
你有很多这样的例子:
if Hour LSS weekdayOffPeakEnd (
这会将文字Hour
与文字weekdayOffPeakEnd
进行比较
你需要
if %Hour% LSS %weekdayOffPeakEnd% (
此外,如果您更改代码块(括号代码)中任何变量的值,则需要使用调用delayed expansion
!var!
检索更改的值(使用search
查找许多 SO 项)
另外,您观察到set /a var=07
会将变量设置为7
,而不是07
。了解set /a
和set
之间的区别很重要。set /a
解析要分配的值,然后将该值作为字符串分配给变量,取消前导零。set
分配文本,包括前导零。
这会导致两个后果。首先,以0
开头的值由set/a
分配为八进制值,因此08
和09
将无效。其次,if %var% op val
将尝试将运算符的两个参数转换为数字以执行比较,如果两个转换都成功,则比较将作为数字比较执行,否则将作为字符串比较执行,其中字符从左侧串行匹配。