batch-file - 问两个问题时,有没有更好的方法来执行这个选择命令序列?
问题描述
我的问题是关于命令的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
解决方案
只是提取选择部分。在这里,我使用了 2 种方法。一个是创建标签ch1
,并ch2
告诉选择命令转到哪里ch%errorlevel%
,在这种情况下,errorlevel 将是1
或2
。
第二个使用通常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
推荐阅读
- javascript - React + Firebase - 处理非规范化数据
- node.js - 如何让@babel/register 转译 ESM 导入?
- php - 如何将 .HAR/ JSON 文件转换为可读的 .txt 文件?(提取 youtube 实时聊天)
- mysql - 慢查询和proxysql
- javascript - webpack 多项目编译成一个项目
- tizen - 由于“证书链无效,签名中的证书错误”,我无法在 Tizen 模拟器中安装我的应用程序
- api - 在 Angular 通用服务器端使用 jsPDF 创建 PDF
- java - 启动 apache nifi 时出现绑定异常
- laravel - 如何对多个批次使用 then() 回调?
- python - 如何在python中只找到信号的“尖峰”?