How to use random in BATCH script?
How to use random in BATCH script?
Solution 1:
%RANDOM%
gives you a random number between 0 and 32767.
Using an expression like SET /A test=%RANDOM% * 100 / 32768 + 1
, you can change the range to anything you like (here the range is [1…100] instead of [0…32767]).
Solution 2:
%RANDOM% gives you a random number between 0 and 32767.
You can control the number's range with:
set /a num=%random% %%100
- will produce number between 0~99.
This one:
set /a num=%random% %%100 +1
- will produce number between 1~100.
Solution 3:
You'll probably want to get several random numbers, and may want to be able to specify a different range for each one, so you should define a function. In my example, I generate numbers from 25 through 30 with call:rand 25 30
. And the result is in RAND_NUM
after that function exits.
@echo off & setlocal EnableDelayedExpansion
for /L %%a in (1 1 10) do (
call:rand 25 30
echo !RAND_NUM!
)
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
Solution 4:
@echo off & setLocal EnableDelayedExpansion
for /L %%a in (1 1 100) do (
echo !random!
)