Using the dynamic variable %Random%, we can get a random integer from 0 to 32767. For example:

echo %random%

This obviously, returns an integer from 0 to 32767. But sometimes we want it to be in a specific range, say from 1 to 100.


Generating Random Numbers Within Specific Range

The basic method to do so is listed below.

set /a result=(%RANDOM%*max/32768)+min

where max is the top number that can be generated, and min is the smallest number that can be generated. Note that you will not get any decimal numbers because set /a rounds down automatically. To generate a decimal random number, try this:

set /a whole=(%RANDOM%*max/32768)+min
set /a decimal=(%RANDOM%*max/32768)+min
echo %whole%.%decimal%

Generating Random Numbers larger than 32767

If you try

set /a whole=(%RANDOM%*65536/32768)+1

you will most likely get random numbers that are odd.

To generate numbers larger than 32767, here is a better method.

set /a result=%random:~-1%%random:~-1%%random:~-1%%random:~-1%%random:~-1%%random:~-1%

The previous code extracts the 1 character from each %random%. But this is done on purpose.

Since the random number could be one digit number, extracting the last 2 digit won't work. That's why we extract only the last character. In this case, we have 6 %random:~-1%, generating the maximum of 999999, and the minimum at 000000, you may need to adjust this to suit your needs.

Pseudorandom

cmd.exe generate the seed based on the time the cmd section started, so if you start mutliple section at the nearly same time, the result may not be 'random' enough.