@Echo Off
:: Generates semi-random alphanumeric character, upper/lower case A-z and 0-9
Setlocal EnableDelayedExpansion
Set _Alphanumeric=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
[COLOR=DarkRed]Set _count=0
:_loop
Set /a _count+=1[/COLOR]
SET _RND=%Random%
:: Use (Number of characters-1) as the [COLOR=Blue]mod operand[/COLOR]. So for just 26 letters use 25 instead of 61
Set /A _RND=_RND%%[COLOR=Blue]61[/COLOR]
SET _rndalphanum=!_Alphanumeric:~%_RND%,1!
Echo Random character is !_rndalphanum!
[COLOR=DarkRed]If !_count! leq 21 goto _loop
[/COLOR]
The red lines are just to make it loop and output 20 characters at a time so you can see what it will generate.
@Echo Off
Setlocal EnableDelayedExpansion
[COLOR=Blue]Set _RNDLength=8[/COLOR]
[COLOR=DarkRed]Set _Alphanumeric=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789[/COLOR]
Set _Str=%_Alphanumeric%987654321
:_LenLoop
IF NOT "%_Str:~18%"=="" SET _Str=%_Str:~9%& SET /A _Len+=9& GOTO :_LenLoop
SET _tmp=%_Str:~9,1%
SET /A _Len=_Len+_tmp
Set _count=0
SET _RndAlphaNum=
:_loop
Set /a _count+=1
SET _RND=%Random%
Set /A _RND=_RND%%%_Len%
SET _RndAlphaNum=!_RndAlphaNum!!_Alphanumeric:~%_RND%,1!
If !_count! lss %_RNDLength% goto _loop
Echo Random string is !_RndAlphaNum!
I've modified it so you can easily specify the length, and add or remove characters without having to change any other part of the code.
For example, you might not want to use both 0 and O (zero and Uppercase O), or 1 and l (one and lowercase L)
You can use punctuation except for these characters: ! % ^ & < >
You can use ^ and %, but must enter them in the _Alphanumeric variable twice as ^^ or %%. However, if you want to use the result (_RndAlphaNum) later in the batch file (other than Echoing to the screen), they might require special handling.
You can even use a space, as long as it's not the last character in the string. If it ends up as the last character in the generated string though, it will not be used, so you would only have 7 characters.
The length of the resulting string is set by the Set _RNDLength=8 line. As long as you don't change that, or add a space or the 6 punctuation characters (! % ^ & < >) indicated to the Set _AlphaNumeric= line, it will always be 8.
Jerry
Status
Not open for further replies.
You have insufficient privileges to reply here.
Related Threads
?
?
?
?
?
Tech Support Guy
9.9M posts
859.7K members
Since 1998
A forum community dedicated to tech experts and enthusiasts. Come join the discussion about articles, computer security, Mac, Microsoft, Linux, hardware, networking, gaming, reviews, accessories, and more!