How to generate random numbers at command prompt?

Asked

Viewed 3,516 times

1

I have a file on .cmd and I need it to generate random numbers with 10 algorithms. Like for example 9006100001 and 1579970319 randomly generated.

I currently have the following function generating random numbers based on team, of the system.

setlocal 
for /f "skip=8 tokens=2,3,4,5,6,7,8 delims=: " %%D in ('robocopy /l * \ \ /ns /nc /ndl /nfl /np /njh /XF * /XD *') do (
 set "dow=%%D"
 set "month=%%E"
 set "day=%%F"
 set "HH=%%G"
 set "MM=%%H"
 set "SS=%%I"
 set "year=%%J"
)

Of that function, I use only the %SS%, is as close as I got to what I want so far, as I could create something similar to generate random numbers?

If possible, they could include a variation of this with alphanumeric characters*

2 answers

2

With your function that is already generating random numbers, take the result and multiply by a large number, and while this number does not exceed 10 digits, continue multiplying. EX:

@echo off
mode 76,30
color 9f
title Gerador de numeros aleatorios com mais de 10 algarimos
setlocal enabledelayedexpansion

:MAIN
cls 
echo.
echo Gerador de numeros aleatorios.
echo.
set start=s
set /p start=Iniciar(s/n):
if %start% equ s call :gerar && goto multiplicar
if not %start% equ s goto MAIN
goto MAIN

:gerar
set gerar=%random%

:multiplicar
set /A gerar=%gerar%*9876
if not %gerar% gtr 999999999 goto multiplicar
if %gerar% gtr 999999999 goto n_gerado

:n_gerado
echo.
echo nº gerado: %gerar%
pause>nul
goto MAIN

I hope it helps.

  • It is an option, but the use of loop is something I intend to avoid if I can, my script is continuous execution, ie this function is used every x seconds. Anyway thank you.

1


Another alternative is to create an alphabet with the characters you want to generate, in a loop for you use the random to randomly obtain an index and access the value of a array:

@echo off
setlocal enabledelayedexpansion

set "alfabeto=0 1 2 3 4 5 6 7 8 9"

set "tamanho=0"
set "resultado="

REM Cria um array com os elementos
for %%a in (%alfabeto%) do (
    set "!tamanho!=%%a"
    set /a "tamanho+=1"
)

REM Retorna 10 caracteres aleatórios
for /L %%G in (1 1 10) do (
    set /a "indice=!random! %% tamanho"
    for %%b in (!indice!) do set "resultado=!resultado!!%%b!"
)

echo %resultado%
endlocal

If possible, they could include a variation of this with alphanumeric characters?

Using the above example, include the characters in the alphabet:

set "alfabeto=a b c d f g h i j k l m n p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9"
  • Great answer, accepting because it met all the requirements of the question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.