
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 などとして入力した場合、「入力したコードは利用できません」というメッセージをエコーして、バットを一時停止する方法はありますか?
ユーザーがこれら 3 つ以外のものを入力すると、スクリプトは引き続き動作します。
これどうやってするの?
答え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
(ファイルの終わり)、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
変数の内容を比較する場合、exist は間違った形式です。正しい形式は次のようになります。
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