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.
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.
[ == ] (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.
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.
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.
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"
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With