Easily generate random strings in pure batch script
Using pure native Batch, this script generates random strings of any length and using any characters except ! % ^ & < >. This script should work on all Windows operating systems from XP onwards.
The code is pretty self-explanatory, so here goes:
@echo off
setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
:: This is used to specify the required length of the random string
set len=12
:: This specifies the characters that will be used to generate the random string
set charpool=0123456789ABCDEF
:: This specifies the length of the character pool above used to generate the string
set len_charpool=16
set gen_str=
:: Loop %len% times
for /L %%b IN (1, 1, %len%) do (
:: %RANDOM% / !RANDOM! is replaced with a random variable between 0 and 32768
:: This is used as our source of randomness so we use some simple math to
:: restrict the random range to be within the length of len_charpool
set /A rnd_index=!RANDOM! * %len_charpool% / 32768
:: Use for to allow us to expand and use the variable with batchs substring
:: functionality, and append the substring at the random index determined above
:: to the gen_str variable. See set /? for more information.
for /F %%i in (echo %%charpool:~!rnd_index!^,1%%) do set gen_str=!gen_str!%%i
)
:: The random string has been generated and stored in %gen_str%
echo %gen_str%
Heres a screenshot of the script in operation: