ss64 comando color cambiar windows batch-file colors character-encoding cmd

comando - ¿Cómo tener múltiples colores en un archivo por lotes de Windows?



comando color cmd (13)

Me preguntaba si es posible tener texto de diferentes colores en la misma línea en un archivo por lotes de Windows, por ejemplo, si dice

echo hi world

Quiero que "hola" sea un color y que "mundo" sea otro color. Tal vez podría establecer el comando COLOR como una variable:

set color1= color 2 set color9= color A

y luego desplegarlos a ambos en la misma línea junto con

echo hi world

pero no sé cómo haría eso.


A menos que esté usando un sistema operativo anterior, creo que esto no es posible con los comandos disponibles para usted.

Sin embargo, no todo está perdido, eche un vistazo a esta página:

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

Esto le dará exactamente lo que necesita, pero el inconveniente es que necesita agregar las utilidades en esa página.


Combinando la sintaxis y el pájaro de dbenham con el método powershell write-host skrebbel , parece que powershell puede renderizar arte complejo más rápidamente que el método de lote puro de dbenham (bueno, después de que powershell haya sido preparado una vez, de todos modos). Se necesita un masaje mínimo de las cuerdas, aunque no he probado esto con otra cosa que no sea el pájaro. Si desea un personaje verde brillante al final de la transmisión, por ejemplo, puede que no tenga suerte. :)

Este método requiere hacer eco en un archivo temporal, simplemente porque se invoca PowerShell para cada call :c toma para siempre, y es mucho más rápido poner en cola la salida para una invocación de PowerShell. Pero tiene la ventaja de la simplicidad y la eficiencia.

@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

Resultado:


Debe descargar chgcolor.zip desde http://www.mailsend-online.com/blog/setting-text-color-in-a-batch-file.html y también descargar echoj.zip desde www.mailsend-online.com / blog /? p = 41 Ambos están hacia la parte inferior de la página. Extraiga ambas carpetas en el escritorio y copie los ejecutables (archivos .exe) desde el interior de las carpetas extraídas al directorio C: / Windows. Esto les permitirá ser ejecutados desde la línea de comando. Abre el bloc de notas y copia lo siguiente en él:

@echo off

chgcolor 03

echoj "hola"

chgcolor 0d

echoj "mundo"

chgcolor 07

echoj $ 0a

Guarde el archivo en el escritorio como hi.bat. Ahora abra el símbolo del sistema y navegue a su carpeta de escritorio y escriba "hi.bat" sin las comillas. Eso debería ayudarte a comenzar a leer ambas páginas web para obtener un tutorial completo.


En realidad, esto se puede hacer sin crear un archivo temporal. El método descrito por jeb y dbenham funcionará incluso con un archivo de destino que no contenga retrocesos. El punto crítico es que la línea reconocida por findstr.exe no debe terminar con un CRLF. Así que el archivo de texto obvio para escanear con una línea que no termina con un CRLF es el lote de invocación en sí mismo, ¡siempre que lo terminemos con esa línea! Aquí hay un script de ejemplo actualizado que funciona de esta manera ...

