0

I'm trying to get a batch script to randomly choose between two names and output one at a time, kinda something like this:

@echo off
::I would not be prompted to enter these, they would already be programmed into the script.
ChooseRandomSet=Maria
                Sean
                Matt
                Laura
ChooseRandom

So, then on the user side, you would see:

C:\>script.bat
Matt was randomly chosen.
C:\>script.bat
Sean was randomly chosen.
C:\>

Thanks!

ditheredtransparency
  • 475
  • 3
  • 10
  • 18
  • 2
    Possible duplicate of [Get a random sentence from a selection each time in Batch](http://stackoverflow.com/questions/15531745/get-a-random-sentence-from-a-selection-each-time-in-batch) – JosefZ Feb 06 '17 at 08:24

2 Answers2

1

First create a text file with all the names on separate lines:

Maria
Sean
Matt
Laura

Then create a .bat file with the following code:

@ECHO OFF
IF "%~1"=="" (ECHO No text file specified & GOTO :EOF)
IF NOT EXIST %1 (ECHO Text file doesn't exist. & GOTO :EOF)
FOR /F "" %%I IN ('FIND /C /V "" ^<%1') DO SET /A lines=%%I
IF %lines%==0 (ECHO Text file is empty or unreadable & GOTO :EOF)
SET /A skip=(%RANDOM%*32768+%RANDOM%)%%lines
<%1 (
  FOR /L %%I IN (1,1,%skip%) DO (
    SET /P line=
  )
  SET line=
  SET /P line=
)
ECHO(%line%

This will print out a name from the file, it will also check for certain errors like:

  • No text file specified
  • File specified but non-existent
  • Empty text file

Disclaimer: I used this bat script for something but I didn't write it, I might've changed a few things over the years but it's largely as I found it a while back. (not a Windows guy myself.. :P)

Rick van Lieshout
  • 2,276
  • 2
  • 22
  • 39
0

Update: I also found an answer to this myself just by experimenting. This chooses one option out of two possible choices:

@echo off
if %random% gtr %random% (
      echo heads
) else (
echo tails
pause
ditheredtransparency
  • 475
  • 3
  • 10
  • 18