简单的函数,用于生成具有可定义长度的随机字母数字字符串

时间:2015-12-08 15:42:31

标签: windows function batch-file random

有人可以帮我创建一个dos函数来生成一个可以调用的随机字母数字字符串,例如

call :randomString output length

其中“output”是函数定义的新变量,“length”是输出基于的字符数?

3 个答案:

答案 0 :(得分:1)

你可以试试这个:

@echo off & setlocal EnableDelayedExpansion

call :randomString output 10
echo %output%
pause
exit /b

:randomString
set length=%2
set CHARS=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
echo %CHARS%>x&for %%? in (x) do set /a strlength=%%~z? - 2&del x
for /L %%a in (1 1 %length%) do (
set /a randnr=!random!%%!strlength!
for /l %%n in (!randnr! 1 !randnr!) do set "line=!line!!CHARS:~%%n,1!"
)
set %1=%line%
exit /b

答案 1 :(得分:1)

这种方法稍有不同,没有延迟扩展:

@echo off
setlocal

call :randomString output= 10
echo %output%
goto :EOF


:randomString output= length

set "charSet=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
set "charLen=62"

set "%1="
for /L %%i in (1,1,%2) do (
   call set /A "rand=%%random%% %%%% charLen"
   call call set "%1=%%%%%1%%%%%%%%charSet:~%%rand%%,1%%%%"
)
exit /B

答案 2 :(得分:1)

使用相同子字符串方法的另一个答案,旨在允许生成更复杂的字符串以满足一系列需求,而不仅仅是 x 长度的字母数字。包括帮助文件和使用示例。

@echo off

(Set \n=^^^

%= \n macro newline variable. Do not modify =%)

::#---------------------------------------------------------------------------------------------------
::#| $rStr Args:         Description:
::#|
::#|  /L Int            : Length of each Substring [MANDATORY] - At least one length must be supplied.
::#|  /L Int Int Int    : Varying Lengths may be provided for each Substring
::#|                      by supplying the length for the corresponding iteration.
::#|                      /R Iterations is defined as the number of lengths provided.
::#|   /Mod Int IntSum  : Supply a Range for a Random Length at provided Index.
::#|                       - Example: Two part string Part 1 = 5 characters, Part 2 = 7-15 characters:
::#|                          /L 5 .  /Mod :0 9+7 /D :
::#|                         - OVERIDES /L 5 . TO /L 5 [RandomInt 7-15]
::#|                       * Modifier value should be at same index of /Mod SubArgs as '.' is in /L:SubArgs
::#|                         - Use 0 values for Modifier list to retain /L lengths at original index.
::#|
::#|  /R Int            : Number of Iterations to repeat pattern as an Integer
::#|                      - Use /R when all Iterations of pattern are to be same /L length
::#|
::#|  /V ReturnVar      : Define Supplied returnvar with generated String
::#|                          - If no return var is supplied, value will be stored in $rStr_RV
::#|
::#|  /A ReturnVar      : Append generated string to supplied return variable.
::#|
::#|  /P Pattern Subargs:
::#|     - Predefined   : ANM - English Letters in Upper and Lower case + 0~9 [DEFAULT]
::#|                    : ANL - English Letters in Lower case + 0~9
::#|                    : ANU - English Letters in Upper case + 0~9
::#|                    : AL  - English Letters in Lower case
::#|                    : AU  - English Letters in Upper case
::#|                    : N   - 0~9
::#|                    : H   - Hex String: ABCDEF0123456789
::#|
::#|     - Range        : Character Range  - Provide a range to use as the Character Set.
::#|                       - Example:     /P [3-w] = 3456789abcdefghijklmnopqrstuvw
::#|                       - Range Order: 0-9a-zA-Z ; Total Available Range: 0-Z
::#|
::#|     - Custom       : Character String - provide a custom string of characters to use.
::#|                       - Example:     /L 3 3  /P "-+@$^&()" /S 6 /D -
::#|
::#|  /S Int            : Supply the length of a Custom Pattern.
::#|
::#|  /D "Delim"        : Delim Character to use.
::#|  /D "Delim Delim"  : Supply Multiple Delims ; inserted after each corresponding iteration.
::#|  Delim Substitution: The following characters require substitution to use:
::#|                      - {FS} for / Forward-Slash ; {SC} for ; Semicolon
::#|                      - {AS} for * Asterisk      ; {CM} for , Comma
::#|                      - {EQ} for = Equals
::#|
::#|  /B Delim Delim    : Bookend the string with the supplied pair of Delims.
::#|
::#|  /O                : Output the Generated string to STDOUT
::#|
::#---------------------------------------------------------------------------------------------------

