I recommend switching to PowerShell 2.0, where you will be able to use the Get-Random Cmdlet across the full range of integers. Either that, or write a simple program in another language just to generate the random number, and then call it from your batch file.
You can do this to get a random number between 10000 and 999999:
set /a rnd=(((%random% * 32768) + %random%) %%990000) + 10000
It's not perfectly uniform, but may be good enough for your purposes.
Given the question title, perhaps you're actually looking for a number between 100000 and 999999 (i.e. 5 or 6 digits). In this case you could use this:
set /a rnd=(((%random% * 32768) + %random%) %%900000) + 100000
Unlike the approach using addition, this uses two random numbers (one for the higher-order bits and one for the lower-order bits), which should give a uniform distribution between 0 and 1073741823; the non-uniformity comes from the wrap-around you get from the modulus (%%) operation. You could avoid this, too, if you used a loop and rejected any candidate random values above 1073700000 (=900000 * 1193).
:: Generate linear random number into variable %1
:: length is %2 digits
:: maxvalue %3 (optional. string of %2 9s if omitted)
:: minval %4 (optional, 0 if omitted)
:: to set minval but not maxval, use "" as %3
IF NOT DEFINED $digits GOTO :EOF
IF DEFINED $maxval GOTO maxvalset
IF "!$maxval:~%2!"=="" GOTO maxvallp
IF NOT DEFINED $minval SET /a minval=0
IF "!$minval:~%2!"=="" GOTO minvallp
SET /a $count=%2
SET /a $digit=%RANDOM%
IF %$digit% gtr 32759 GOTO getdigit
SET /a $digit=%$digit:~-1%
SET /a $count-=1
IF %$count% gtr 0 GOTO getdigit
IF "%$chosen%" gtr "%$maxval%" GOTO minvalset
IF "%$chosen%" lss "%$minval%" GOTO minvalset
IF %$chosen:~0,1%==0 IF %$chosen% neq 0 SET "$chosen=%$chosen:~1%"&GOTO slzlp
Here's a routine that will generate a random number with linear distribution of any length with maximum and minimum.
Its use expects some intelligence on the part of the user. Sure - asking for a number between 0 and 99 then adding 1 will be a whole lot faster than asking for a number between 1 and 100. It's also not bullet-proof and assumes the parameters with which it is provided are valid.
Each step is trivial - the variable names and labels should provide appropriate clues to their purpose. In essence, a string of random digits of the appropriate length is built and discarded if out-of-range. The magic number 32759 is chosen to make sure that the random number chosen as a basis for the digits generated are 0..32759 which will yield a linear distribution mod 10 assuming the random number generator is linear.
Asked in February 2016Viewed 3,832 timesVoted 11Answered 2 times