How can I use multiple conditions in “If” in batch

2020-05-27 07:10发布

Can I specify multiple conditions with "or"/"and" in batch file if block?

If not that complex, can I at least use something like:

if value1 < value < value2

Basically my purpose is to check whether current system time falls in a certain interval(2.05 AM and 7.55 AM to be precise) and if it does, to execute certain commands.

3条回答
来,给爷笑一个
2楼-- · 2020-05-27 07:26

You can break your condition into 2 and use if and if for setting 2 conditions

if %value% GTR %value1% (
echo Value is greater that %value1% ) else call :Error
if %value% LSS %value2% (
echo Value is less than %value2% ) else call :Error
::Write your Command if value lie under specified range
exit

:Error
echo Value doesn't lie in the range 
::Write your command for if value doesn't lie in the range
exit
查看更多
▲ chillily
3楼-- · 2020-05-27 07:45

Adding to dbenham's answer, you can emulate both logical operators (AND, OR) using a combination of if and goto statements.

To test condition1 AND codition2:

    if <condition1> if <condition2> goto ResultTrue

:ResultFalse
REM do something for a false result
    goto Done

:ResultTrue
REM do something for a true result

:Done

To test condition1 OR codition2:

    if <condition1> goto ResultTrue
    if <condition2> goto ResultTrue

:ResultFalse
REM do something for a false result
    goto Done

:ResultTrue
REM do something for a true result

:Done

The labels are of course arbitrary, and you can choose their names as long as they are unique.

查看更多
三岁会撩人
4楼-- · 2020-05-27 07:49

There are no logic operators in batch. But AND is easy to mimic with two IF statements

if value1 lss value if value lss value2 REM do something

Batch IF statements don't know how to compare times. Batch IF knows how to compare integers and strings.

One option is to convert the times into minutes or seconds past midnight.

The other option is to format the time with both hours, minutes (and seconds if needed) to be 2 digits wide each (0 prefixed as needed). The hours should be 24 hour format (military time).

查看更多
登录 后发表回答