Search code examples
batch-filedos

Need a line of Code that will spit out a random string of specified characters


I am working in notepad, and a need a line of code that will spit out a random line of characters (that I specify). I need to be able change the number characters also.

Can anyone help?


Solution

  • I'm really not sure what exactly you're asking, but maybe you want a batch file that spits out a line of random characters, and here's a script that will do that.

    Example output:

    C:\>rand_chars
    XF3KqsBIFzi
    C:\>rand_chars
    UNx1eQ8MebihmizfIjHT4gc7O85uIOxBk5u8xZj8pnBBOf0jSygII4kNx7IUJA8nMchRKl1f6sQgJjB
    

    Code:

    @echo off & setlocal EnableDelayedExpansion
    
    REM Change these values to whatever you want, or change the code to take them
    REM as command-line arguments.  You must set CHARS_LEN to the string length
    REM of the string in the CHARS variable.
    REM 
    REM This script generates a string of these characters at least
    REM MIN_CHARS_IN_LINE chars long and at most MAX_CHARS_IN_LINE chars long.
    
    SET CHARS=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
    SET /A CHARS_LEN=26 + 26 + 10
    SET /A MIN_CHARS_IN_LINE=5
    SET /A MAX_CHARS_IN_LINE=79
    
    REM Pick a random line length and output a random character until we reach that
    REM length.
    
    call:rand %MIN_CHARS_IN_LINE% %MAX_CHARS_IN_LINE%
    SET /A LINE_LENGTH=%RAND_NUM%
    
    SET LINE=
    for /L %%a in (1 1 %LINE_LENGTH%) do (
        call:rand 1 %CHARS_LEN%
        SET /A CHAR_INDEX=!RAND_NUM! - 1
        CALL SET EXTRACTED_CHAR=%%CHARS:~!CHAR_INDEX!,1%%
        SET LINE=!LINE!!EXTRACTED_CHAR!
    )
    echo !LINE!
    
    goto:EOF
    
    REM The script ends at the above goto:EOF.  The following are functions.
    
    REM rand()
    REM Input: %1 is min, %2 is max.
    REM Output: RAND_NUM is set to a random number from min through max.
    :rand
    SET /A RAND_NUM=%RANDOM% * (%2 - %1 + 1) / 32768 + %1
    goto:EOF