从批处理脚本中的变量中减去数字

时间:2017-12-20 14:20:13

标签: batch-file subtraction

我是批处理脚本的新手,所以请对这个问题保持宽容。当我从' TodayDay'中减去1时变量,值不会更新。以下是该行。

set /a "TodayDay=%TodayDay%-1"

我的用例是查找今天的日期是否小于“lastOpenedDate'变量,我想设置' lastOpenedDate'昨天的

set lastOpenedDate=2017-12-22
IF %TodayYear%-%TodayMonth%-%TodayDay% LSS %lastOpenedDate% (   
  echo Before Subtraction TodayDay is %TodayDay%
  set /a "TodayDay=%TodayDay%-1"
  echo After Subtraction TodayDay is %TodayDay%
)

当我运行上面的代码时,输​​出是:

Before Subtraction TodayDay is 20
After Subtraction TodayDay is 20

我从下面提到的代码中获得了其他变量值

for /F "skip=1 delims=" %%F in ('
    wmic PATH Win32_LocalTime GET Day^,Month^,Year /FORMAT:TABLE
') do (
    for /F "tokens=1-3" %%L in ("%%F") do (
        set TodayDay=0%%L
        set TodayMonth=0%%M
        set TodayYear=%%N
    )
)
set TodayDay=%TodayDay:~-2%
set TodayMonth=%TodayMonth:~-2%

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您需要使用delayed expansion的顶部栏搜索SO。这是#1 FAQ。

变化

  set /a "TodayDay=%TodayDay%-1"
  echo After Subtraction TodayDay is %TodayDay%
)

  set /a "TodayDay=%TodayDay%-1"
)
echo After Subtraction TodayDay is %TodayDay%

一旦您熟悉delayed expansion.

,这将是有意义的

现在你遇到的下一个问题(直到本月8日或9日才出现)是批处理领先0意味着“八进制”所以 - 你实际需要

  set /a "TodayDay=1%TodayDay%-1"
)
set "TodayDay=%TodayDay:~-2"
echo After Subtraction TodayDay is %TodayDay%

通过在日期编号前面加1字符串,将日期编号加100,然后您需要获取最后2个字符。