5

A slightly late Happy New Year to everyone, hope you had a good one.

I'm trying to create a batch file that will take keyboard input and then either launch a program based on that input or display an error message if the option entered isn't valid. But it's not working. Here's what I've got so far:

ECHO OFF
set /p %environment%=Connect to Live or Dev?:

IF %environment% = "Live" 
(
C:\Windows\System32\runas.exe /user:live\someuser /netonly "C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\ManagementStudio\Ssms.exe"
) 
ELSE IF %environment% = "Dev" 
(
C:\Windows\System32\runas.exe /user:dev\someuser /netonly "C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\ManagementStudio\Ssms.exe"
) 
ELSE 
(
ECHO "Invalid Option"
)

I've tried it with and without the % round the variable but it didn't work. Can anyone point me in the right direction?

Hope you can help.

Cheers

Alex

1
  • remove the @echo off to see what happens: 1) look, how your if-line is translated. 2) the ( has to be on the same line than the if 3) ) else ( has to be on one line Commented Jan 10, 2014 at 9:49

2 Answers 2

14

Here's some code to get you in the right direction. I tested this with a .cmd file in Windows 7.

ECHO OFF
SET /p environment="Connect to Live or Dev?"
IF /i "%environment%" == "Live" GOTO live
IF /i "%environment%" == "Dev" GOTO dev
ECHO Invalid Option
GOTO end
:live
ECHO "Live!!!!"
goto end
:dev
ECHO "Dev!!!"
:end
PAUSE
Sign up to request clarification or add additional context in comments.

Comments

7
ECHO OFF
set /p "environment=Connect to Live or Dev?:"

IF "%environment%"=="Live" (
    ....
) ELSE IF "%environment%"=="Dev" (
    ....
) ELSE (
    ....
)

1 - In set command, the name of the variable on the left side of equal sign does not use % signs. %var% sintax is used to retrieve the value of the variable.

2 - The operator to test for equality is == or EQU (see if /?)

3 - In the IF command, the same quoting should be applied to both sides of the equality operator. If not, values will not be considered equals

4 - The commands / block to execute when the IF command condition is true, must start in the same line that the IF, so starting parenthesis can not be in the next line

5 - The ELSE must continue the IF block and precede the start of its own block. Close parenthesis of the IF and starting parenthesis of the ELSE must be in the same line.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.