Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional statements in batch files

Tags:

batch-file

Is it possible to have conditional statements in batch scripts?

For example:

I have two servers, S1 and S2.When the batch file is deployed in S1 then the output should be generated in location L1. Likewise if the batch file is deployed in S2 then output should be generated in location L2.

My script:

set ComputerName=S1
set RepServer=%ComputerName%
set DBServer=%ComputerName%
set ReportPath="/DEV/Clearviewbilling"
set SharedPath=\\scottvdr1\ClearviewBilling\DEV-TEST
set UserId=-E
set fn=Create_Log.txt

if exist %fn% del %fn%
@echo on

@rem Reports
rs -i "%CD%"\Reports\Create_Sub.rss -s http://%RepServer%/reportserver -v Path=%SharedPath% -v rootpath=%ReportPath% -v DBServer=%DBServer% -t  >>  %fn% 2>&1

But i want the script to be:

set ComputerName=S1
set RepServer=%ComputerName%
set DBServer=%ComputerName%

If ComputerName=S1
Set SharedPath=//blah/blah
else
Set sharedPath=//some/path

set ReportPath="/DEV/Clearviewbilling"
set UserId=-E
set fn=Create_Log.txt

if exist %fn% del %fn%
@echo on

@rem Reports
rs -i "%CD%"\Reports\Create_Sub.rss -s http://%RepServer%/reportserver -v Path=%SharedPath% -v rootpath=%ReportPath% -v DBServer=%DBServer% -t  >>  %fn% 2>&1   

Hence when the file is deployed, the reports are generated in the required path. But this is not working.

like image 592
Iswarya Avatar asked Apr 08 '11 06:04

Iswarya


People also ask

Can you use if statements in batch files?

One of the common uses for the 'if' statement in Batch Script is for checking variables which are set in Batch Script itself. The evaluation of the 'if' statement can be done for both strings and numbers.

What is == in batch file?

[ == ] (Double Equals) The "IF" command uses this to test if two strings are equal: IF "%1" == "" GOTO HELP. means that if the first parameter on the command line after the batch file name is equal to nothing, that is, if a first parameter is not given, the batch file is to go to the HELP label.

How do you write an if statement in CMD?

If the condition specified in an if clause is true, the command that follows the condition is carried out. If the condition is false, the command in the if clause is ignored and the command executes any command that is specified in the else clause. When a program stops, it returns an exit code.

What MS DOS command is used to perform conditional functions in a batch file?

One of the most important capabilities of any programming language is the ability to choose from among different instructions based on conditions the program finds as it runs. For this purpose, the batch file language has the if command.


1 Answers

You compare the string ComputerName against S1 with the wrong if-else syntax

This should work

if "%ComputerName%"=="S1" (
    Set "SharedPath=//blah/blah"
) else (
    Set "sharedPath=//some/path"
)
like image 156
jeb Avatar answered Sep 18 '22 13:09

jeb