Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "SET /P" inside an IF statement

I'm creating a batch to turn my laptop into wifi an make my life easier to type lines in cmd each time.

The trouble is the wifi name always get set to key= insted of the one which I enter.

Here is what I did:

@echo OFF
set /p option="Enter 1 to create wifi, Enter 2 to stop wifi "
IF %option% EQU 1 (
    set /p id="Enter wifi Name:"
    set /p key="Set password:"
    netsh wlan set hostednetwork mode=allow ssid = %id% key = %key%
    netsh wlan start hostednetwork
)

IF %option% EQU 2 (
netsh wlan set hostednetwork mode=disallow
)

timeout /t 5
like image 312
Basic Bridge Avatar asked Jul 11 '13 19:07

Basic Bridge


People also ask

How do you use SET P command?

The /P switch allows you to set a variable equal to a line of input entered by the user. The Prompt string is displayed before the user input is read. The Prompt string can be empty. The variable name can also be left empty but this is undocumented.

What does set P do?

set /p allows to have the user enter a value and assign it to a environment variable. The new line that echo writes can be piped into set /p to echo text without new lines.

How to assign value to a variable in command prompt?

2.2 Set/Unset/Change an Environment Variable for the "Current" CMD Session. To set (or change) a environment variable, use command " set varname=value ". There shall be no spaces before and after the '=' sign. To unset an environment variable, use " set varname= ", i.e., set it to an empty string.


2 Answers

While you shouldn't have any spaces between the switch and the equal sign, or the equal sign and the parameter, the real culprit is because you're using SET /P inside the IF statement.

To correct this, you'll need to do two things:

  1. Add Setlocal EnableDelayedExpansion to the top of your batch file, after the @ECHO OFF statement (so that the variables in the IF block can be expanded at execution time).

  2. Since we're now using EnableDelayedExpansion, call all your variables using !! instead of %%, such as:

    netsh wlan set hostednetwork mode=allow ssid=!id! key=!key!

like image 100
LittleBobbyTables - Au Revoir Avatar answered Sep 28 '22 17:09

LittleBobbyTables - Au Revoir


Got the solution

@echo off

echo What You What To Do ?
echo 1 to create wifi
echo 2 to stop wifi

set /p input=
if %input%==1 goto 1
if %input%==2 goto 2

:1
cls
set /p name=Enter wifi name 
set /p pass=Enter wifi password 
echo Creating wifi with
echo Name = %name% 
echo Password = %pass%
netsh wlan set hostednetwork mode=allow ssid="%name%" key="%pass%"
netsh wlan start hostednetwork
timeout /t 5
exit;

:2
cls
netsh wlan set hostednetwork mode=disallow
exit;
timeout /t 5
like image 44
Basic Bridge Avatar answered Sep 28 '22 18:09

Basic Bridge