-3

I want to generate a random number between 1 to 5 in a batch file

Peter O.
  • 32,158
  • 14
  • 82
  • 96

2 Answers2

1

Since it's tagged PowerShell:

Get-Random -Minimum 1 -Maximum 5

Or

[System.Random]::new().Next( 1, 5 )

If you want to run inside a batch file you can just execute PowerShell with the -Command parameter:

powershell.exe -Command "Get-Random -Minimum 1 -Maximum 5"

You can use either method with this syntax

Steven
  • 6,817
  • 1
  • 14
  • 14
0

Using batch, syntax is (set /a var=(%RANDOM%*max/32768)+min)

@echo off
set /a rand=(%RANDOM%*5/32768)+1
echo %rand%
Wasif
  • 14,755
  • 3
  • 14
  • 34
  • 1
    `set /a rand=(%RANDOM% %% max)+min` actually gets you a more even distribution of random numbers – SomethingDark Nov 07 '20 at 05:56
  • Also worth noting Delayed expansion and !random! should be used if generating the random number within a code block. – T3RR0R Nov 07 '20 at 08:10