如果存在則使用 SET

如果存在則使用 SET
 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 :nextlabel...如果沒有,將執行下一行...

4)回顯/您的訊息和超時顯示給用戶,等待用戶按任意鍵

5)goto :EOF(文件結尾),與退出/中止/退出你的蝙蝠相同。


@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

相關內容