0

I’m having trouble with the %RANDOM% environment variable in the following command:

FOR /l %%A in (0,1,30) do set /a results=1600 + %RANDOM% %% (1900 - 1600 + 1) && echo %%A--!results!

I expect this output:

0--1656
1--1743
2--1629
3--1887
…

But I’m getting this:

0--1656
1--1656
2--1656
3--1656
…

The %RANDOM% variable is supposed to return a random number, but it’s giving the same number. What’s the problem and how can I fix it?

2
  • @WernerHenze, actually it’s not; it’s closer to this question.
    – Synetech
    Nov 19, 2013 at 17:24
  • 1
    @Synetech OK, but at least the answers in the question I linked give the answer to the question here :). Nov 19, 2013 at 17:28

1 Answer 1

1

You need to use delayed expansion for the RANDOM variable as well:

FOR /l %%A in (0,1,30) do set /a results=1600 + !RANDOM! %% (1900 - 1600 + 1) && echo %%A--!results!

Screenshot of command-prompt with expected results from script

2
  • Thanks... By using delayed expansion, it worked the way I wanted.
    – hbelouf
    Nov 19, 2013 at 17:31
  • You were already using delayed expansion on the results variable, you just forgot to use on the random variable. You need to use ! in place of % for all variables in a for loop. ;-)
    – Synetech
    Nov 19, 2013 at 17:41

Not the answer you're looking for? Browse other questions tagged .