Vijay Nag
Vijay Nag

Reputation: 267

If statement in Batch file gives error

The below simple steps in the batch script is giving me errors. It says

'else' is not recognized as an internal or external command,
operable program or batch file.
) was unexpected at this time.

Can some please help?

set var_machine64 = 0

if exist "C:\Program Files (x86)" ( set var_machine64 = 1 )

if !var_machine64! == 1 (
    If exist "C:\Program Files (x86)\Microsoft" (
        echo Microsoft folder not available 
        goto End ) ) 
else (
        If exist "C:\Program Files \Microsoft" (
        echo Microsoft folder not available 
        goto End ) )

:End
Exit

Upvotes: 0

Views: 1803

Answers (1)

Joey
Joey

Reputation: 354854

The else has to be on the same line where you close the last block, i.e. the ):

if !var_machine64! == 1 (
    If exist "C:\Program Files (x86)\Microsoft" (
        echo Microsoft folder not available 
        goto End
    )
) else (
    If exist "C:\Program Files\Microsoft" (
        echo Microsoft folder not available 
        goto End
    )
)

I took the liberty of fixing indenting and a superfluous space in a folder name as well.

This fixes your immediate problem of the syntax error but won't help since the batch file won't work anyway. You cannot use any whitespace around the = in set statements because otherwise you're creating a variable that ends in a space with a value that begins with one. So:

set var_machine64=0
if exist "C:\Program Files (x86)" ( set var_machine64=1 )

will make things work nicer. Also note that to use delayed expansion you need either setlocal enabledelayedexpansion before that in your batch file or start cmd with /v:on. I just guess you're not showing the whole file (which is ok, but given the error rate in this short snippet I'd say you should double-check everything else).

Random side note: It's not nice to include exit in a batch file because, when run from an interactive session it will kill it. If you just want to exit the batch file (and not the whole command processor with it) use exit /b or goto :eof.

Upvotes: 2

Related Questions