如何在Windows命令行中使用不同的颜色进行回显

rui*_*rui 191 windows command-line colors batch-file

我知道该color bf命令设置整个命令行窗口的颜色,但我想以不同的颜色打印一行.

Jen*_*och 252

我想用不同的颜色打印一行.

使用ANSI转义序列.

10之前的Windows - 在控制台上没有本机支持ANSI颜色

对于低于10的Windows版本,Windows命令控制台默认情况下不支持输出着色.您可以安装Cmder,ConEmu,ANSICONMintty(默认情况下在GitBash和Cygwin中使用)来为Windows命令控制台添加着色支持.

Windows 10 - 命令行颜色

从Windows 10开始,Windows控制台默认支持ANSI Escape序列和一些颜色.2015年11月Threshold 2 Update附带的功能.

MSDN文档

演示

在此输入图像描述

批处理命令

win10colors.cmd是由Michele Locati撰写的:

@echo off
cls
echo [101;93m STYLES [0m
echo ^<ESC^>[0m [0mReset[0m
echo ^<ESC^>[1m [1mBold[0m
echo ^<ESC^>[4m [4mUnderline[0m
echo ^<ESC^>[7m [7mInverse[0m
echo.
echo [101;93m NORMAL FOREGROUND COLORS [0m
echo ^<ESC^>[30m [30mBlack[0m (black)
echo ^<ESC^>[31m [31mRed[0m
echo ^<ESC^>[32m [32mGreen[0m
echo ^<ESC^>[33m [33mYellow[0m
echo ^<ESC^>[34m [34mBlue[0m
echo ^<ESC^>[35m [35mMagenta[0m
echo ^<ESC^>[36m [36mCyan[0m
echo ^<ESC^>[37m [37mWhite[0m
echo.
echo [101;93m NORMAL BACKGROUND COLORS [0m
echo ^<ESC^>[40m [40mBlack[0m
echo ^<ESC^>[41m [41mRed[0m
echo ^<ESC^>[42m [42mGreen[0m
echo ^<ESC^>[43m [43mYellow[0m
echo ^<ESC^>[44m [44mBlue[0m
echo ^<ESC^>[45m [45mMagenta[0m
echo ^<ESC^>[46m [46mCyan[0m
echo ^<ESC^>[47m [47mWhite[0m (white)
echo.
echo [101;93m STRONG FOREGROUND COLORS [0m
echo ^<ESC^>[90m [90mWhite[0m
echo ^<ESC^>[91m [91mRed[0m
echo ^<ESC^>[92m [92mGreen[0m
echo ^<ESC^>[93m [93mYellow[0m
echo ^<ESC^>[94m [94mBlue[0m
echo ^<ESC^>[95m [95mMagenta[0m
echo ^<ESC^>[96m [96mCyan[0m
echo ^<ESC^>[97m [97mWhite[0m
echo.
echo [101;93m STRONG BACKGROUND COLORS [0m
echo ^<ESC^>[100m [100mBlack[0m
echo ^<ESC^>[101m [101mRed[0m
echo ^<ESC^>[102m [102mGreen[0m
echo ^<ESC^>[103m [103mYellow[0m
echo ^<ESC^>[104m [104mBlue[0m
echo ^<ESC^>[105m [105mMagenta[0m
echo ^<ESC^>[106m [106mCyan[0m
echo ^<ESC^>[107m [107mWhite[0m
echo.
echo [101;93m COMBINATIONS [0m
echo ^<ESC^>[31m                     [31mred foreground color[0m
echo ^<ESC^>[7m                      [7minverse foreground ^<-^> background[0m
echo ^<ESC^>[7;31m                   [7;31minverse red foreground color[0m
echo ^<ESC^>[7m and nested ^<ESC^>[31m [7mbefore [31mnested[0m
echo ^<ESC^>[31m and nested ^<ESC^>[7m [31mbefore [7mnested[0m
Run Code Online (Sandbox Code Playgroud)

  • 好.感谢您的反馈.`.cmd`或`.bat` - 两者都应该有效.但是,我想我知道为什么它不起作用:似乎在发布到StackOverflow时删除了转义符号.请不要复制我的答案中的内容,而是使用此处的内容:https://gist.githubusercontent.com/mlocati/fdabcaeb8071d5c75a2d51712db24011/raw/b710612d6320df7e146508094e84b92b34c77d48/win10colors.cmd (33认同)
  • 我之前从未在notepad ++中生成`ESC` ...您可以使用小键盘和左ALT键使用ALT代码执行此操作:`L-ALT` +`0` +`2` +`7` (21认同)
  • @Jens A. Koch - 它在我的Windows 10控制台(cmd)中不起作用 (8认同)
  • 顺便说一句,作为一个批量生产和使用大多数日子的人,这个答案以美学的方式增强了我的整体工具集!用VB?一定不行.这是要走的路! (3认同)
  • 您可以通过以下方式在批处理文件中生成`ESC`字符:对于/ F %% a in('echo提示符$ E ^ | cmd'),请设置“ ESC = %% a”。 (2认同)
  • **您可以更改颜色而无需创建新行:`echo | 设置/ p =“ ESCAPECHARACTER [91m”`** (2认同)

npo*_*aka 54

这是一个自编译的bat/.net混合(应保存为.BAT),可用于已安装.net框架的任何系统(即使是最老的XP/2003,看到没有.NET框架的窗口也是罕见的装置).它使用jscript.net编译器创建一个exe,只能为当前行打印具有不同背景/前景色的字符串.

@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;
Run Code Online (Sandbox Code Playgroud)

这是帮助信息:

在此输入图像描述

示例:

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

您也可以在此处找到此脚本.

您还可以查看卡洛斯的颜色功能 - > http://www.dostips.com/forum/viewtopic.php?f=3&t=4453

  • 多么酷啊.一个bat文件,编译其中的jscript,只有在需要的时候 - 我印象深刻.甚至不知道有一个jscript编译器只是坐在那里等待使用.你获得了本月的"精彩奖".你应该提到它的第一次使用会很慢(因为编译). (13认同)
  • 我不需要颜色到达这个极端,但技术真的令人印象深刻,我可以看到自己在其他地方使用它. (3认同)

Iai*_*ain 45

这不是一个好的答案,但如果您知道目标工作站有Powershell,您可以执行类似的操作(假设BAT/CMD脚本):

CALL:ECHORED "Print me in red!"

:ECHORED
%Windir%\System32\WindowsPowerShell\v1.0\Powershell.exe write-host -foregroundcolor Red %1
goto:eof
Run Code Online (Sandbox Code Playgroud)

编辑:( 现在更简单!)

这是一个古老的答案,但我想我会澄清并简化一下

IMG

从7开始,PowerShell现在包含在所有版本的Windows中.因此,此答案的语法可以缩短为更简单的形式:

  • 路径并不需要指定,因为它应该是在环境变量了.
  • 明确的命令可以缩写.例如,你可以:
    • -fore而不是-foregroundcolor
    • -back而不是-backgroundcolor
  • 该命令基本上也可以用' inline '代替echo
    (而不是像上面那样创建一个单独的批处理文件).

例:

powershell write-host -fore Cyan This is Cyan text
powershell write-host -back Red This is Red background
Run Code Online (Sandbox Code Playgroud)

更多信息:

完整的颜色列表和更多信息可在
- PowerShell 文档中找到Write-Host

  • Greate,它适用于我,但它太慢了太oooooooooooooo. (14认同)
  • 我意识到这是一个提供解决方案的答案,但是PowerShell?啊. (4认同)
  • 这就是为什么我从“这不是一个好答案”开始的原因。我非常喜欢Powershell,但这太过分了。如果您可以将ANSICON部署到目标计算机,则它会更好。 (2认同)

Tut*_*men 18

您可以创建具有要打印的单词名称的文件,使用可以彩色打印的findstr,然后擦除文件.试试这个例子:

@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"
)

call :ColorText 0a "green"
call :ColorText 0C "red"
call :ColorText 0b "cyan"
echo(
call :ColorText 19 "blue"
call :ColorText 2F "white"
call :ColorText 4e "yellow"

goto :eof

:ColorText
echo off
<nul set /p ".=%DEL%" > "%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1
goto :eof
Run Code Online (Sandbox Code Playgroud)

运行color /?以获取颜色列表.

  • 这将在Windows命令行中设置颜色.你能解释它的作用吗? (3认同)
  • 好吧,它只是创建带有要打印的单词名称的文件,使用可以打印彩色的findstr,然后擦除文件. (2认同)
  • 这令人印象深刻!请注意,颜色代码是错误的.运行"color /?" 看到实际的颜色代码. (2认同)
  • 请注意,findstr只能对*filename*进行着色,这意味着您不能将此技巧用于包含非法路径字符的字符串. (2认同)
  • 另外值得注意的是,如果它们共享您要打印的内容的名称,这将覆盖同一目录中的文件......这一点都不好. (2认同)

Gri*_*ave 18

Windows 10 - TH2及以上版本:

echo ^[[32m HI ^[[0m
Run Code Online (Sandbox Code Playgroud)

使用实际键:echo Ctrl+[[32m HICtrl+[[0mEnter

你应该看到它下面有一个绿色的"HI".

代码编号可在此处找到:

要将其保存到记事本中,您可以使用以下内容键入ESC:Alt+027使用小键盘,然后使用[32m部件.我在笔记本电脑上的另一个技巧,将上面的行重定向到文件中以开始,然后剪切和粘贴:

echo echo ^[[32m HI ^[[0m >> batch_file.cmd
Run Code Online (Sandbox Code Playgroud)

  • Alt + 027 正是我所需要的! (4认同)

Bry*_*Ash 14

您可以使用ANSICON在现代Windows中启用ANSI终端代码.我在Windows XP和Windows 7中使用了32位和64位版本.


Ole*_*evs 6

我对cmd中缺乏适当的着色感到恼火,所以我继续创建了cmdcolor.它只是一个stdout代理,它寻找一组有限的ANSI/VT100控制序列(换句话说,就像在bash中),即echo \033[31m RED \033[0m DEFAULT | cmdcolor.exe.

用法和下载.


小智 6

我看了这个是因为我想在Win7 Batch文件中引入一些简单的文本颜色.这就是我提出的.谢谢你的帮助.

@echo off
cls && color 08

rem .... the following line creates a [DEL] [ASCII 8] [Backspace] character to use later
rem .... All this to remove [:]
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (set "DEL=%%a")

echo.

<nul set /p="("
call :PainText 09 "BLUE is cold"    && <nul set /p=")  ("
call :PainText 02 "GREEN is earth"  && <nul set /p=")  ("
call :PainText F0 "BLACK is night"  && <nul set /p=")"
echo.
<nul set /p="("
call :PainText 04 "RED is blood"    && <nul set /p=")  ("
call :PainText 0e "YELLOW is pee"   && <nul set /p=")  ("
call :PainText 0F "WHITE all colors"&& <nul set /p=")"

goto :end

:PainText
<nul set /p "=%DEL%" > "%~2"
findstr /v /a:%1 /R "+" "%~2" nul
del "%~2" > nul
goto :eof

:end
echo.
pause
Run Code Online (Sandbox Code Playgroud)


Pav*_*Dub 5

已经有 250 多个赞成票的公认答案。我仍然贡献的原因escape是许多编辑器不接受回显所需的字符(我正在使用,例如 MS Code),并且所有其他解决方案都需要一些第三方(非 Windows 默认)软件。

仅使用普通批处理命令的解决方法是使用PROMPT而不是ECHO. 该PROMPT命令escape以任何编辑器友好的方式接受字符作为$E字符序列。(只需将ASCII 转义码Esc中的替换为)。$E

这是一个演示代码:

@ECHO OFF

    :: Do not pollute environment with the %prompt.bak% variable
    :: ! forgetting ENDLOCAL at the end of the batch leads to prompt corruption
    SETLOCAL

    :: Old prompt settings backup
    SET prompt.bak=%PROMPT%

    :: Entering the "ECHO"-like section

        :: Forcing prompt to display after every command (see below)
        ECHO ON

        :: Setting the prompt using the ANSI Escape sequence(s)
        :: - Always start with $E[1A, otherwise the text would appear on a next line
        :: - Then the decorated text follows
        :: - And it all ends with $E30;40m, which makes the following command invisible
        ::   - assuming default background color of the screen
        @ PROMPT $E[1A$E[30;42mHELLO$E[30;40m

        :: An "empty" command that forces the prompt to display. 
        :: The word "rem" is displayed along with the prompt text but is made invisible
        rem

        :: Just another text to display
        @ PROMPT $E[1A$E[33;41mWORLD$E[30;40m
        rem

        :: Leaving the "ECHO"-like section
        @ECHO OFF

    :: Or a more readable version utilizing the cursor manipulation ASCII ESC sequences

        :: the initial sequence
        PROMPT $E[1A
        :: formating commands
        PROMPT %PROMPT%$E[32;44m
        :: the text
        PROMPT %PROMPT%This is an "ECHO"ed text...
        :: new line; 2000 is to move to the left "a lot"
        PROMPT %PROMPT%$E[1B$E[2000D
        :: formating commands fro the next line
        PROMPT %PROMPT%$E[33;47m
        :: the text (new line)
        PROMPT %PROMPT%...spreading over two lines
        :: the closing sequence
        PROMPT %PROMPT%$E[30;40m

        :: Looks like this without the intermediate comments:
        :: PROMPT $E[1A
        :: PROMPT %PROMPT%$E[32;44m
        :: PROMPT %PROMPT%This is an "ECHO"ed text...
        :: PROMPT %PROMPT%$E[1B$E[2000D
        :: PROMPT %PROMPT%$E[33;47m
        :: PROMPT %PROMPT%...spreading over two lines
        :: PROMPT %PROMPT%$E[30;40m

        :: show it all at once!
        ECHO ON
        rem
        @ECHO OFF

    :: End of "ECHO"-ing

    :: Setting prompt back to its original value
    :: - We prepend the settings with $E[37;40m in case
    ::   the original prompt settings do not specify color
    ::   (as they don't by default).
    :: - If they do, the $E[37;40m will become overridden, anyway.
    :: ! It is important to write this command 
    ::   as it is with `ENDLOCAL` and in the `&` form.
    ENDLOCAL & PROMPT $E[37;40m%prompt.bak%

EXIT /B 0
Run Code Online (Sandbox Code Playgroud)

注意:唯一的缺点是,color如果不明确知道,此技术会与用户 cmd 颜色设置(命令或设置)发生冲突。

- 希望这会有所帮助,因为出于开头提到的原因,这是我唯一可以接受的解决方案。——

编辑:

根据评论,我附上了另一个受@Jeb 启发的片段。它:

  • 演示如何获取和使用“Esc”字符运行时(而不是将其输入到编辑器)(Jeb 的解决方案)
  • 使用“本机”ECHO命令
  • 所以它不会影响本地PROMPT
  • 证明对ECHO输出着色不可避免地会影响PROMPT颜色,因此无论如何都必须重置颜色
@ECHO OFF

    :: ! To observe color effects on prompt below in this script
    ::   run the script from a fresh cmd window with no custom
    ::   prompt settings

    :: Only not to pollute the environment with the %\e% variable (see below)
    :: Not needed because of the `PROMPT` variable
    SETLOCAL

        :: Parsing the `escape` character (ASCII 27) to a %\e% variable
        :: Use %\e% in place of `Esc` in the [http://ascii-table.com/ansi-escape-sequences.php]
        FOR /F "delims=#" %%E IN ('"prompt #$E# & FOR %%E IN (1) DO rem"') DO SET "\e=%%E"

        :: Demonstrate that prompt did not get corrupted by the previous FOR
        ECHO ON
        rem : After for
        @ECHO OFF

        :: Some fancy ASCII ESC staff
        ECHO [          ]
        FOR /L %%G IN (1,1,10) DO (
            TIMEOUT /T 1 > NUL
            ECHO %\e%[1A%\e%[%%GC%\e%[31;43m.
            ECHO %\e%[1A%\e%[11C%\e%[37;40m]
        )

        :: ECHO another decorated text
        :: - notice the `%\e%[30C` cursor positioning sequence
        ::   for the sake of the "After ECHO" test below
        ECHO %\e%[1A%\e%[13C%\e%[32;47mHELLO WORLD%\e%[30C

        :: Demonstrate that prompt did not get corrupted by ECHOing
        :: neither does the cursor positioning take effect.
        :: ! But the color settings do.
        ECHO ON
        rem : After ECHO
        @ECHO OFF

    ENDLOCAL

    :: Demonstrate that color settings do not reset
    :: even when out of the SETLOCAL scope
    ECHO ON
    rem : After ENDLOCAL
    @ECHO OFF

    :: Reset the `PROMPT` color
    :: - `PROMPT` itself is untouched so we did not need to backup it.
    :: - Still ECHOING in color apparently collide with user color cmd settings (if any).
    :: ! Resetting `PROMPT` color this way extends the `PROMPT`
    ::   by the initial `$E[37;40m` sequence every time the script runs.
    :: - Better solution then would be to end every (or last) `ECHO` command
    ::   with the `%\e%[37;40m` sequence and avoid setting `PROMPT` altogether.
    ::   which makes this technique preferable to the previous one (before EDIT)
    :: - I am keeping it this way only to be able to
    ::   demonstrate the `ECHO` color effects on the `PROMPT` above.
    PROMPT $E[37;40m%PROMPT%

    ECHO ON
    rem : After PROMPT color reset
    @ECHO OFF

EXIT /B 0
Run Code Online (Sandbox Code Playgroud)


Dol*_*ens 5

我添加一个答案来解决上面一些评论中指出的问题:内联 ansi 颜色代码在 FOR 循环内(实际上,在任何带括号的代码块内)可能会出现错误行为。 下面的 .bat 代码演示了 (1) 内联颜色代码的使用,(2) 在 FOR 循环中或括号内的代码块中使用内联颜色代码时可能发生的颜色故障,以及 (3) 解决方案问题。 当 .bat 代码执行时,测试 2 和 3 显示颜色代码失败,测试 4 显示没有失败,因为它实现了解决方案。

[编辑 2020-04-07:我找到了另一种解决方案,可能比调用子例程更有效。将 FINDSTR 短语括在括号中,如下行所示:

   echo success | (findstr /R success)
Run Code Online (Sandbox Code Playgroud)

结束编辑]

注意:根据我(有限的)经验,颜色代码问题仅在输入通过管道传输到代码块内的 FINDSTR 后才会显现。这就是下面的 .bat 重现问题的方式。 颜色代码问题可能比通过管道传输到 FINDSTR 后更普遍。如果有人可以解释问题的本质,并且有更好的方法来解决它,我将不胜感激。

@goto :main
:resetANSI
EXIT /B
rem  The resetANSI subroutine is used to fix the colorcode
rem  bug, even though it appears to do nothing.

:main
@echo off
setlocal EnableDelayedExpansion

rem  Define some useful colorcode vars:
for /F "delims=#" %%E in ('"prompt #$E# & for %%E in (1) do rem"') do set "ESCchar=%%E"
set "green=%ESCchar%[92m"
set "yellow=%ESCchar%[93m"
set "magenta=%ESCchar%[95m"
set "cyan=%ESCchar%[96m"
set "white=%ESCchar%[97m"
set "black=%ESCchar%[30m"

echo %white%Test 1 is NOT in a FOR loop nor within parentheses, and color works right.
   echo %yellow%[Test 1] %green%This is Green, %magenta%this is Magenta, and %yellow%this is Yellow.
   echo %Next, the string 'success' will be piped to FINDSTR...
   echo success | findstr /R success
   echo %magenta%This is magenta and FINDSTR found and displayed 'success'.%yellow%
   echo %green%This is green.
echo %cyan%Test 1 completed.

echo %white%Test 2 is within parentheses, and color stops working after the pipe to FINDSTR.
(  echo %yellow%[Test 2] %green%This is Green, %magenta%this is Magenta, and %yellow%this is Yellow.
   echo %Next, the string 'success' will be piped to FINDSTR...
   echo success | findstr /R success
   echo %magenta%This is supposed to be magenta and FINDSTR found and displayed 'success'.
   echo %green%This is supposed to be green.
)
echo %cyan%Test 2 completed.

echo %white%Test 3 is within a FOR loop, and color stops working after the pipe to FINDSTR.
for /L %%G in (3,1,3) do (
   echo %yellow%[Test %%G] %green%This is Green, %magenta%this is Magenta, and %yellow%this is Yellow.
   echo %Next, the string 'success' will be piped to FINDSTR...
   echo success | findstr /R success
   echo %magenta%This is supposed to be magenta and FINDSTR found and displayed 'success'.
   echo %green%This is supposed to be green.
)
echo %cyan%Test 3 completed.

echo %white%Test 4 is in a FOR loop but color works right because subroutine :resetANSI is 
echo called after the pipe to FINDSTR, before the next color code is used.
for /L %%G in (4,1,4) do (
   echo %yellow%[Test %%G] %green%This is Green, %magenta%this is Magenta, and %yellow%this is Yellow.
   echo %Next, the string 'success' will be piped to FINDSTR...
   echo success | findstr /R success
   call :resetANSI
   echo %magenta%This is magenta and FINDSTR found and displayed 'success'.
   echo %green%This is green.
)
echo %cyan%Test 4 completed.%white%

EXIT /B
Run Code Online (Sandbox Code Playgroud)