Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
706 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 Answer

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...