Cambios desde el ejemplo anterior:

  • Utiliza un solo trazo en la última línea como cadena de búsqueda. (Debe ser corto y no aparecer en ningún otro lugar como este en el lote).
  • Las rutinas y variables renombradas son un poco más orientadas a objetos :-)
  • Se eliminó un nivel de llamada para mejorar ligeramente el rendimiento.
  • Comentarios añadidos (A partir de: # para que se parezca más a la mayoría de los otros lenguajes de scripting).

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

PD. Estoy teniendo un problema con la salida de! personaje que no tenías en el ejemplo anterior. (O al menos no tuvo los mismos síntomas). Para ser investigado.


La respuesta editada de jeb se acerca a resolver todos los problemas. Pero tiene problemas con las siguientes cadenas:

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

Modifiqué su técnica a algo que creo que realmente puede manejar cualquier cadena de caracteres imprimibles, a excepción de las limitaciones de longitud.

Otras mejoras:

  • Utiliza la ubicación% TEMP% para el archivo temporal, por lo que ya no necesita acceso de escritura al directorio actual.

  • Creado 2 variantes, una toma una cadena literal, el otro el nombre de una variable que contiene la cadena. La versión variable generalmente es menos conveniente, pero elimina algunos problemas especiales de escape de caracteres.

  • Se agregó la opción / n como tercer parámetro opcional para agregar una nueva línea al final de la salida.

El retroceso no funciona en un salto de línea, por lo que la técnica puede tener problemas si la línea se ajusta. Por ejemplo, imprimir una cadena con una longitud entre 74 - 79 no funcionará correctamente si la consola tiene un ancho de línea de 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


ACTUALIZACIÓN 2012-11-27

Este método falla en XP porque FINDSTR muestra un retroceso como un punto en la pantalla. La respuesta original de jeb funciona en XP, aunque con las limitaciones ya notadas


ACTUALIZACIÓN 2012-12-14

Ha habido mucha actividad de desarrollo en DosTips y SS64 . Resulta que FINDSTR también corrompe los nombres de archivos que contienen ASCII extendido si se suministran en la línea de comandos. Actualicé mi FIN & Q de preguntas y respuestas .

A continuación se muestra una versión que funciona en XP y admite TODOS los caracteres de un solo byte excepto 0x00 (nul), 0x0A (avance de línea) y 0x0D (retorno de carro). Sin embargo, cuando se ejecuta en XP, la mayoría de los caracteres de control se mostrarán como puntos. Esta es una característica inherente de FINDSTR en XP que no se puede evitar.

Desafortunadamente, agregar soporte para XP y para caracteres ASCII extendidos ralentiza la rutina :-(

Solo por diversión, tomé un poco de arte ASCII en color de la galería de arte ASCII de joan stark y lo adapté para usarlo con ColorPrint. Agregué un punto de entrada: c solo para taquigrafía, y para manejar un problema con literales de comillas.

@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


Puede hacer salidas multicolores sin ningún programa externo.

@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

Utiliza la función de color del comando findstr.

Findstr se puede configurar para generar números de línea o nombres de archivo en un color definido.
Así que primero creo un archivo con el texto como nombre de archivo, y el contenido es un único carácter <backspace> (ASCII 8).
Luego busco todas las líneas no vacías en el archivo y en nul, por lo que el nombre del archivo se imprimirá en el color correcto con dos puntos, pero el espacio se eliminará inmediatamente con el <backspace> .

EDITAR: Un año después ... todos los personajes son válidos

@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

Esto usa la regla para una ruta / nombre de archivo válidos.
Si un /../ está en la ruta, el elemento elemet prefijado se eliminará completamente y no es necesario que este elemento contenga solo caracteres de nombre de archivo válidos.


Sí, es posible con cmdcolor :

echo /033[32mhi /033[92mworld

hi será verde oscuro, y verde claro del world .


Si su consola admite códigos de color ANSI (por ejemplo, ConEmu , Clink o ANSICON ) puede hacer esto:

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

donde la variable ESC contiene el carácter ASCII 27.

Encontré una forma de completar la variable ESC aquí: http://www.dostips.com/forum/viewtopic.php?p=6827#p6827 y al usar la tasklist , es posible probar qué archivos DLL están cargados en un proceso.

El siguiente script obtiene el ID del proceso de cmd.exe en el que se ejecuta el script. Comprueba si tiene un dll que agregará el soporte ANSI inyectado, y luego establece las variables de color para que contengan secuencias de escape o que esté vacío dependiendo de si el color es compatible. o no.

@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


Si tiene un Windows moderno (que tiene instalado PowerShell), lo siguiente también puede funcionar bien

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

Ajuste el color como mejor le parezca.


Solo para completar este tema, también puede mostrar texto en color usando mi programa auxiliar ColorShow.exe; Puede descargarlo desde este sitio , busque el programa # 12. Tenga en cuenta que la primera parte de la documentación aparece en el programa # 2-Show.exe.

Hay varios programas auxiliares en ese sitio que permiten lograr algunas cosas interesantes. Por ejemplo, el programa # 6-CursorPos.exe permite mover el cursor a cualquier lugar de la pantalla.

Este es un ejemplo de salida producido por un archivo por lotes utilizando mi programa auxiliar ColorShow.exe:

El archivo por lotes tomó menos de 3 segundos para mostrar la imagen anterior, que tiene una resolución de 322x138 (usando la fuente Lucida Console @ tamaño 5). Puede revisar el método utilizado para producir esta imagen en esta publicación .

EDITAR : Publiqué un método mucho más simple para obtener el programa ColorShow.exe y una breve descripción de él; solo sigue este enlace


Varios métodos están cubiertos en
"51} ¿Cómo puedo hacer eco de líneas en diferentes colores en scripts NT?"
http://www.netikka.net/tsneti/info/tscmd051.htm

Una de las alternativas: si puede hacerse con QBASIC, usar colores es relativamente fácil:

@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


Sin herramientas externas . Se trata de un híbrido bat / .net autocompilado (se debe guardar como .BAT ) que se puede utilizar en cualquier sistema que tenga .NET Framework instalado (es raro ver una ventana sin .NET framework incluso para las instalaciones más antiguas de XP / 2003). Utiliza el compilador jscript.net para crear un exe capaz de imprimir cadenas con diferentes colores de fondo / primer plano solo para la línea actual.

@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://.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;

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

También puede verificar la función de color de carlos -> http://www.dostips.com/forum/viewtopic.php?f=3&t=4453


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