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?

Synetech
  • 68,243
  • 36
  • 223
  • 356
hbelouf
  • 721
  • 1
  • 5
  • 9

1 Answers1

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

Synetech
  • 68,243
  • 36
  • 223
  • 356
  • Thanks... By using delayed expansion, it worked the way I wanted. – hbelouf Nov 19 '13 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 '13 at 17:41