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
This is source code for a program that does what you want: http://www.mailsend-online.com/blog/setting-text-color-in-a-batch-file.html
I am beginning to think that there is no longer a built-in way to do this without an additional program, or modifications to the user's system.
An aside - For my scenario, if modifications to the user's system was a requirement, I'd simply opt to use python, IronPython, or JScript.NET instead.
There is no built-in way of doing this. I suggest you write yourself a little helper program which either changes the color attributes of text to come or writes some text with specific color attributes.
In C# this could look like the following:
using System;
class SetConsoleColor {
static void Main(string[] args) {
if (args.Length < 3) {
Console.Error.WriteLine("Usage: SetConsoleColor [foreground] [background] [message]");
return;
}
Console.ForegroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), args[0], true);
Console.BackgroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), args[1], true);
Console.WriteLine(args[2]);
Console.ResetColor();
}
}
Feel free to port to C or another language you like; this was just the fastest way for me after struggling with a 50-line C monster which still didn't work ;-).
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 <space> will be stripped.
::
:: The string is printed to the screen without issuing a <newline>,
:: 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 (
<nul set/p"=%%a" >"%~2"
)
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1
popd
exit /b