您只是忘记在使用它们时将变量包装在% 中。
但是,您最好使用将 SET 命令包装在 " 中的良好做法
另外,你可以通过使用选择来简化你的生活,尽管仍然有可能让选择出错,所以 YMMV
:EditUser
cls
echo.You chose to edit a user
echo.========================
echo.1. Change Password
echo.2. Change Account Type
echo.3. Go back to Users
echo.
set /p "CHOICE6=What do you want to do? "
IF %CHOICE6% EQU 1 goto :PassChange
IF %CHOICE6% EQU 2 goto :PrivChange
if %CHOICE6% EQU 3 goto :Users
goto :EditUser
也就是说,为了获得最佳实践,您应该使用 CALL 编写函数,并且您可以将选择变量返回到主代码以执行操作,或者在函数中作为最佳套件执行。
CALL 是“安全的”,因为它会在函数或脚本结束时返回到当前执行点,您可以更好地编写脚本。
REM Example main function
:Main
REM ...
REM Call Edit User, Specify a variable name to be returned
CALL :EditUser "CALL_THIS"
REM Call the function we chose in the :Edit User Function and was returned to us here, and may be :PassChange, :PrivChange, :Users
CALL %CALL_THIS%
REM ...
GOTO :EOF
:EditUser
REM Clear the Variable Provided to the fucntion to be returned
SET "%~1="
REM Clear the Choice
SET "CHOICE6="
cls
echo.You chose to edit a user
echo.========================
echo.1. Change Password
echo.2. Change Account Type
echo.3. Go back to Users
echo.
CHOICE /C 123 /N /M "What do you want to do? "
SET "CHOICE6=%ERRORLEVEL%"
REM Check an arbitrary number of choices without having to write a full IF on each.
FOR %%_ IN (
1:PassChange
2:PrivChange
3:Users
) DO (
REM Split choices to test them:
FOR /F "Tokens=12 Delims=:" %%A (
IF %%A EQU %CHOICE6% (
REM Set The Variable given the function '%1' to a value to return to Main script when the Choice was matched.
SET "%~1=:%%B"
)
)
REM Exit Function when %~1 is defined.
IF DEFINED %~1 GOTO :EOF
)
REM Show screen again when not matched
GOTO :EditUser
是的,还有更多代码,但正如您现在所看到的,您有一个可重用的函数,可以根据您的代码要求任意多次调用,并允许外部代码在另一个函数或主代码中执行下一个调用功能。
但即使在您不需要调用另一个函数的地方,您也可以使用此处的循环逻辑来存储选项列表并评估它们,而无需重新键入所有 if 语句。
此外,您也可以更通用地编写它,并且没有任何多项选择变量每次都将选择函数逻辑重新用作可调用函数,并允许您编写更少重复且占用空间更小的代码。