I was wondering if its possible to have different colored text on the same line in a Windows batch file, for example if it says
echo hi world
I want "hi" to be one color, and "world" to be another color. Maybe I could set the COLOR command as a variable:
set color1= color 2
set color9= color A
and then deploy them both on the same line along with
echo hi world
but I don't know how I would do that.
This question is related to
windows
batch-file
colors
character-encoding
cmd
Yes, it is possible with cmdcolor:
echo \033[32mhi \033[92mworld
hi
will be dark green, and world
- light green.
You can do multicolor outputs without any external programs.
@echo off
SETLOCAL EnableDelayedExpansion
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
set "DEL=%%a"
)
echo say the name of the colors, don't read
call :ColorText 0a "blue"
call :ColorText 0C "green"
call :ColorText 0b "red"
echo(
call :ColorText 19 "yellow"
call :ColorText 2F "black"
call :ColorText 4e "white"
goto :eof
:ColorText
echo off
<nul set /p ".=%DEL%" > "%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1
goto :eof
It uses the color feature of the findstr command.
Findstr can be configured to output line numbers or filenames in a defined color.
So I first create a file with the text as filename, and the content is a single <backspace>
character (ASCII 8).
Then I search all non empty lines in the file and in nul, so the filename will be output in the correct color appended with a colon, but the colon is immediatly removed by the <backspace>
.
EDIT: One year later ... all characters are valid
@echo off
setlocal EnableDelayedExpansion
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
set "DEL=%%a"
)
rem Prepare a file "X" with only one dot
<nul > X set /p ".=."
call :color 1a "a"
call :color 1b "b"
call :color 1c "^!<>&| %%%%"*?"
exit /b
:color
set "param=^%~2" !
set "param=!param:"=\"!"
findstr /p /A:%1 "." "!param!\..\X" nul
<nul set /p ".=%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%"
exit /b
This uses the rule for valid path/filenames.
If a \..\
is in the path the prefixed elemet will be removed completly and it's not necessary that this element contains only valid filename characters.
If your console supports ANSI colour codes (e.g. ConEmu, Clink or ANSICON) you can do this:
SET GRAY=%ESC%[0m
SET RED=%ESC%[1;31m
SET GREEN=%ESC%[1;32m
SET ORANGE=%ESC%[0;33m
SET BLUE=%ESC%[0;34m
SET MAGENTA=%ESC%[0;35m
SET CYAN=%ESC%[1;36m
SET WHITE=%ESC%[1;37m
where ESC variable contains ASCII character 27.
I found a way to populate the ESC variable here: http://www.dostips.com/forum/viewtopic.php?p=6827#p6827
and using tasklist
it's possible to test what DLLs are loaded into a process.
The following script gets the process ID of the cmd.exe that the script is running in. Checks if it has a dll that will add ANSI support injected, and then sets colour variables to contain escape sequences or be empty depending on whether colour is supported or not.
@echo off
call :INIT_COLORS
echo %RED%RED %GREEN%GREEN %ORANGE%ORANGE %BLUE%BLUE %MAGENTA%MAGENTA %CYAN%CYAN %WHITE%WHITE %GRAY%GRAY
:: pause if double clicked on instead of run from command line.
SET interactive=0
ECHO %CMDCMDLINE% | FINDSTR /L %COMSPEC% >NUL 2>&1
IF %ERRORLEVEL% == 0 SET interactive=1
@rem ECHO %CMDCMDLINE% %COMSPEC% %interactive%
IF "%interactive%"=="1" PAUSE
EXIT /B 0
Goto :EOF
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
: SUBROUTINES :
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::
:INIT_COLORS
::::::::::::::::::::::::::::::::
call :supportsANSI
if ERRORLEVEL 1 (
SET GREEN=
SET RED=
SET GRAY=
SET WHITE=
SET ORANGE=
SET CYAN=
) ELSE (
:: If you can, insert ASCII CHAR 27 after equals and remove BL.String.CreateDEL_ESC routine
set "ESC="
:: use this if can't type ESC CHAR, it's more verbose, but you can copy and paste it
call :BL.String.CreateDEL_ESC
SET GRAY=%ESC%[0m
SET RED=%ESC%[1;31m
SET GREEN=%ESC%[1;32m
SET ORANGE=%ESC%[0;33m
SET BLUE=%ESC%[0;34m
SET MAGENTA=%ESC%[0;35m
SET CYAN=%ESC%[1;36m
SET WHITE=%ESC%[1;37m
)
exit /b
::::::::::::::::::::::::::::::::
:BL.String.CreateDEL_ESC
::::::::::::::::::::::::::::::::
:: http://www.dostips.com/forum/viewtopic.php?t=1733
::
:: Creates two variables with one character DEL=Ascii-08 and ESC=Ascii-27
:: DEL and ESC can be used with and without DelayedExpansion
setlocal
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
ENDLOCAL
set "DEL=%%a"
set "ESC=%%b"
goto :EOF
)
::::::::::::::::::::::::::::::::
:supportsANSI
::::::::::::::::::::::::::::::::
:: returns ERRORLEVEL 0 - YES, 1 - NO
::
:: - Tests for ConEmu, ANSICON and Clink
:: - Returns 1 - NO support, when called via "CMD /D" (i.e. no autoruns / DLL injection)
:: on a system that would otherwise support ANSI.
if "%ConEmuANSI%" == "ON" exit /b 0
call :getPID PID
setlocal
for /f usebackq^ delims^=^"^ tokens^=^* %%a in (`tasklist /fi "PID eq %PID%" /m /fo CSV`) do set "MODULES=%%a"
set MODULES=%MODULES:"=%
set NON_ANSI_MODULES=%MODULES%
:: strip out ANSI dlls from module list:
:: ANSICON adds ANSI64.dll or ANSI32.dll
set "NON_ANSI_MODULES=%NON_ANSI_MODULES:ANSI=%"
:: ConEmu attaches ConEmuHk but ConEmu also sets ConEmuANSI Environment VAR
:: so we've already checked for that above and returned early.
@rem set "NON_ANSI_MODULES=%NON_ANSI_MODULES:ConEmuHk=%"
:: Clink supports ANSI https://github.com/mridgers/clink/issues/54
set "NON_ANSI_MODULES=%NON_ANSI_MODULES:clink_dll=%"
if "%MODULES%" == "%NON_ANSI_MODULES%" endlocal & exit /b 1
endlocal
exit /b 0
::::::::::::::::::::::::::::::::
:getPID [RtnVar]
::::::::::::::::::::::::::::::::
:: REQUIREMENTS:
::
:: Determine the Process ID of the currently executing script,
:: but in a way that is multiple execution safe especially when the script can be executing multiple times
:: - at the exact same time in the same millisecond,
:: - by multiple users,
:: - in multiple window sessions (RDP),
:: - by privileged and non-privileged (e.g. Administrator) accounts,
:: - interactively or in the background.
:: - work when the cmd.exe window cannot appear
:: e.g. running from TaskScheduler as LOCAL SERVICE or using the "Run whether user is logged on or not" setting
::
:: https://social.msdn.microsoft.com/Forums/vstudio/en-US/270f0842-963d-4ed9-b27d-27957628004c/what-is-the-pid-of-the-current-cmdexe?forum=msbuild
::
:: http://serverfault.com/a/654029/306
::
:: Store the Process ID (PID) of the currently running script in environment variable RtnVar.
:: If called without any argument, then simply write the PID to stdout.
::
::
setlocal disableDelayedExpansion
:getLock
set "lock=%temp%\%~nx0.%time::=.%.lock"
set "uid=%lock:\=:b%"
set "uid=%uid:,=:c%"
set "uid=%uid:'=:q%"
set "uid=%uid:_=:u%"
setlocal enableDelayedExpansion
set "uid=!uid:%%=:p!"
endlocal & set "uid=%uid%"
2>nul ( 9>"%lock%" (
for /f "skip=1" %%A in (
'wmic process where "name='cmd.exe' and CommandLine like '%%<%uid%>%%'" get ParentProcessID'
) do for %%B in (%%A) do set "PID=%%B"
(call )
))||goto :getLock
del "%lock%" 2>nul
endlocal & if "%~1" equ "" (echo(%PID%) else set "%~1=%PID%"
exit /b
An alternative adaptation of Jebs Solution that avoids the use of call via the use of Macro arguments and variable substitution:
@Echo off
:# Macro Definitions
For /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (set "DEL=%%a")
:# %\C% - Color macro; No error checking. Usage:
:# %\C:?=HEXVALUE%Output String
:# (%\C:?=HEXVALUE%Output String) & (%\C:?=HEXVALUE%Output String)
Set "\C=For %%o in (1 2)Do if %%o==2 (( <nul set /p ".=%DEL%" > "^^!os:\n=^^!" ) & ( findstr /v /a:? /R "^$" "^^!os:\n=^^!" nul ) & ( del "^^!os:\n=^^!" > nul 2>&1 ) & (Set "testos=^^!os:\n=^^!" & If not "^^!testos^^!" == "^^!os^^!" (Echo/)))Else Set os="
:# Ensure macro escaping is correct depending on delayedexpansion environment type
If Not "!![" == "[" (
Set "\C=%\C:^^=^%"
)
Setlocal EnableExtensions EnableDelayedExpansion
PUSHD "%~dp0"
:# SCRIPT MAIN BODY
:# To force a new line; terminate an output string with: \n
:# Usage info:
(%\C:?=40% This is an example of usage\n)&(%\C:?=50% Trailing whitespace and periods are removed.\n)
(%\C:?=0e% Leading spaces and periods are retained)&(%\C:?=e0%. NOT SUPPORTED - \n)
%\C:?=02% Colon ^& Unescaped Ampersands ^& doublequotes\n
%\C:?=02% LSS than ^& GTR than symbols ^& foreward and backward slashes\n
(%\C:?=02% Pipe ^& Question Mark and Asterisk characters.\n) & (%\C:?=e2%^^! Exclaimation ^^! marks must be escaped\n)
:end
POPD
Endlocal
Goto :Eof
Without external tools.This is a self-compiled bat/.net hybrid (should be saved as .BAT
) that can be used on any system that have installed .net framework (it's a rare thing to see an windows without .NET framework even for the oldest XP/2003 installations) . It uses jscript.net compiler to create an exe capable to print strings with different background/foreground color only for the current line.
@if (@X)==(@Y) @end /* JScript comment
@echo off
setlocal
for /f "tokens=* delims=" %%v in ('dir /b /s /a:-d /o:-n "%SystemRoot%\Microsoft.NET\Framework\*jsc.exe"') do (
set "jsc=%%v"
)
if not exist "%~n0.exe" (
"%jsc%" /nologo /out:"%~n0.exe" "%~dpsfnx0"
)
%~n0.exe %*
endlocal & exit /b %errorlevel%
*/
import System;
var arguments:String[] = Environment.GetCommandLineArgs();
var newLine = false;
var output = "";
var foregroundColor = Console.ForegroundColor;
var backgroundColor = Console.BackgroundColor;
var evaluate = false;
var currentBackground=Console.BackgroundColor;
var currentForeground=Console.ForegroundColor;
//http://stackoverflow.com/a/24294348/388389
var jsEscapes = {
'n': '\n',
'r': '\r',
't': '\t',
'f': '\f',
'v': '\v',
'b': '\b'
};
function decodeJsEscape(_, hex0, hex1, octal, other) {
var hex = hex0 || hex1;
if (hex) { return String.fromCharCode(parseInt(hex, 16)); }
if (octal) { return String.fromCharCode(parseInt(octal, 8)); }
return jsEscapes[other] || other;
}
function decodeJsString(s) {
return s.replace(
// Matches an escape sequence with UTF-16 in group 1, single byte hex in group 2,
// octal in group 3, and arbitrary other single-character escapes in group 4.
/\\(?:u([0-9A-Fa-f]{4})|x([0-9A-Fa-f]{2})|([0-3][0-7]{0,2}|[4-7][0-7]?)|(.))/g,
decodeJsEscape);
}
function printHelp( ) {
print( arguments[0] + " -s string [-f foreground] [-b background] [-n] [-e]" );
print( " " );
print( " string String to be printed" );
print( " foreground Foreground color - a " );
print( " number between 0 and 15." );
print( " background Background color - a " );
print( " number between 0 and 15." );
print( " -n Indicates if a new line should" );
print( " be written at the end of the ");
print( " string(by default - no)." );
print( " -e Evaluates special character " );
print( " sequences like \\n\\b\\r and etc ");
print( "" );
print( "Colors :" );
for ( var c = 0 ; c < 16 ; c++ ) {
Console.BackgroundColor = c;
Console.Write( " " );
Console.BackgroundColor=currentBackground;
Console.Write( "-"+c );
Console.WriteLine( "" );
}
Console.BackgroundColor=currentBackground;
}
function errorChecker( e:Error ) {
if ( e.message == "Input string was not in a correct format." ) {
print( "the color parameters should be numbers between 0 and 15" );
Environment.Exit( 1 );
} else if (e.message == "Index was outside the bounds of the array.") {
print( "invalid arguments" );
Environment.Exit( 2 );
} else {
print ( "Error Message: " + e.message );
print ( "Error Code: " + ( e.number & 0xFFFF ) );
print ( "Error Name: " + e.name );
Environment.Exit( 666 );
}
}
function numberChecker( i:Int32 ){
if( i > 15 || i < 0 ) {
print("the color parameters should be numbers between 0 and 15");
Environment.Exit(1);
}
}
if ( arguments.length == 1 || arguments[1].toLowerCase() == "-help" || arguments[1].toLowerCase() == "-help" ) {
printHelp();
Environment.Exit(0);
}
for (var arg = 1; arg <= arguments.length-1; arg++ ) {
if ( arguments[arg].toLowerCase() == "-n" ) {
newLine=true;
}
if ( arguments[arg].toLowerCase() == "-e" ) {
evaluate=true;
}
if ( arguments[arg].toLowerCase() == "-s" ) {
output=arguments[arg+1];
}
if ( arguments[arg].toLowerCase() == "-b" ) {
try {
backgroundColor=Int32.Parse( arguments[arg+1] );
} catch(e) {
errorChecker(e);
}
}
if ( arguments[arg].toLowerCase() == "-f" ) {
try {
foregroundColor=Int32.Parse(arguments[arg+1]);
} catch(e) {
errorChecker(e);
}
}
}
Console.BackgroundColor = backgroundColor ;
Console.ForegroundColor = foregroundColor ;
if ( evaluate ) {
output=decodeJsString(output);
}
if ( newLine ) {
Console.WriteLine(output);
} else {
Console.Write(output);
}
Console.BackgroundColor = currentBackground;
Console.ForegroundColor = currentForeground;
Example coloroutput.bat -s "aa\nbb\n\u0025cc" -b 10 -f 3 -n -e
You can also check carlos' color function -> http://www.dostips.com/forum/viewtopic.php?f=3&t=4453
If you have a modern Windows (that has powershell installed), the following may work fine as well
call :PrintBright Something Something
(do actual batch stuff here)
call :PrintBright Done!
goto :eof
:PrintBright
powershell -Command Write-Host "%*" -foreground "White"
Adjust the color as you see fit.
Windows 10 ((Version 1511, build 10586, release 2015-11-10)) supports ANSI colors.
You can use the escape key to trigger the color codes.
In the Command Prompt:
echo ^[[32m HI ^[[0m
echo Ctrl+[[32m HI
Ctrl+[[0m
Enter
When using a text editor, you can use ALT key codes.
The ESC key code can be created using ALT and NUMPAD numbers : Alt+027
[32m HI [0m
After my previous answer was deleted for failing to include the code, on the basis the Ansi characters used can not be displayed by stack overflow rendering the presence of the code somewhat pointless given it was based on them, I have redesigned the code to include the method of populating the Escape character detailed by @Sam Hasler
In the process, I've also taken out all the subroutines in favor of macro's, and adapted my approach to passing parameters to the macro's.
All macro's balance the Setlocal / Endlocal pairings to prevent exceeding recursion level's through use of ^&^& endlocal
after completeing their handling of the Args.
The std.out macro also demonstrates how to adapt the macros to store output into variables that survive past the Endlocal barrier.
@Echo off & Mode 1000
::: / Creates two variables with one character DEL=Ascii-08 and /AE=Ascii-27 escape code. only /AE is used
::: - http://www.dostips.com/forum/viewtopic.php?t=1733
::: - https://stackoverflow.com/a/34923514/12343998
:::
::: - DEL and ESC can be used with and without DelayedExpansion, except during Macro Definition
Setlocal
For /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
Endlocal
Set "DEL=%%a"
Set "/AE=%%b"
)
::: \
::: / Establish Environment for macro Definition
Setlocal DisableDelayedExpansion
(Set LF=^
%= NewLine =%)
Set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"
::: \
::: / Ascii code variable assignment
::: - Variables used for cursor Positiong Ascii codes in the form of bookends to prevent ansi escape code disrupting macro definition
Set "[=%/AE%["
Set "]=H"
::: - define Variables for Ascii color code values
Set "Red=%/AE%[31m"
Set "Green=%/AE%[32m"
Set "Yellow=%/AE%[33m"
Set "Blue=%/AE%[34m"
Set "Purple=%/AE%[35m"
Set "Cyan=%/AE%[36m"
Set "White=%/AE%[37m"
Set "Grey=%/AE%[90m"
Set "Pink=%/AE%[91m"
Set "BrightGreen=%/AE%[92m"
Set "Beige=%/AE%[93m"
Set "Aqua=%/AE%[94m"
Set "Magenta=%/AE%[95m"
Set "Teal=%/AE%[96m"
Set "BrightWhite=%/AE%[97m"
Set "Off=%/AE%[0m"
::: \
::: / mini-Macro to Pseudo pipe complex strings into Macros.
Set "Param|=Set Arg-Output="
::: \
::: / Macro for outputing to cursor position Arg1 in color Arg2
Set Pos.Color=^&for /L %%n in (1 1 2) do if %%n==2 (%\n%
For /F "tokens=1,2 delims=, " %%G in ("!argv!") do (%\n%
Echo(![!%%G!]!!%%H!!Arg-Output!!Off!^&^&Endlocal%\n%
) %\n%
) ELSE setlocal enableDelayedExpansion ^& set argv=,
::: \
::: / Macro variable for creating a Colored prompt with pause at Cursor pos Arg1 in Color Arg2
Set Prompt.Pause=^&for /L %%n in (1 1 2) do if %%n==2 (%\n%
For /F "tokens=1,2 delims=, " %%G in ("!argv!") do (%\n%
Echo.!/AE![%%G!]!!/AE![%%Hm!Arg-Output!!Off!%\n%
pause^>nul ^&^& Endlocal%\n%
) %\n%
) ELSE setlocal enableDelayedExpansion ^& set argv=,
::: \
::: / Macro variable for outputing to stdout on a new line with selected color Arg1 and store output to VarName Arg2
Set std.out=^&for /L %%n in (1 1 2) do if %%n==2 (%\n%
For /F "tokens=1,2 delims=, " %%G in ("!argv!") do (%\n%
Echo.!/AE![%%Gm!Arg-Output!!Off!^&^& Endlocal ^&(Set %%H=!Arg-Output!)%\n%
) %\n%
) ELSE setlocal enableDelayedExpansion ^& set argv=,
::: \
::: / Stringlength Macro. Not utilized in this example.
::: Usage: %Param|%string or expanded variable%get.strLen% ResultVar
Set get.strLen=^&for /L %%n in (1 1 2) do if %%n==2 (%\n%
For /F "tokens=1,* delims=, " %%G in ("!argv!") do (%\n%
Set tmpLen=!Arg-Output!%\n%
Set LenTrim=Start%\n%
For /L %%a in (1,1,250) Do (%\n%
IF NOT "!LenTrim!"=="" (%\n%
Set LenTrim=!tmpLen:~0,-%%a!%\n%
If "!LenTrim!"=="" Echo.>nul ^&^& Endlocal ^&(Set %%G=%%a)%\n%
)%\n%
) %\n%
) %\n%
) ELSE setlocal enableDelayedExpansion ^& set argv=,
::: \
::: / Create Script break for Subroutines. Subroutines not utilized in this example
Goto :main
::: \
::: / Subroutines
::: \
::: / Script main Body
:::::: - Example usage
:main
Setlocal EnableDelayedExpansion
For %%A in ("31,1,37" "41,1,47" "90,1,97" "100,1,107") do For /L %%B in (%%~A) Do %Param|%[Color Code = %%B.]%std.out% %%B AssignVar
Set "XP=20"
For %%A in (red aqua white brightwhite brightgreen beige blue magenta green pink cyan grey yellow purple teal) do (
Set /A XP+=1
Set /A YP+=1
Set "output=%%A !YP!;!XP!"
%Param|%Cursor Pos: !YP!;!XP!, %%A %Pos.Color% !YP!;!XP! %%A
)
%Param|%Example %green%Complete.%prompt.pause% 32;10 31
Endlocal
Exit /B
::: \ End Script
My thanks to @Martijn Pieters for deleting my previous answer. In rewriting my code I also discovered for myself some new ways to manipulate macro's.
Several methods are covered in
"51} How can I echo lines in different colors in NT scripts?"
http://www.netikka.net/tsneti/info/tscmd051.htm
One of the alternatives: If you can get hold of QBASIC, using colors is relatively easy:
@echo off & setlocal enableextensions
for /f "tokens=*" %%f in ("%temp%") do set temp_=%%~sf
set skip=
findstr "'%skip%QB" "%~f0" > %temp_%\tmp$$$.bas
qbasic /run %temp_%\tmp$$$.bas
for %%f in (%temp_%\tmp$$$.bas) do if exist %%f del %%f
endlocal & goto :EOF
::
CLS 'QB
COLOR 14,0 'QB
PRINT "A simple "; 'QB
COLOR 13,0 'QB
PRINT "color "; 'QB
COLOR 14,0 'QB
PRINT "demonstration" 'QB
PRINT "By Prof. (emer.) Timo Salmi" 'QB
PRINT 'QB
FOR j = 0 TO 7 'QB
FOR i = 0 TO 15 'QB
COLOR i, j 'QB
PRINT LTRIM$(STR$(i)); " "; LTRIM$(STR$(j)); 'QB
COLOR 1, 0 'QB
PRINT " "; 'QB
NEXT i 'QB
PRINT 'QB
NEXT j 'QB
SYSTEM 'QB
Combining dbenham's bird and syntax with skrebbel's powershell write-host
method, it seems that powershell can render complex art more quickly than dbenham's pure batch method (well, after powershell has been primed once, anyway). Minimal massaging of the strings are needed, although I haven't tested this with anything other than the bird. If you want a bright green end-of-transmission character for example, you may be out of luck. :)
This method requires echoing out to a temp file, simply because invoking powershell for each call :c
takes forever, and it's much faster to queue the output for one powershell invocation. But it does have the advantage of simplicity and efficiency.
@echo off
setlocal disableDelayedExpansion
set q=^"
echo(
echo(
call :c 0E " , .-;" /n
call :c 0E " , |\ / / __," /n
call :c 0E " |\ '.`-.| |.'.-'" /n
call :c 0E " \`'-: `; : /" /n
call :c 0E " `-._'. \'|" /n
call :c 0E " ,_.-=` ` ` ~,_" /n
call :c 0E " '--,. "&call :c 0c ".-. "&call :c 0E ",=!q!." /n
call :c 0E " / "&call :c 0c "{ "&call :c 0A "* "&call :c 0c ")"&call :c 0E "`"&call :c 06 ";-."&call :c 0E "}" /n
call :c 0E " | "&call :c 0c "'-' "&call :c 06 "/__ |" /n
call :c 0E " / "&call :c 06 "\_,\|" /n
call :c 0E " | (" /n
call :c 0E " "&call :c 0c "__ "&call :c 0E "/ ' \" /n
call :c 02 " /\_ "&call :c 0c "/,'`"&call :c 0E "| ' "&call :c 0c ".-~!q!~~-." /n
call :c 02 " |`.\_ "&call :c 0c "| "&call :c 0E "/ ' , "&call :c 0c "/ \" /n
call :c 02 " _/ `, \"&call :c 0c "| "&call :c 0E "; , . "&call :c 0c "| , ' . |" /n
call :c 02 " \ `, "&call :c 0c "| "&call :c 0E "| , , "&call :c 0c "| : ; : |" /n
call :c 02 " _\ `, "&call :c 0c "\ "&call :c 0E "|. , "&call :c 0c "| | | | |" /n
call :c 02 " \` `. "&call :c 0c "\ "&call :c 0E "| ' "&call :c 0A "|"&call :c 0c "\_|-'|_,'\|" /n
call :c 02 " _\ `, "&call :c 0A "`"&call :c 0E "\ ' . ' "&call :c 0A "| | | | | "&call :c 02 "__" /n
call :c 02 " \ `, "&call :c 0E "| , ' "&call :c 0A "|_/'-|_\_/ "&call :c 02 "__ ,-;` /" /n
call :c 02 " \ `, "&call :c 0E "\ . , ' .| | | | | "&call :c 02 "_/' ` _=`|" /n
call :c 02 " `\ `, "&call :c 0E "\ , | | | | |"&call :c 02 "_/' .=!q! /" /n
call :c 02 " \` `, "&call :c 0E "`\ \/|,| ;"&call :c 02 "/' .=!q! |" /n
call :c 02 " \ `, "&call :c 0E "`\' , | ; "&call :c 02 "/' =!q! _/" /n
call :c 02 " `\ `, "&call :c 05 ".-!q!!q!-. "&call :c 0E "': "&call :c 02 "/' =!q! /" /n
call :c 02 " jgs _`\ ;"&call :c 05 "_{ ' ; "&call :c 02 "/' =!q! /" /n
call :c 02 " _\`-/__"&call :c 05 ".~ `."&call :c 07 "8"&call :c 05 ".'.!q!`~-. "&call :c 02 "=!q! _,/" /n
call :c 02 " __\ "&call :c 05 "{ '-."&call :c 07 "|"&call :c 05 ".'.--~'`}"&call :c 02 " _/" /n
call :c 02 " \ .=!q!` "&call :c 05 "}.-~!q!'"&call :c 0D "u"&call :c 05 "'-. '-..' "&call :c 02 "__/" /n
call :c 02 " _/ .!q! "&call :c 05 "{ -'.~('-._,.'"&call :c 02 "\_,/" /n
call :c 02 " / .!q! _/'"&call :c 05 "`--; ; `. ;" /n
call :c 02 " .=!q! _/' "&call :c 05 "`-..__,-'" /n
call :c 02 " __/'" /n
if exist "%temp%\color.psm1" (
powershell -command "&{set-executionpolicy remotesigned; Import-Module '%temp%\color.psm1'}"
del "%temp%\color.psm1"
)
echo(
exit /b
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:c <color pair> <string> </n>
setlocal enabledelayedexpansion
set "colors=0-black;1-darkblue;2-darkgreen;3-darkcyan;4-darkred;5-darkmagenta;6-darkyellow;7-gray;8-darkgray;9-blue;a-green;b-cyan;c-red;d-magenta;e-yellow;f-white"
set "p=%~1"
set "bg=!colors:*%p:~0,1%-=!"
set bg=%bg:;=&rem.%
set "fg=!colors:*%p:~-1%-=!"
set fg=%fg:;=&rem.%
if not "%~3"=="/n" set "br=-nonewline"
set "str=%~2" & set "str=!str:'=''!"
>>"%temp%\color.psm1" echo write-host '!str!' -foregroundcolor '%fg%' -backgroundcolor '%bg%' %br%
endlocal
Result:
You should download chgcolor.zip from http://www.mailsend-online.com/blog/setting-text-color-in-a-batch-file.html and also download echoj.zip from www.mailsend-online.com/blog/?p=41 They're both towards the bottom of the page. Extract both folders to the desktop and copy the executables(.exe files) from inside the extracted folders to the C:\Windows directory. This will allow them to be executed from the command line. Open up notepad and copy the following into it:
@echo off
chgcolor 03
echoj "hi "
chgcolor 0d
echoj "world"
chgcolor 07
echoj $0a
Save the file to the Desktop as hi.bat. Now open the command prompt and navigate to your Desktop folder and type "hi.bat" without the quotes. That should get you started besure to read both webpages to get a full tutorial.
jeb's edited answer comes close to solving all the issues. But it has problems with the following strings:
"a\b\"
"a/b/"
"\"
"/"
"."
".."
"c:"
I've modified his technique to something that I think can truly handle any string of printable characters, except for length limitations.
Other improvements:
Uses the %TEMP% location for the temp file, so no longer need write access to the current directory.
Created 2 variants, one takes a string literal, the other the name of a variable containing the string. The variable version is generally less convenient, but it eliminates some special character escape issues.
Added the /n option as an optional 3rd parameter to append a newline at the end of the output.
Backspace does not work across a line break, so the technique can have problems if the line wraps. For example, printing a string with length between 74 - 79 will not work properly if the console has a line width of 80.
@echo off
setlocal
call :initColorPrint
call :colorPrint 0a "a"
call :colorPrint 0b "b"
set "txt=^" & call :colorPrintVar 0c txt
call :colorPrint 0d "<"
call :colorPrint 0e ">"
call :colorPrint 0f "&"
call :colorPrint 1a "|"
call :colorPrint 1b " "
call :colorPrint 1c "%%%%"
call :colorPrint 1d ^"""
call :colorPrint 1e "*"
call :colorPrint 1f "?"
call :colorPrint 2a "!"
call :colorPrint 2b "."
call :colorPrint 2c ".."
call :colorPrint 2d "/"
call :colorPrint 2e "\"
call :colorPrint 2f "q:" /n
echo(
set complex="c:\hello world!/.\..\\a//^<%%>&|!" /^^^<%%^>^&^|!\
call :colorPrintVar 74 complex /n
call :cleanupColorPrint
exit /b
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:colorPrint Color Str [/n]
setlocal
set "str=%~2"
call :colorPrintVar %1 str %3
exit /b
:colorPrintVar Color StrVar [/n]
if not defined %~2 exit /b
setlocal enableDelayedExpansion
set "str=a%DEL%!%~2:\=a%DEL%\..\%DEL%%DEL%%DEL%!"
set "str=!str:/=a%DEL%/..\%DEL%%DEL%%DEL%!"
set "str=!str:"=\"!"
pushd "%temp%"
findstr /p /A:%1 "." "!str!\..\x" nul
if /i "%~3"=="/n" echo(
exit /b
:initColorPrint
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do set "DEL=%%a"
<nul >"%temp%\x" set /p "=%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%.%DEL%"
exit /b
:cleanupColorPrint
del "%temp%\x"
exit /b
UPDATE 2012-11-27
This method fails on XP because FINDSTR displays backspace as a period on the screen. jeb's original answer works on XP, albeit with the limitations already noted
UPDATE 2012-12-14
There has been a lot of development activity at DosTips and SS64. It turns out that FINDSTR also corrupts file names containing extended ASCII if supplied on the command line. I've updated my FINDSTR Q&A.
Below is a version that works on XP and supports ALL single byte characters except 0x00 (nul), 0x0A (linefeed), and 0x0D (carriage return). However, when running on XP, most control characters will display as dots. This is an inherent feature of FINDSTR on XP that cannot be avoided.
Unfortunately, adding support for XP and for extended ASCII characters slows the routine down :-(
Just for fun, I grabbed some color ASCII art from joan stark's ASCII Art Gallery and adapted it for use with ColorPrint. I added a :c entry point just for shorthand, and to handle an issue with quote literals.
@echo off
setlocal disableDelayedExpansion
set q=^"
echo(
echo(
call :c 0E " , .-;" /n
call :c 0E " , |\ / / __," /n
call :c 0E " |\ '.`-.| |.'.-'" /n
call :c 0E " \`'-: `; : /" /n
call :c 0E " `-._'. \'|" /n
call :c 0E " ,_.-=` ` ` ~,_" /n
call :c 0E " '--,. "&call :c 0c ".-. "&call :c 0E ",=!q!." /n
call :c 0E " / "&call :c 0c "{ "&call :c 0A "* "&call :c 0c ")"&call :c 0E "`"&call :c 06 ";-."&call :c 0E "}" /n
call :c 0E " | "&call :c 0c "'-' "&call :c 06 "/__ |" /n
call :c 0E " / "&call :c 06 "\_,\|" /n
call :c 0E " | (" /n
call :c 0E " "&call :c 0c "__ "&call :c 0E "/ ' \" /n
call :c 02 " /\_ "&call :c 0c "/,'`"&call :c 0E "| ' "&call :c 0c ".-~!q!~~-." /n
call :c 02 " |`.\_ "&call :c 0c "| "&call :c 0E "/ ' , "&call :c 0c "/ \" /n
call :c 02 " _/ `, \"&call :c 0c "| "&call :c 0E "; , . "&call :c 0c "| , ' . |" /n
call :c 02 " \ `, "&call :c 0c "| "&call :c 0E "| , , "&call :c 0c "| : ; : |" /n
call :c 02 " _\ `, "&call :c 0c "\ "&call :c 0E "|. , "&call :c 0c "| | | | |" /n
call :c 02 " \` `. "&call :c 0c "\ "&call :c 0E "| ' "&call :c 0A "|"&call :c 0c "\_|-'|_,'\|" /n
call :c 02 " _\ `, "&call :c 0A "`"&call :c 0E "\ ' . ' "&call :c 0A "| | | | | "&call :c 02 "__" /n
call :c 02 " \ `, "&call :c 0E "| , ' "&call :c 0A "|_/'-|_\_/ "&call :c 02 "__ ,-;` /" /n
call :c 02 " \ `, "&call :c 0E "\ . , ' .| | | | | "&call :c 02 "_/' ` _=`|" /n
call :c 02 " `\ `, "&call :c 0E "\ , | | | | |"&call :c 02 "_/' .=!q! /" /n
call :c 02 " \` `, "&call :c 0E "`\ \/|,| ;"&call :c 02 "/' .=!q! |" /n
call :c 02 " \ `, "&call :c 0E "`\' , | ; "&call :c 02 "/' =!q! _/" /n
call :c 02 " `\ `, "&call :c 05 ".-!q!!q!-. "&call :c 0E "': "&call :c 02 "/' =!q! /" /n
call :c 02 " jgs _`\ ;"&call :c 05 "_{ ' ; "&call :c 02 "/' =!q! /" /n
call :c 02 " _\`-/__"&call :c 05 ".~ `."&call :c 07 "8"&call :c 05 ".'.!q!`~-. "&call :c 02 "=!q! _,/" /n
call :c 02 " __\ "&call :c 05 "{ '-."&call :c 07 "|"&call :c 05 ".'.--~'`}"&call :c 02 " _/" /n
call :c 02 " \ .=!q!` "&call :c 05 "}.-~!q!'"&call :c 0D "u"&call :c 05 "'-. '-..' "&call :c 02 "__/" /n
call :c 02 " _/ .!q! "&call :c 05 "{ -'.~('-._,.'"&call :c 02 "\_,/" /n
call :c 02 " / .!q! _/'"&call :c 05 "`--; ; `. ;" /n
call :c 02 " .=!q! _/' "&call :c 05 "`-..__,-'" /n
call :c 02 " __/'" /n
echo(
exit /b
:c
setlocal enableDelayedExpansion
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:colorPrint Color Str [/n]
setlocal
set "s=%~2"
call :colorPrintVar %1 s %3
exit /b
:colorPrintVar Color StrVar [/n]
if not defined DEL call :initColorPrint
setlocal enableDelayedExpansion
pushd .
':
cd \
set "s=!%~2!"
:: The single blank line within the following IN() clause is critical - DO NOT REMOVE
for %%n in (^"^
^") do (
set "s=!s:\=%%~n\%%~n!"
set "s=!s:/=%%~n/%%~n!"
set "s=!s::=%%~n:%%~n!"
)
for /f delims^=^ eol^= %%s in ("!s!") do (
if "!" equ "" setlocal disableDelayedExpansion
if %%s==\ (
findstr /a:%~1 "." "\'" nul
<nul set /p "=%DEL%%DEL%%DEL%"
) else if %%s==/ (
findstr /a:%~1 "." "/.\'" nul
<nul set /p "=%DEL%%DEL%%DEL%%DEL%%DEL%"
) else (
>colorPrint.txt (echo %%s\..\')
findstr /a:%~1 /f:colorPrint.txt "."
<nul set /p "=%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%"
)
)
if /i "%~3"=="/n" echo(
popd
exit /b
:initColorPrint
for /f %%A in ('"prompt $H&for %%B in (1) do rem"') do set "DEL=%%A %%A"
<nul >"%temp%\'" set /p "=."
subst ': "%temp%" >nul
exit /b
:cleanupColorPrint
2>nul del "%temp%\'"
2>nul del "%temp%\colorPrint.txt"
>nul subst ': /d
exit /b
Source: Stackoverflow.com