ad

Sunday, 3 January 2016

Decision making if/else in batch programming

Decision making's very important in any programming, not just batch. It allows your program to decide what to do. Here we're going to create a small program where it asks user for password and allows of denies access depending on whether password's right or not.

Here's if statement structure in batch
if CONDITION (
    do this
) else (
   do this
)

To compare two numbers we use double equal signs '=='. Lets ask our program if 1 is equal to 2.
if 1 == 2 (
   echo 1 is equal to 2
) else (
   echo 1 is not equal to 2
)

It returns whatever we put in else because 1 is obviously not equal to 2.

Here's our complete script where
1. Turn command display off
2. Get user input and store it in password variable
3. Use if/else statement you just learned. It will only allow access if password is 'webdevtown', anything else it wil echo 'access denied'.
4. Pause so program doesn't exit.

@echo off
SET /p name="Please enter password "
if %name%==webdevtown (
  echo Access granted
) else (
  echo Access deinied
)
pause


access denied



No comments:

Post a Comment