如何在Windowsbatch file中有多种颜色?

我想知道是否有可能在Windowsbatch file中的同一行上有不同的彩色文本,例如,如果它说

echo hi world 

我希望“嗨”是一种颜色,“世界”是另一种颜色。 也许我可以将COLOR命令设置为一个variables:

 set color1= color 2 set color9= color A 

然后将它们同时部署在同一行上

 echo hi world 

但我不知道我会怎么做。

其实这可以做到没有创build一个临时文件。 jeb和dbenham描述的方法即使对于不包含退格的目标文件也是可行的。 临界点是由findstr.exe识别的行不能以CRLF结尾。 所以用一条不以CRLF结尾的行扫描的明显的文本文件就是调用批处理本身,只要我们用这样的一行结束它! 这是一个更新的示例脚本,以这种方式工作…

前面例子的变化:

  • 在最后一行使用一个短划线作为可search的string。 (必须很短,不会出现在批处理中的其他任何地方。)
  • 重命名例程和variables,使其更加面向对象:-)
  • 删除了一个通话级别,以略微提高性能。
  • 新增评论(从#开始,看起来更像大多数其他脚本语言)。

 @echo off setlocal call :Echo.Color.Init goto main :Echo.Color %1=Color %2=Str [%3=/n] setlocal enableDelayedExpansion set "str=%~2" :Echo.Color.2 :# Replace path separators in the string, so that the final path still refers to the current path. set "str=a%ECHO.DEL%!str:\=a%ECHO.DEL%\..\%ECHO.DEL%%ECHO.DEL%%ECHO.DEL%!" set "str=!str:/=a%ECHO.DEL%/..\%ECHO.DEL%%ECHO.DEL%%ECHO.DEL%!" set "str=!str:"=\"!" :# Go to the script directory and search for the trailing - pushd "%ECHO.DIR%" findstr /p /r /a:%~1 "^^-" "!str!\..\!ECHO.FILE!" nul popd :# Remove the name of this script from the output. (Dependant on its length.) for /l %%n in (1,1,12) do if not "!ECHO.FILE:~%%n!"=="" <nul set /p "=%ECHO.DEL%" :# Remove the other unwanted characters "\..\: -" <nul set /p "=%ECHO.DEL%%ECHO.DEL%%ECHO.DEL%%ECHO.DEL%%ECHO.DEL%%ECHO.DEL%%ECHO.DEL%" :# Append the optional CRLF if not "%~3"=="" echo. endlocal & goto :eof :Echo.Color.Var %1=Color %2=StrVar [%3=/n] if not defined %~2 goto :eof setlocal enableDelayedExpansion set "str=!%~2!" goto :Echo.Color.2 :Echo.Color.Init set "ECHO.COLOR=call :Echo.Color" set "ECHO.DIR=%~dp0" set "ECHO.FILE=%~nx0" set "ECHO.FULL=%ECHO.DIR%%ECHO.FILE%" :# Use prompt to store a backspace into a variable. (Actually backspace+space+backspace) for /F "tokens=1 delims=#" %%a in ('"prompt #$H# & echo on & for %%b in (1) do rem"') do set "ECHO.DEL=%%a" goto :eof :main call :Echo.Color 0a "a" call :Echo.Color 0b "b" set "txt=^" & call :Echo.Color.Var 0c txt call :Echo.Color 0d "<" call :Echo.Color 0e ">" call :Echo.Color 0f "&" call :Echo.Color 1a "|" call :Echo.Color 1b " " call :Echo.Color 1c "%%%%" call :Echo.Color 1d ^""" call :Echo.Color 1e "*" call :Echo.Color 1f "?" :# call :Echo.Color 2a "!" call :Echo.Color 2b "." call :Echo.Color 2c ".." call :Echo.Color 2d "/" call :Echo.Color 2e "\" call :Echo.Color 2f "q:" /n echo( set complex="c:\hello world!/.\..\\a//^<%%>&|!" /^^^<%%^>^&^|!\ call :Echo.Color.Var 74 complex /n exit /b :# The following line must be last and not end by a CRLF. - 

PS。 我遇到了输出的问题! 前面例子中没有的字符。 (或者至less你没有相同的症状。)被调查。

你可以做任何外部程序的多色输出。

 @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 

它使用findstr命令的颜色特征。

Findstr可以configuration为以定义的颜色输出行号或文件名。
所以我首先创build一个文件作为文件名,内容是一个<backspace>字符(ASCII 8)。
然后,我search文件中的所有非空行,并且以nul为单位,所以文件名将以正确的颜色输出,而且冒号被<backspace>立即删除。

编辑:一年后…所有的字符都是有效的

 @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 

这使用有效path/文件名的规则。
如果\..\位于path中,则前缀元素将被完全删除,并且不需要该元素仅包含有效的文件名字符。

杰布的编辑答案接近解决所有问题。 但它有以下string的问题:

 "a\b\" "a/b/" "\" "/" "." ".." "c:" 

我已经将他的技术修改为我认为可以真正处理任何可打印字符的string,除了长度限制之外。

其他改进:

  • 使用临时文件的%TEMP%位置,因此不再需要对当前目录的写入访问权限。

  • 创build了两个变体,一个是string,另一个是包含string的variables的名称。 variables版本通常不太方便,但它消除了一些特殊的字符转义问题。

  • 添加了/ n选项作为可选的第三个参数,以便在输出结尾附加一个换行符。

退格不起作用换行符,所以如果行换行,该技术可能会有问题。 例如,如果控制台的行宽为80,则打印长度在74 – 79之间的string将无法正常工作。

 @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 

更新2012-11-27

此方法在XP上失败,因为FINDSTR在屏幕上显示退格作为句点。 杰布的原始答案适用于XP,尽pipe已经注意到了局限性

更新2012-12-14

DosTips和SS64已经有很多开发活动。 事实certificate,如果在命令行中提供的话,FINDSTR也会破坏包含扩展ASCII的文件名。 我已经更新了我的FINDSTR问答 。

下面是一个在XP上运行的版本,支持除0x00(nul),0x0A(linefeed)和0x0D(回车)之外的所有单字节字符。 但是,在XP上运行时,大多数控制字符将显示为点。 这是FINDSTR在XP上的固有特性,无法避免。

不幸的是,增加对XP和扩展ASCII字符的支持会降低程序的速度:-(

为了好玩,我从joan stark的ASCII Art Gallery中撷取了一些彩色的ASCII艺术,并将其改编为ColorPrint。 我添加了一个简单的c入口点,并用引用字面值来处理问题。

 @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 

如果你有一个现代的Windows(已安装PowerShell),下面的工作也可以

 call :PrintBright Something Something (do actual batch stuff here) call :PrintBright Done! goto :eof :PrintBright powershell -Command Write-Host "%*" -foreground "White" 

根据需要调整颜色。

没有外部工具 。这是一个自编的bat / .net混合体 (应该保存为.BAT ),可以在任何已经安装.net框架的系统上使用(很less见到一个没有.NET框架的窗口甚至是为最旧的XP / 2003安装)。 它使用jscript.net编译器来创build一个exe文件,只能为当前行打印不同背景/前景色的string。

 @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; 

示例coloroutput.bat -s "aa\nbb\n\u0025cc" -b 10 -f 3 -n -e

您也可以检查carlos的颜色function – > http://www.dostips.com/forum/viewtopic.php?f=3&t=4453

是的,这可能与cmdcolor

 echo \033[32mhi \033[92mworld 

hi将是深绿色, world – 浅绿色。

将dbenham的鸟和语法与skrebbel的powershell write-host方法相结合,似乎powershell可以比dbenham的纯批处理方法更快地渲染复杂的艺术(不过,Powerhell已经启动一次后,无论如何)。 尽pipe我没有testing过除鸟之外的其他东西,但需要尽可能less的按摩。 如果你想要一个明亮的绿色传输结束字符,例如,你可能会运气不好。 🙂

这个方法需要回显到一个临时文件,只是因为调用每个调用powershell call :c需要永远,并且为一个powershell调用排队输出要快得多。 但它确实具有简单和高效的优点。

 @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 

结果:

在这里输入图像描述

为了完成这个主题,您也可以使用我的ColorShow.exe辅助程序以彩色显示文本; 你可以从这个网站下载,find程序#12。 请注意,文档的第一部分出现在程序#2-Show.exe中。

在该网站有几个辅助程序,可以实现一些有趣的事情。 例如,程序#6-CursorPos.exe允许将光标移动到屏幕上的任何位置。

这是使用我的ColorShow.exe辅助程序由batch file生成的输出示例:

蒙娜丽莎丽莎

batch file用不到3秒钟显示以前的图像,分辨率为322×138(使用Lucida控制台字体@大小5)。 您可以在这篇文章中查看用于制作此图片的方法。

编辑 :我发布了一个更简单的方法来获取ColorShow.exe程序和它的简要说明; 只要按照这个链接 。

您应该从http://www.mailsend-online.com/blog/setting-text-color-in-a-batch-file.html下载chgcolor.zip,并从www.mailsend-online.com下载echoj.zip / blog /?p = 41他们都在页面底部。 将这两个文件夹解压缩到桌面,并将解压缩文件夹内的可执行文件(.exe文件)复制到C:\ Windows目录。 这将允许他们从命令行执行。 打开记事本并将以下内容复制到记事本中:

@echoclosures

chgcolor 03

echoj“嗨”

chgcolor 0d

echoj“世界”

chgcolor 07

echoj $ 0a

以hi.bat文件保存到桌面。 现在打开命令提示符并导航到您的桌面文件夹并键入“hi.bat”不带引号。 这应该让你开始保证阅读这两个网页,以获得完整的教程。

有几种方法被覆盖
“51}我怎样才能在NT脚本中以不同颜色显示线条?”
http://www.netikka.net/tsneti/info/tscmd051.htm

其中一个select:如果你可以得到QBASIC,使用颜色是相对容易的:

  @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 

除非您正在使用较旧的操作系统,否则我相信您不可能使用可用的命令。

不过一切都没有丢失,看看这个页面:

http://www.mailsend-online.com/blog/setting-text-color-in-a-batch-file.html

这会给你正是你需要的东西,但不利的一面是,你需要在该页面上添加实用程序。

如果您的控制台支持ANSI颜色代码(例如ConEmu , Clink或ANSICON ),您可以这样做:

 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 

ESCvariables包含ASCII字符27。

我find了一种方法来填充ESCvariables: http : //www.dostips.com/forum/viewtopic.php? tasklist和使用tasklist可以testing哪些DLL加载到一个进程。

以下脚本获取运行脚本的cmd.exe的进程ID。检查它是否具有将添加注入的ANSI支持的dll,然后将颜色variables设置为包含转义序列或为空,具体取决于是否支持颜色或不。

 @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" (ie 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 (eg Administrator) accounts, :: - interactively or in the background. :: - work when the cmd.exe window cannot appear :: eg 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 

All alternatives described thus far use any temporary files. This is bad, it is not always possible to use temporary files. This script below uses no temporary file and can write text on any screen position. The best script for this purpose is this