Reputation: 14256
I'm trying to write a script that prompts the user for a drive letter and then validate the entry insofar that it is a single character and falls within a valid range: D-Z
This is what I have so far:
setlocal enableextensions enabledelayedexpansion
set MIN_DRIVE_LOWER=d
set MAX_DRIVE_LOWER=z
set /P RELEASE_DRIVE="What is the assigned network drive letter on this workstation? "
echo Release drive is %RELEASE_DRIVE%
if /I !RELEASE_DRIVE! GEQ %MIN_DRIVE_LOWER% (
if /I !RELEASE_DRIVE! LEQ %MAX_DRIVE_LOWER% (
echo Release drive is lower-case.
)
)
No matter what I enter at the prompt my script reaches the "echo Release drive is lower-case.
" Any thoughts or suggestions would be much appreciated.
Upvotes: 0
Views: 571
Reputation: 24466
Here's a hacksy alternative. Rather than giving the user the freedom to screw up then punishing him for his insolence, you can enforce entry of a valid response with the choice
command. Then to avoid a long list of if errorlevel
conditions to convert the choice back to its alpha value, there's a trick using a special environment variable that converts ERRORLEVEL to an alphanumeric character, %=ExitCodeAscii%
. More details are here.
@echo off
setlocal
choice /c defghijklmnopqrstuvwxyz /n /m "What is the assigned network drive letter on this workstation? "
set /a ascii = %ERRORLEVEL% + 67
cmd /c exit /b %ascii%
set "letter=%=ExitCodeAscii%"
echo You chose %letter%
It's not clear what your goal is, whether the drive letter you want chosen is an existing letter or an unused letter for a drive mapping. Depending on your intentions, you might be interested in one or both of the following tips. *shrug*
You can programmatically determine what drive letters are currently assigned with a WMI query using wmic
:
wmic logicaldisk get deviceid /value | find "="
If you want to create a network drive mapping and would like to allow Windows to figure out which drive letter to assign automatically, use pushd
.
net use \\server /user:domain\username password
pushd \\server\share
... then to remove the mapping:
popd
net use \\server /delete
Upvotes: 2
Reputation: 6630
Why don't you try this:
@echo off
setlocal enableextensions enabledelayedexpansion
set /P rd="What is the assigned network drive letter on this workstation? "
echo Release drive is %rd%
:: Variable valid will be either 0 or 1
set valid=0
for %%a in (D E F G H I J K L M N O P Q R S T U V W X Y Z) do (
if /i "%rd%"=="%%a" (
set valid=1
if "%rd%" neq "%%a" set rd=%%a
)
)
Echo.
if "%valid%"=="1" (
Echo Valid Input Detected: %rd%
) else (
Echo Invalid Input: %rd%
)
pause
Edit: I made it so that it converted the character to upper-case too.
Upvotes: 1