Author Options:

How do I make a Batch file echo a random set thing, like jokes? Answered

Hi, I'm wondering how to make a Batch file tell jokes. I know quite a bit about Batch, and I'm making a butler. I want him to tell jokes that I code for him, but random ones. If he has, let's say, three available jokes coded for him, how would I make him tell one of them randomly, not in order or by the user's input? Help will be greatly appreciated. Thanks!


The forums are retiring in 2021 and are now closed for new topics and comments.

4 years ago

One way would be to have a text file with your jokes listed, one line per joke and use skip and RANDOM to select the line or joke to display. I grabbed a batch file from the internet and modified it below. Going through it, it sets the joke file to jokelist.txt, calculates the NumberOfLines (how many jokes to choose from), selects the joke using a RANDOM number, you can't skip 0 so makes sure it wont skip everything, then grabs the joke and echos it to the screen. Hope this helps.

SET "JokeListFile=jokelist.txt"

FOR /f %%a IN ('type "%JokeListFile%"^|find /c /v ""') DO SET /a NumberOfLines=%%a

SET /A SelectedJoke=(%RANDOM% %% %NumberOfLines%)

IF "%SelectedJoke%"=="0" (SET "SelectedJoke=") ELSE (SET "SelectedJoke=skip=%SelectedJoke%")

FOR /F "usebackq tokens=* %SelectedJoke% delims=" %%A IN (`TYPE %JokeListFile%`) DO (