none
(Command Prompt) How to use for with echo and get a different %random% each time. RRS feed

  • Question

    • I want

    for /l %n in (1,1,3) do echo %random%

    • to equal

    6482

    7392

    19365

    • instead of

    7428

    7428

    7428

    Monday, November 30, 2015 1:07 AM

Answers

  • Hi Bblazerm,

    You need to use EnableDelayedExpansion.

    Within the for loop you need to use !variable! instead of %variable%.

    EnableDelayedExpansion is Disabled by default.
    EnableDelayedExpansion can also be enabled by starting CMD with the /v switch.

    #Run the cmd /v
    C:\windows\system32>cmd /v
    
    C:\windows\system32>for /l %n in (1,1,3) do echo !random!
    
    C:\windows\system32>echo !random!
    8887
    
    C:\windows\system32>echo !random!
    1846
    
    C:\windows\system32>echo !random!
    8306


    Regards,

    Satyajit

    Please “Vote As Helpful” if you find my contribution useful or “Mark As Answer” if it does answer your question. That will encourage me - and others - to take time out to help you.

    Monday, November 30, 2015 6:17 AM

All replies

  • Hi Bblazerm,

    You need to use EnableDelayedExpansion.

    Within the for loop you need to use !variable! instead of %variable%.

    EnableDelayedExpansion is Disabled by default.
    EnableDelayedExpansion can also be enabled by starting CMD with the /v switch.

    #Run the cmd /v
    C:\windows\system32>cmd /v
    
    C:\windows\system32>for /l %n in (1,1,3) do echo !random!
    
    C:\windows\system32>echo !random!
    8887
    
    C:\windows\system32>echo !random!
    1846
    
    C:\windows\system32>echo !random!
    8306


    Regards,

    Satyajit

    Please “Vote As Helpful” if you find my contribution useful or “Mark As Answer” if it does answer your question. That will encourage me - and others - to take time out to help you.

    Monday, November 30, 2015 6:17 AM
  • Satyajit321 is correct. The reason for the output is that cmd.exe expands environment variables (%name%) when in parses the line, not when it executes it. When you use delayed variable expansion (!name!), cmd.exe expands the variable when it executes the line.

    PowerShell equivalent:


    PS C:\> 0..32767 | Get-Random -Count 3
    


    -- Bill Stewart [Bill_Stewart]

    Monday, November 30, 2015 7:07 PM
    Moderator