Here's a similar idea, also using choice.exe
, but instead using mountvol.exe
for the drive letter enumeration, (instead of the slow, and now deprecated WMIC.exe
).
@Echo Off & SetLocal EnableExtensions DisableDelayedExpansion
Set "DrvList=" & For /F "Delims=: " %%G In ('%SystemRoot%\System32\mountvol.exe
^| %SystemRoot%\System32\findstr.exe /RC:"^ *[A-Z]:\\$"'
) Do Call Set "DrvList=%%DrvList%%%%G"
If Not Defined DrvList (Exit /B 1) Else Set "Selection="
If "%DrvList:~,1%" == "%DrvList%" Set "Selection=%DrvList%:"
If Defined Selection GoTo Selected
Echo Enter your drive letter here [%DrvList%]:
For /F "Tokens=2 Delims=?" %%G In ('
%SystemRoot%\System32\choice.exe /C %DrvList%') Do Set "Selection=%%G:"
:Selected
@Rem Place your commands below here, [%Selection% will be the drive letter].
Echo Your selected drive letter is %Selection%
Pause
The above code should auto select the drive letter, should only one be enumerated.
As a sidenote, based upon the seemingly random drive order output from mountvol.exe
, if you'd prefer the prompted order to be guaranteed alphabetical, you could use sort.exe
to order it.
@Echo Off & SetLocal EnableExtensions DisableDelayedExpansion
Set "DrvList=" & For /F "Delims=: " %%G In ('%SystemRoot%\System32\mountvol.exe
^| %SystemRoot%\System32\findstr.exe /RC:"^ *[A-Z]:\\$"
^| %SystemRoot%\System32\sort.exe') Do Call Set "DrvList=%%DrvList%%%%G"
If Not Defined DrvList (Exit /B 1) Else Set "Selection="
If "%DrvList:~,1%" == "%DrvList%" Set "Selection=%DrvList%:"
If Defined Selection GoTo Selected
Echo Enter your drive letter here [%DrvList%]:
For /F "Tokens=2 Delims=?" %%G In ('
%SystemRoot%\System32\choice.exe /C %DrvList%') Do Set "Selection=%%G:"
:Selected
@Rem Place your commands below here, [%Selection% will be the drive letter].
Echo Your selected drive letter is %Selection%
Pause