How to change text color of comment line in batch file

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 (comments lines) CD d:\ ... 
+1
batch-file
source share
3 answers

Almost the same question was asked within 6 months after that, and jeb provided a good answer 3 after that: how to have several colors in a batch file?

His answer allows you to print multiple colors on one line!

Here is an adaptation of his solution as a stand-alone batch file that can be used as a utility for printing in color in batch mode. To print Hello world! in red text on a white background, you should use call colorText f4 "Hello world!" . See 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 
+1
source share

There is no built-in way to do this. I suggest you write a small helper program that either changes the text color attributes or writes text with specific color attributes.

In C #, it might look like this:

 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 that you like; it was the fastest way for me after fighting a 50-line-down monster C that still didn't work; -).

0
source share

This is the 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'm starting to think that there is no longer a built-in way to do this without additional software or changes to the user system.

Aside - for my scenario, if changes in the user system were a requirement, I would just decide to use python, IronPython or JScript.NET.

0
source share

All Articles