Reputation: 83
I'm a beginner in batch programming. I want to create a batch script in order to create a random sequence of eight alphanumeric characters. This is my tentative:
@echo off
setlocal enabledelayedexpansion
::Initializing uppercase alphabet
set "upper=A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"
set cntu=0 & for %%P in (!upper!) do (
set /a cntu+=1
set "upper[!cntu!]=%%P"
)
::Initializing lowercase alphabet
set "lower=a b c d e f g h i j k l m n o p q r s t u v w x y z"
set cntl=0 & for %%P in (!lower!) do (
set /a cntl+=1
set "lower[!cntl!]=%%P"
)
::Initializing numbers
set "numbers=0 1 2 3 4 5 6 7 8 9"
set cntn=0 & for %%P in (!numbers!) do (
set /a cntn+=1
set "numbers[!cntn!]=%%P"
)
::Initializing something...
for /L %%P in (0 1 8) do (
set /a rndIntp=%random% %% 2
if %rndIntp% == 0 (
set /a rndIntu=%random% %% cntu +1
set /a psw[!%%P!]=upper[%rndIntu%]
)
if %rndIntp% == 1 (
set /a rndIntl=%random% %% cntl +1
set /a psw[!%%P!]=upper[%rndIntl%]
)
if %rndIntp% == 2 (
set /a rndIntn=%random% %% cntn +1
set /a psw[!%%P!]=upper[%rndIntn%]
)
)
pause
What's wrong? How can I outupt the created sequence? Thank you!
Upvotes: 1
Views: 3415
Reputation: 785
You can do this with a slight modification to Stephan's elegant solution:
@echo off
setlocal enabledelayedexpansion
set "string=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
set "result="
for /L %%i in (1,1,%1) do call :add
echo %result%
goto :eof
:add
set /a x=%random% %% 62
set result=%result%!string:~%x%,1!
goto :eof
Save it, run it and pass the length of the random string you want:
RandomString.bat 10
Output:
yxfcK6rGWv
Edit: Updated solution based on refined requirements:
@echo off
setlocal enableextensions enabledelayedexpansion
set "string=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
set "upper=ABCDEFGHIJKLMNOPQRSTUVWXYZ"
set "numeric=0123456789"
set /a rand1=%random% %% 4
set /a rand2=rand1 + 4
set "result="
set /a index = 0
for /L %%i in (1,1,8) do (
if !index!==%rand1% (
call :addUpper
) else if !index!==%rand2% (
call :addNumeric
) else (
call :addAny
)
set /a index += 1
)
echo %result%
pause
goto :eof
:addUpper
set /a u=%random% %% 26
set result=%result%!upper:~%u%,1!
goto :eof
:addNumeric
set /a n=%random% %% 10
set result=%result%!numeric:~%n%,1!
goto :eof
:addAny
set /a s=%random% %% 62
set result=%result%!string:~%s%,1!
goto :eof
Upvotes: 2