Ronak
Ronak

Reputation: 51

Compare Variable with multiple values in single If condition

I want to compare variable with multiple values with "OR" condition I batch script rather having multiple if logic.

@echo off

robocopy D:\SourceData E:\DestinationData

If %ErrorLevel% Equ 0 OR 1 OR 2 ( GoTo Success) Else ( GoTo Error)

:Success

Echo Robocopy completed successfully.
Pause
GoTo End

:Error

Echo Robo completed with some error/s.
Paude

:End
Exit

Upvotes: 2

Views: 1799

Answers (2)

Jean-François Fabre
Jean-François Fabre

Reputation: 140188

ERRORLEVEL is rarely < 0, so you could use:

if %errorlevel% LEQ 2 ( GoTo Success) Else ( GoTo Error)

...and for safety just in case:

if %errorlevel% LEQ -1 ( GoTo Error)

If your values were not consecutive you could just duplicate the if lines without the else (not very good but would work)

If you know all the possible values you can just do

goto branch%ERRORLEVEL%

and define

:branch0
:branch1
:branch2

...and so on.

(this is more or less directly lifted from IF online help, I learned a lot with the /? switch of commands like that)

Upvotes: 1

npocmaka
npocmaka

Reputation: 57252

If you want to compare the error level with a certain list:

for %%a in (1 2 3 whatever) do (
  if %errorlevel% equ %%a (
     goto :Success
  )
)
goto :error

Upvotes: 2

Related Questions