Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

This question already has an answer here:

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?

share|improve this question

marked as duplicate by Tog, MariusMatutiae, Mokubai, Dave M, Moses Nov 21 '13 at 2:35

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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

1 Answer 1

up vote 1 down vote accepted

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

share|improve this answer
    
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

Not the answer you're looking for? Browse other questions tagged or ask your own question.