首页 > 解决方案 > 问两个问题时,有没有更好的方法来执行这个选择命令序列?

问题描述

我的问题是关于命令的choice。我将一个嵌套在另一个中,因为我需要问一个问题,如果,则将用户添加到组中并问下一个问题add another user。但如果第一个问题的回答是否定的,我只想问另一个问题add another user

@echo off
setlocal enabledelayedexpansion
openfiles > NUL 2>&1
if NOT %ERRORLEVEL% EQU 0 goto NotAdmin
GOTO create
:NotAdmin
echo This command prompt is NOT ELEVATED
GOTO END

:create
set /p userName="Please enter a new user name to create:"
net user !userName! > NUL 2>&1
if  %ERRORLEVEL% EQU 0 GOTO ERROR
set /p Passwd="Please enter a password:"
set /p FullName="Please enter user's full name:"
net user !userName! !Passwd! /ADD /FullNAME:"!FullName!" > NUL 2>&1
if %ERRORLEVEL% EQU 0 (
    echo command completed succuessfully
) else (
    echo command did not compelte
)
choice /C yn /M "Would you like to add the user to the local Administrators group"
if ERRORLEVEL 2 (
    choice /C yn /M "Would you like to create another user "
    if ERRORLEVEL 2 (
        GOTO END
    )
    if ERRORLEVEL 1 (
        GOTO create
    )
 )
if ERRORLEVEL 1 (
    net localgroup Administrators !userName! /ADD
)
:ERROR
echo The user !userName! already exist
pause
GOTO create

:END

标签: batch-file

解决方案


只是提取选择部分。在这里,我使用了 2 种方法。一个是创建标签ch1,并ch2告诉选择命令转到哪里ch%errorlevel%,在这种情况下,errorlevel 将是12

第二个使用通常if errorlevel 1但没有第二个条件,因为如果第一个条件errorlevel 1不满足,它将落入goto end

choice /C yn /M "Would you like to add the user to the local Administrators group"
goto ch%errorlevel%
:ch1
echo add the user to the group here

:ch2
choice /C yn /M "Would you like to create another user "
if errorlevel 1 cls & goto create
goto end

推荐阅读