I have a batch file as follows:
myfile.bat
:: This is a sample batch file
@echo off
echo change directory to d: <---How to change color of only this line
A nearly identical question was asked 6 months after this one, and jeb provided a good answer 3 after that: how to have multiple colors in a batch file?
His answer allows printing multiple colors on a single line!
Here is an adaptation of his solution as a standalone batch file that can be used as a utility to print in color in batch. To print Hello world! in red text on a white background you would use call colorText f4 "Hello world!". See the comments in the code for full documentation and limitations.
@echo off
:ColorText Color String
::
:: Prints String in color specified by Color.
::
:: Color should be 2 hex digits
:: The 1st digit specifies the background
:: The 2nd digit specifies the foreground
:: See COLOR /? for more help
::
:: String is the text to print. All quotes will be stripped.
:: The string cannot contain any of the following: * ? < > | : \ /
:: Also, any trailing . or will be stripped.
::
:: The string is printed to the screen without issuing a ,
:: so multiple colors can appear on one line. To terminate the line
:: without printing anything, use the ECHO( command.
::
setlocal
pushd %temp%
for /F "tokens=1 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
"%~2"
)
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1
popd
exit /b