user1926152
user1926152

Reputation: 235

Batch file - using multiple IF's to separate

I am writing a batch script what i am looking for is something so that multiple hings be compared with each other

for example i have to look into folders to check what all files are there if there are following files

  abc.wxs
  verify.wxs
  start.wxs
  myname.wxs

i want to go to

 makeadmin

else if there are

  abc.wxs
  verify.wxs
  start.wxs
  myname.wxs
  verifyme.wxs
  abc.dll

i have written some thing like

IF EXIST "abc.wxs" (
IF EXIST "verify.wxs" (
IF EXIST "start.wxs" (
IF EXIST "myname.wxs" (
goto makeadmin
) else (
echo 1
 )
 ) else (
 echo 2
)
) else (
echo 3
)    
) else (
echo 4
)

Now how do i integrate the second part

Upvotes: 0

Views: 132

Answers (1)

Leajian
Leajian

Reputation: 129

You can do this with a "checking buffer". I mean each file will count +1 to the check variable. Now, if the sum matches the number of checked files it would do something specific. Take a look below :

@echo off
set sum=0

IF EXIST "abc.wxs" (
set /a sum=%sum%+1
)
IF EXIST "verify.wxs" (
set /a sum=%sum%+1
)
IF EXIST "start.wxs" (
set /a sum=%sum%+1
)
IF EXIST "myname.wxs" (
set /a sum=%sum%+1
)
IF EXIST "verifyme.wxs" (
set /a sum=%sum%+1
)
IF EXIST "abc.dll" (
set /a sum=%sum%+1
)

if sum==4 (
set sum=0
goto makeadmin
)
if sum==6 (
set sum=0
<insert whatever you want here>
)

pause

Generally, I find it quite useful to use counters with numbers. It's much more convenient for me. I hope it helps.

P.S. I am setting sum=0 on each case of the 2 "if"s because I haven't tested this (cause I am on linux right now) and I am afraid that if you return to the beginning of the program, you'll going to have the sum over-exceed the number 6.

EDIT
The above can be shortened and made easier to maintain by using a FOR loop. Also, the set sum=0 is not needed within the IFs. Finally, variables do not need to be expanded within SET /A. set /a sum=sum+1 works, as does set /a sum+=1

@echo off
set sum=0
for %%F in (
  abc.wxs
  verify.wxs
  start.wxs
  myname.wxs
  verifyme.wxs
  abc.dll
) do if exist %%F set /a sum+=1
if sum==4 goto makeadmin
if sum==6 REM do something else

Upvotes: 2

Related Questions