set /p codename="Please enter the codename! "
if exist %codename% = Candy, Sugar, Lollipop (
echo The code you entered is not available.
)
如果用户输入的 %codename% 如 Candy、Sugar 或 Lollipop 等,有没有办法让回声说“您输入的代码不可用”,然后暂停蝙蝠?
如果用户输入除这三个之外的任何其他内容,脚本将继续工作。
我怎样才能做到这一点?
答案1
您可以使用多个字符串来验证用户输入findstr
:
echo/%codename% |%__APPDIR__%findstr.exe "Candy Sugar Lollipop" >nul && goto :Next
1)echo/%codename%
(字符串输入)至findstr
(查找字符串),
2)使用/i
不区分大小写如果需要,如果不需要,删除/i
3)如果匹配,goto :next
标签...如果没有,将执行下一行...
4)向用户显示回显/您的消息和超时,等待用户按任意键
5)goto :EOF
(文件结束),与 exit/abort/quit 你的 bat 相同。
@echo off & setlocal
set /p codename="Please enter the codename! "
echo/%codename% |%__APPDIR__%findstr.exe "Candy Sugar Lollipop" >nul && goto :Next
echo/The code you entered is not available^!! & %__APPDIR__%timeout -1 & goto :EOF
:Next
rem :: your code continue here...`
- 观察。如果用户仅输入回车,您可以限制这一点:
if !_cnt! equ 3
@echo off & setlocal EnableDelayedExpansion
:loop
set /p codename="Please enter the codename! "
set /a "_cnt+=1+0"
if !_cnt! equ 3 (
echo/Maximum number of attempts allowed exceeded^!!
goto :Error ) else if "!codename!"=="" goto :loop
echo/!codename! |%__APPDIR__%findstr.exe "Candy Sugar Lollipop" >nul && goto :Next
:Error
echo/The code you entered is not available^!! & %__APPDIR__%timeout -1
endlocal & goto :EOF
:Next
rem :: your code continue here...
答案2
如果存在,则变量内容的比较形式是错误的。正确的形式应该是:
If "%variable%"=="desired value" (command)
如果要对任何给定的允许值执行相同的命令,则可以使用如下 for 循环:
For %%A In (Candy,Sugar,Lollipop) Do (
If /I "%codename%"=="%%A" (
Call :CodeTrue
)
)
作为脚本末尾的函数
:CodeTrue
Pause
Rem other commands
Exit /b
答案3
如果你可以转到 PowerShell:
$NewName = Read-host -Prompt 'Please enter the codename!'
If ($NewName -in ('Candy', 'Sugar', 'Lollipop') ) { echo 'The code you entered is not available.'}
PS C:\> $NewName = Read-host -Prompt 'Please enter the codename!'
>> If ($NewName -in ('Candy', 'Sugar', 'Lollipop') ) { echo 'The code you entered is not available.'}
Please enter the codename!: Candy
The code you entered is not available.
PS C:\>
您需要真正的环境变量吗?
$NewName = Read-host -Prompt 'Please enter the codename!'
If ($NewName -in ('Candy', 'Sugar', 'Lollipop') ) {
echo 'The code you entered is not available.'
}
Else {$env:CodeName = $NewName} # only exists within scope of procesd
or
Else {[Environment]::SetEnvironmentVariable("CodeName", $NewName, "User")} # Persistant at user-level
or (Requires Admin PowerShell Console. Not avaiable to creating process.)
Else {[Environment]::SetEnvironmentVariable("CodeName", $NewName, "Machine")} # Persistant at machine-level