Randomizing text color and background color in batch file

10,781

Solution 1

To change the color, you need the color command. The arguments are:

color <background><text>

So generating a random color works like this:

set /a rand1=%random% %% 16
set /a rand2=%random% %% 16
set HEX=0123456789ABCDEF
call set hexcolors=%%HEX:~%rand1%,1%%%%HEX:~%rand2%,1%%
color %hexcolors%

Solution 2

Just for the heck of it, here's a .BAT using the answer above and a couple others to create a psychedelic coloured light show (aka loop random colors with delay).

I'd call it useless, but actually it does demonstrate creative use of a few cmd line commands (written by others, slapped together by me) such as pausing under 1 second using ping.

@echo off
cls

rem prepare loop 
Set Sleep=0  
:start

rem loop 40 times
if %Sleep% == 40 ( goto end )

rem pick random numbers 1-16
set /a rand1=%random% %% 16
set /a rand2=%random% %% 16

rem user 
set HEX=0123456789ABCDEF
call set hexcolors=%%HEX:~%rand1%,1%%%%HEX:~%rand2%,1%%

rem set back/fore colors
color %hexcolors%
echo loop#%Sleep% color=%hexcolors%

rem the pings act as a split-second delay   
PING localhost -n 1 >NUL
PING localhost -n 1 >NUL

rem increment counter and loop
Set /A Sleep+=1
goto start
:end

rem close after 3 seconds
timeout /t 3


More Information:

Share:
10,781
mrdorkface
Author by

mrdorkface

Updated on June 04, 2022

Comments

  • mrdorkface
    mrdorkface almost 2 years

    I am attempting to make a batch file that will randomize the color code when the script is run. How would i do this?