Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
747 views
in Technique[技术] by (71.8m points)

command line - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...