Rob van der Woude's Scripting Pages

Batch How To ...

Generate Random Numbers

Using native commands only

This technique uses the hundredths of seconds from the time the command is executed as a more or less random number in the 0..99 range:

FOR /F "tokens=*" %%A IN ('VER ^| TIME ^| FINDSTR.EXE /R "[.,]"') DO FOR %%B IN (%%A) DO SET Random=%%B

Decide for yourself if this technique satisfies your random number requirements.
If used with user interaction it just might, if used in a program loop it probably won't!

 

Using external commands

PowerShell

Though PowerShell may be native in Windows since XP, by default it won't not run unrestricted on every computer, so check before using this technique!

The most basic form will generate a random 32-bit integer:

FOR /F %%A IN ('powershell.exe -Command "Get-Random"') DO SET Random=%%A

To generate a random integer in the 0..99 range:

FOR /F %%A IN ('powershell.exe -Command "Get-Random 99"') DO SET Random=%%A

or:

FOR /F %%A IN ('powershell.exe -Command "Get-Random -Maximum 99"') DO SET Random=%%A

To generate a random integer in the 1..100 range:

FOR /F %%A IN ('powershell.exe -Command "Get-Random -Minimum 1 -Maximum 100"') DO SET Random=%%A

 

Rexx

This technique requires Open Object Rexx and its rexxtry.rex script.

The most basic form will generate a random integer in the 0..999 range:

FOR /F %%A IN ('rexxtry say Random^( ^) ^| FINDSTR.EXE /R /C:"[0-9]"') DO SET Random=%%A

To generate a random integer in the 0..99 range, specify a maximum of 99:

FOR /F %%A IN ('rexxtry say Random^( 99 ^) ^| FINDSTR.EXE /R /C:"[0-9]"') DO SET Random=%%A

To generate a random integer in the 1..100 range, specify both minimum and maximum:

FOR /F %%A IN ('rexxtry say Random^( 1^, 100 ^) ^| FINDSTR.EXE /R /C:"[0-9]"') DO SET Random=%%A

The range (maximum minus minimum) should not exceed 999999999 (nine nines); hardly a show-stopper, I presume.

Don't forget to escape parentheses and commas.

 

Using scripts

Many scripting languages feature random number generation.
You can write a script in any of these languages to generate a random number, and use a FOR /F loop to capture its value.

A very basic VBScript example:

Randomize ' Initialize random-number generator
WScript.Echo Int( ( 6 * Rnd ) + 1 ) ' Random value in 1..6 range

Assuming the script is saved as random.vbs, the batch code to use this script would look like this:

FOR /F %%A IN ('CSCRIPT.EXE //NoLogo random.vbs') DO SET Random=%%A

 


page last uploaded: 2021-05-24, 18:18