批处理文件:随机字母数字序列

时间:2017-10-04 20:26:46

标签: arrays batch-file random

我是批处理编程的初学者。我想创建一个批处理脚本,以便创建一个包含八个字母数字字符的随机序列。这是我的尝试:

@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

出了什么问题? 我怎样才能超越创建的序列? 谢谢!

1 个答案:

答案 0 :(得分:1)

您可以稍加修改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

保存,运行并传递所需随机字符串的长度:

RandomString.bat 10

输出:

yxfcK6rGWv

修改 根据改进的要求更新了解决方案:

@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