0

Trying to generate a random number and use it for variable value in Windows batch script file. Maybe I am missing something very basic, but something is not working here for me.

Created a batch file named random_test.bat with the following content.

SET rnumber=%random%
echo %random%
pause

Running the file consecutively three times produces the following set of outputs:

One

C:\Users\user\Desktop>SET rnumber=28955

C:\Users\user\Desktop>echo 20160
20160

C:\Users\user\Desktop>pause
Press any key to continue . . .

Two

C:\Users\user\Desktop>SET rnumber=29072

C:\Users\user\Desktop>echo 13887
13887

C:\Users\user\Desktop>pause
Press any key to continue . . .

Three

C:\Users\user\Desktop>SET rnumber=29183

C:\Users\user\Desktop>echo 18885
18885

C:\Users\user\Desktop>pause
Press any key to continue . . .

As you can see the command echo %random% keeps producing relatively random numbers between 0 and 32,767 as expected.

At the same time using %random% to set a value for variable rnumber does not. It produces a not-so random number (possibly too between 0 and 32,767) but it is not random. If I were to guess right now it seems to be slowly growing in the 0 to 32,767 direction.

To clarify the script keeps producing a random number with line 2 on each execution (20160, 13887, 18885...), but line 1 seems to produce a number that keeps increasing with each execution of the batch file (28955, 29072, 29183, and so on in my multiple tests).

I already tried it on two different computers, Windows 7 x64 and Windows 2012 R2 respectively, running this 3 line script multiple times in row.

Next thing to try will be on a computer from a completely different network, I'm wondering if this has anything to do with domain policies, network, software..

What is going on here?

UPDATE:

When running the commands in sequence from the same CMD window it works as expected, but it does not when executing the same batch file multiple times.

  • The line in the script echo %random% works as expected.
  • The line SET rnumber=%random% does not.

(When executing the same script multiple times)

Community
  • 1
  • 1
ArdenP
  • 11
  • 3
  • 1
    Well, what would you consider as "random enough"?? How often did you try?? – aschipfl May 31 '19 at 16:25
  • [Sheer coincidence, imo](https://i.imgur.com/mJmqUAl.png) – SomethingDark May 31 '19 at 16:28
  • About 100 times now? Just tried this on a completely different computer. Looks like this is a bug. – ArdenP May 31 '19 at 17:04
  • Not a coincidence, it does indeed produce random number when running the command from the same command line window, the bug shows up only when you running the same batch file multiple times. – ArdenP May 31 '19 at 17:06
  • 2
    [known behavior](https://devblogs.microsoft.com/oldnewthing/?p=13673) - very annoying indeed. – Stephan May 31 '19 at 17:14
  • Did I just discover some very old Windows bug? Most people probably would not care all that much due to rarity of my scenario, I think even I would not care for it in my production scenario, but took a good hour trying to figure out what is wrong with my script. – ArdenP May 31 '19 at 17:14
  • Thank you @Stephan! Will read his post later today. – ArdenP May 31 '19 at 17:18
  • So explain my results of running the same script three times in a row then – SomethingDark May 31 '19 at 17:20
  • 2
    @SomethingDark: the random number generator is initialized using `%time%` when you start a new `cmd` process. You run your test all in the same window (=process), so there is no re-initialization between. Double click your `test.bat` a few times very fast (within the same second) and you should be able to replicate the issue. (don't forget to add a `pause` to keep the windows open) – Stephan May 31 '19 at 17:27
  • 3
    Oh, right, some people run scripts by double-clicking them... – SomethingDark May 31 '19 at 17:28
  • 5
    @SomethingDark: yes - a concept I too can't adapt to somehow... – Stephan May 31 '19 at 17:35
  • @stephan https://devblogs.microsoft.com/oldnewthing/?p=13673 I've enjoyed this. – elzooilogico May 31 '19 at 18:57
  • @Stephan "a few times very fast (within the same second)" not even within the same second actually, it does the same thing even after a few seconds, the number just keeps flowing upwards. I'm yet to read that blog, but at least I can now proceed with what I need to do knowing that nothing is wrong with my environment. – ArdenP May 31 '19 at 19:49
  • Thanks for the help @Everyone, my brain was overheating there for a bit. – ArdenP May 31 '19 at 19:51
  • Perhaps you may be interested in [this topic](https://www.dostips.com/forum/viewtopic.php?f=3&t=7494)... – Aacini May 31 '19 at 22:21
  • @ArdenP the output in the blog is the same every time for a single second, which is exactly the same issue as [Why does rand() yield the same sequence of numbers on every run?](https://stackoverflow.com/q/9459035/995714). Just discard the first iteration, or better move to powershell. In case cmd is a must then run `powershell -com get-random` – phuclv Jun 01 '19 at 06:21

2 Answers2

1

To provide a summary of everything that was learned from the comment discussion, external resources and testing regarding my original question.

Random number generator in batch script uses the following algorithm to seed the initial random number value when a new CMD window is opened. (from here - https://devblogs.microsoft.com/oldnewthing/?p=13673)

srand((unsigned)time(NULL));

As a result when two(or more) CMD windows are started within the same second the initial returns of the %random% are the same. Subsequent returns of %random% within two CMD windows with the same seed and run time (to a second) are also the same.

Moreover if CMD windows are consequently started with certain delays from each other the first return of the %random% pseudo-variable in each new CMD window will be far from random and will be slowly increasing (0 to 32767 range). In my testing this initial seed number grows by either 3 or 4 every one second for each new window.

To learn more about this and to find workarounds look here:

Also look at PowerShell workaround provided by @lit.

ArdenP
  • 11
  • 3
0

Random numbers from cmd.exe is not for the faint of heart. Neither %RANDOM% nor !RANDOM! will get you there.

This page, https://ss64.com/nt/syntax-random.html, makes for interesting reading.

If you are on a supported Windows platform, PowerShell will work.

@ECHO OFF
FOR /F %%n IN ('powershell -NoLogo -NoProfile -Command Get-Random') DO (
    SET "RNUM=%%~n"
)
ECHO RNUM is %RNUM%
lit
  • 14,456
  • 10
  • 65
  • 119
  • Please explain your code – john k Feb 27 '22 at 15:56
  • @johnktejik, the output of the PowerShell `Get-Random` command is a random number. In a PowerShell console, use the command `help Get-Random -full` to read more about it. The result is stored in the environment variable `RNUM`. – lit Feb 27 '22 at 19:22