1

I want to generate a random number in a For Loop like that (part of it):

FOR /F "delims=, eol=; tokens=1,2" %%a in (DATA.TXT) DO (   
    SET min=10000
    SET max=99999
    SET /a passwort=!min!+(!max!-!min!+1)*%random%/32768
)

Unfortunately, it returns this error:

"*[randomly generated number]/32768" cannot be processed syntactically at this point.

  • OP has a specific error which IMHO is not handled in [How to use random in BATCH script?](https://stackoverflow.com/q/5777400) – Adrian W Jul 10 '18 at 18:40

1 Answers1

2
  • It doesn't work because the set /a command isn't double quoted and the (code block) ends prematurely with the unescaped closing parentheses in the formula.
  • Otherwise the formula has the flaw that it could generate negative numbers due to multiplying first
    (set /a is limited to signed 32bit integer math).
  • Also inside a (code block) it needs to be !random! while all the other variables don't need %/! for expansion (special to set /A)
  • without further precautions a number password in this range isn't very secure,
    but you can use random numbers repeatedly to generate a password of arbitrary length from a set of characters like in this answer

:: Q:\Test\2018\07\10\SO_51271717.cmd
@Echo off & SetLocal EnableExtensions EnableDelayedExpansion

SET /A "min=10000,max=99999,range=max-min+1"

FOR /F "delims=, eol=; tokens=1,2" %%a in (DATA.TXT) DO (   
    SET /a "passwort=min + range / 32768* !random! "
    Echo passwort=!passwort!
)

Sample output:

> Q:\Test\2018\07\10\SO_51271717.cmd
passwort=10528
passwort=56868
passwort=34042
passwort=40878
passwort=32590
passwort=47396
passwort=51676
passwort=66530
passwort=40106
passwort=56218