:# $rStr Switches. Defined outside macro for readability and maintainance.
 Set $rStr[Switches]="V" "A" "P" "L" "S" "R" "D" "O" "Mod" "B" "Rep"

 Set $rStr=For %%n in (1 2)Do if %%n==2 (                                          %\n: CAPTURE ARG STRING =%
  For /F "Tokens=1,2 Delims==" %%G in ('Set "$rStr_" 2^^^> nul')Do Set "%%~G=" %\n: RESETS ALL MACRO INTERNAL VARS =%
  (If not "!$rStr[args]:/?=!"=="!$rStr[args]!" (mode 160,80^&For /F "Tokens=1,2* Delims=#" %%G in ('findstr.exe /BLIC:"::#" "%~f0"')Do Echo(%%H))%\n%
  If not "!$rStr[args]:* /=!" == "!$rStr[args]!" (                              %\n: BUILD $rStr.Args[!$rStr_arg[i]!] ARRAY IF ARGS PRESENT =%
   Set "$rStr_leading.args=!$rStr[args]:*/=!"                                  %\n: SPLIT ARGS FROM SWITCHES =%
   For /F "Delims=" %%G in ("!$rStr_leading.args!")Do Set "$rStr_leading.args=!$rStr[args]:/%%G=!"%\n%
   Set ^"$rStr[args]=!$rStr[args]:"=!"                                          %\n: REMOVE DOUBLEQUOTES FROM REMAINING ARGSTRING - SWITCHES =%
   Set "$rStr_arg[i]=0"                                                            %\n: ZERO INDEX FOR ARGS ARRAY =%
   For %%G in (!$rStr_leading.args!)Do (                                           %\n: BUILD ARGS ARRAY =%
    Set /A "$rStr_arg[i]+=1"%\n%
    Set "$rStr_arg[!$rStr_arg[i]!]=%%~G"%\n%
    For %%i in ("!$rStr_arg[i]!")Do (                                              %\n: SUBSTITUTE THE FOLLOWING POISON CHARACTERS =%
     Set "$rStr_arg[%%~i]=!$rStr_arg[%%~i]:{FS}=/!"%\n%
     Set "$rStr_arg[%%~i]=!$rStr_arg[%%~i]:{AS}=*!"%\n%
     Set "$rStr_arg[%%~i]=!$rStr_arg[%%~i]:{EQ}==!"%\n%
     Set ^"$rStr_arg[%%~i]=!$rStr_arg[%%~i]:{DQ}="!"%\n%
  ))) Else (                                                                        %\n: IF NO ARGS REMOVE DOUBLEQUOTES FROM ARGSTRING - SWITCHES =%
   Set ^"$rStr[args]=!$rStr[args]:"=!"%\n%
  )%\n%
  For /L %%L in (2 1 4)Do If "!$rStr_LastSwitch!" == "" (%\n%
   If "!$rStr[args]:~-%%L,1!" == " " Set "$rStr_LastSwitch=_"%\n%
   If "!$rStr[args]:~-%%L,1!" == "/" (                                              %\n: FLAG LAST SWITCH TRUE IF NO SUBARGS ; FOR SWITCHES UP TO 3 CHARCTERS LONG =%
    For /F "Delims=" %%v in ('Set /A "%%L-1"')Do Set "$rStr_Switch[!$rStr[args]:~-%%v!]=true"%\n%
    If not "!$rStr[args]:/?=!." == "!$rStr[args]!." Set "$rStr_Switch[help]=true"%\n%
    Set "$rStr[args]=!$rStr[args]:~0,-%%L!"%\n%
    Set "$rStr_LastSwitch=_"%\n%
  ))%\n%
  For %%G in ( %$rStr[Switches]% )Do If not "!$rStr[args]:/%%~G =!" == "!$rStr[args]!" (%\n: SPLIT AND ASSIGN SWITCH VALUES =%
   Set "$rStr_Switch[%%~G]=!$rStr[args]:*/%%~G =!"%\n%
   If not "!$rStr_Switch[%%~G]:*/=!" == "!$rStr_Switch[%%~G]!" (%\n%
    Set "$rStr_Trail[%%~G]=!$rStr_Switch[%%~G]:*/=!"%\n%
    For %%v in ("!$rStr_Trail[%%~G]!")Do (%\n%
     Set "$rStr_Switch[%%~G]=!$rStr_Switch[%%~G]: /%%~v=!"%\n%
     Set "$rStr_Switch[%%~G]=!$rStr_Switch[%%~G]:/%%~v=!"%\n%
    )%\n%
    Set "$rStr_Trail[%%~G]="%\n%
    If "!$rStr_Switch[%%~G]:~-1!" == " " Set "$rStr_Switch[%%~G]=!$rStr_Switch[%%~G]:~0,-1!"%\n%
    If "!$rStr_Switch[%%~G]!" == "" Set "$rStr_Switch[%%~G]=true"%\n%
    If not "!$rStr_Switch[%%~G]!" == "" If not "!$rStr_Switch[%%~G]!" == "true" (%\n%
     Set "$rStr_Switch[%%~G]=!$rStr_Switch[%%~G]:{FS}=/!"%\n%
     Set "$rStr_Switch[%%~G]=!$rStr_Switch[%%~G]:{EQ}==!"%\n%
     Set ^"$rStr_Switch[%%~G]=!$rStr_Switch[%%~G]:{DQ}="!"%\n%
  )))                                                                                   %\n: ACTION SWITCH ASSESSMENT BELOW. =%
  If not "!$rStr_Switch[L]!" == "true" If not "!$rStr_Switch[L]!" == "" (%\n%
   For %%G in ( Switch[L] Switch[B] Switch[D] Switch[Mod] )Do If not "!$rStr_%%G!" == "true" If not "!$rStr_%%G!" == "" (%\n%
    Set "$rStr_%%G[i]=0"%\n%
    For %%H in (!$rStr_%%G!)Do (%\n%
     Set /A "$rStr_%%G[i]+=1"%\n%
     Set "$rStr_%%G[!$rStr_%%G[i]!]=%%H"%\n%
     For %%q in (Switch[B] Switch[D])Do if "%%q" == "%%G" (%\n%
      Set "rStr_dSub=%%H"%\n%
      Set "rStr_dSub=!rStr_dSub:{AS}=*!"%\n%
      Set "rStr_dSub=!rStr_dSub:{SC}=;!"%\n%
      Set "rStr_dSub=!rStr_dSub:{CN}=:!"%\n%
      Set "rStr_dSub=!rStr_dSub:{CM}=,!"%\n%
      Set "$rStr_%%G[!$rStr_%%G[i]!]=!rStr_dSub!"%\n%
     )%\n%
     If "%%G" == "Switch[Mod]" If not "%%H" == "0" Set /A "$rStr_Switch[L][!$rStr_%%G[i]!]=!random! %% %%H "%\n%
   ))%\n%
   If "!$rStr_Switch[P]!" == "" Set "$rStr_Switch[P]=ANM" %\n%
   If "!$rStr_Switch[P]!" == "true" Set "$rStr_Switch[P]=ANM" %\n%
   If /I "!$rStr_Switch[P]!" == "ANM" ( Set "$rStr_CharSet=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" ^& Set "$rStr_pSize=62" )%\n%
   If /I "!$rStr_Switch[P]!" == "ANU" ( Set "$rStr_CharSet=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" ^& Set "$rStr_pSize=36" )%\n%
   If /I "!$rStr_Switch[P]!" == "ANL" ( Set "$rStr_CharSet=abcdefghijklmnopqrstuvwxyz0123456789" ^& Set "$rStr_pSize=36" )%\n%
   If /I "!$rStr_Switch[P]!" == "AM" ( Set "$rStr_CharSet=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" ^& Set "$rStr_pSize=52" )%\n%
   If /I "!$rStr_Switch[P]!" == "AL"  ( Set "$rStr_CharSet=abcdefghijklmnopqrstuvwxyz" ^& Set "$rStr_pSize=26" )%\n%
   If /I "!$rStr_Switch[P]!" == "AU"  ( Set "$rStr_CharSet=ABCDEFGHIJKLMNOPQRSTUVWXYZ" ^& Set "$rStr_pSize=26" )%\n%
   If /I "!$rStr_Switch[P]!" == "N"   ( Set "$rStr_CharSet=1234567890" ^& Set "$rStr_pSize=10" )%\n%
   If /I "!$rStr_Switch[P]!" == "H"   ( Set "$rStr_CharSet=ABCDEF0123456789" ^& Set "$rStr_pSize=16" )%\n%
   If not "!$rStr_Switch[P]:*]=!" == "!$rStr_Switch[P]!" (%\n: facilitate custom P [start-end] Pattern Range =%
    For /F "Tokens=1,2 Delims=[-]" %%1 in ("!$rStr_Switch[P]!")Do (%\n%
     Set "$rStr_pSize="^& Set "$rStr_Start=%%1"%\n%
     For %%c in ( 0 1 2 3 4 5 6 7 8 9 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 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 )Do (%\n%
      If "%%c" == "%%1" (%\n%
       Set "$rStr_CharSet=%%c"%\n%
       Set "$rStr_pSize=0"%\n%
      )%\n%
      If "%%c" == "%%2" (%\n%
       Set "$rStr_CharSet=!$rStr_CharSet!%%c"%\n%
       Set "$rStr_Start="%\n%
       Set /A "$rStr_pSize+=1"%\n%
      )%\n%
      If not "!$rStr_CharSet!" == "%%c" If not "!$rStr_Start!" == "" (%\n%
       Set "$rStr_CharSet=!$rStr_CharSet!%%c"%\n%
       Set /A "$rStr_pSize+=1"%\n%
   ))))%\n%
   If "!$rStr_CharSet!" == "" (%\n%
    Set "$rStr_CharSet=!$rStr_Switch[P]!"%\n%
    If not "!$rStr_Switch[S]!" == "" If not "!$rStr_Switch[S]!" == "true" (Set "$rStr_pSize=!$rStr_Switch[S]!")%\n%
    If "!$rStr_pSize!" == "" (%\n%
     For /L %%i in (0 1 200) Do If "!$rStr_pSize!" == "" If "!$rStr_Switch[P]:~%%i,1!" == "" ( Set /A "$rStr_pSize=%%i-1" )%\n%
   ))%\n%
   If "!$rStr_Switch[R]!" == "" Set "$rStr_Switch[R]=!$rStr_Switch[L][i]!"%\n%
   If not "!$rStr_Switch[Rep]!" == "" (%\n%
    Set "$rStr_Switch[D]=!$rStr_Switch[D]:{SC}=;!"%\n%
    Set "$rStr_Switch[D]=!$rStr_Switch[D]:{CM}=,!"%\n%
    Set "$rStr_Switch[D]=!$rStr_Switch[D]:{AS}=*!"%\n%
    Set "$rStr_Switch[R]=!$rStr_Switch[Rep]!"%\n%
    For /L %%i in (1 1 !$rStr_Switch[R]!)Do (%\n%
     Set "$rStr_Switch[L][%%i]=!$rStr_Switch[L]!"%\n%
     Set "$rStr_Switch[D][%%i]=!$rStr_Switch[D]!"%\n%
     If "%%i" == "!$rStr_Switch[Rep]!" Set "$rStr_Switch[D][%%i]="%\n%
   ))%\n%
   For /L %%i in (1 1 !$rStr_Switch[R]!) Do (%\n%
    FOR /L %%n IN (1 1 !$rStr_Switch[L][%%i]!)Do (%\n%
     For /F "delims=" %%c In ( 'SET /A "!RANDOM! %% !$rStr_pSize!"' )Do (%\n%
      Set "$rStr_RV=!$rStr_RV!!$rStr_CharSet:~%%c,1!"%\n%
    ))%\n%
    Set "$rStr_RV=!$rStr_RV!!$rStr_Switch[D][%%i]!"%\n%
   )%\n%
   Set "$rStr_RV=!$rStr_Switch[B][1]!!$rStr_RV!!$rStr_Switch[B][2]!"%\n%
   If not "!$rStr_Switch[A]!" == "" (For /F "Delims=" %%v in ("!$rStr_Switch[A]!")Do Set "$rStr_RV=!%%v!!$rStr_RV!")%\n%
   If not "!$rStr_Switch[V]!" == "" ( Set "!$rStr_Switch[A]: =!=!$rStr_RV!" 2^> nul ) %\n%
   If not "!$rStr_Switch[V]!" == "" ( Set "!$rStr_Switch[V]: =!=!$rStr_RV!" 2^> nul ) %\n%
   If "!$rStr_Switch[O]!" == "true" Echo(!$rStr_RV!%\n%
   If "!$rStr_Switch[help]!" == "true" (For /F "Tokens=1,2* Delims=#" %%G in ('findstr.exe /BLIC:"::#" "%~f0"')Do Echo(%%H)%\n%
  )Else If not "!$rStr_Switch[Help]!" == "true" (Echo( /L Integer Required^^! )%\n%
 ) Else Set $rStr[args]=

:# load the macro from another script
If not "%~1" == "" Echo("%~1"|findstr.exe /IC:"/load" > nul && exit /B 0

:# Enable $rStr Macro
 Setlocal enableextensions enableDelayedExpansion
If not "%~1" == "" (
 %$rStr% %*
 exit /b
)

:# Usage Examples
:# {3xINT:10to24xINT-5xINT}
 %$rStr% /L 3 . 5 /Mod 0 10+15 0 /P N /B { } /D : - /V output1

:# append {7to15xLET;2xLET,7to15xLET} to {3xINT:10to24xINT-5xINT} to get: {3xINT:10to24xINT-5xINT}{7to15xLET;2xLET,7to15xLET}
 %$rStr% /L . 2 . /Mod 7+9 0 3+4 /P AM /B { } /D {SC} {CM} /A output1

:# 4xHEX;4xHEX;4xHEX
 %$rStr% /L 4 /Rep 3 /P H /D {SC} /V output2

:# character range example: [3x[3-f]-3x[3-f]-3x[3-f]-3x[3-f]-3x[3-f]]
 %$rStr% /L 3 /Rep 5 /P [3-f] /B [ ] /D - /V output3

 Set output
 Timeout /T 2 /Nobreak > nul
 pause
 CLS

:# custom character set example - 'maze box' . Supply size of pattern using /S Integer
 %$rStr% /l 25 /p - /O /S 1
 For /L %%i in (1 1 12)Do %$rStr% /l 23 /P + x  . /B "| |" /O /S 6
 %$rStr% /l 25 /p - /O /S 1

 Timeout /T 2 /Nobreak > nul
 pause
 CLS

:# Show help
 %$rStr% /?
Goto :Eof