【问题标题】:How can I have color text output in a windows batch file that is called with the output being redirected to a file?如何在将输出重定向到文件时调用的 Windows 批处理文件中输出彩色文本?
【发布时间】:2018-07-31 17:20:01
【问题描述】:

我正在运行一个批处理文件,其中 std 输出被重定向到一个文件,我想在控制台上显示的输出中获取彩色文本。我找到了一些可以提供彩色文本的东西,但我不知道如何将它发送到控制台。这有效,但在重定向标准输出时无效: How to have multiple colors in a Windows batch file?

我这样调用批处理文件:
我的批处理 >myoutput.txt

我的批处理文件如下所示:

:: Sample Batch file
@echo off
@echo this goes to the text file when std output is redirected
@echo this goes to the console >CON
call :ColorText 19 "This uses the above referenced method to print in blue, but doesn't go to the console" & echo( 
.
.
.
:ColorText
    <nul set /p ".=%DEL%" > "%~2"
    findstr /v /a:%1 /R "^$" "%~2" nul
    del "%~2" > nul 2>&1
    goto :eof

如何让该文本进入控制台?

【问题讨论】:

  • nul 本身是什么意思?
  • 你需要把goto :EOF放在:ColorText之前!变量DEL 设置为什么?
  • 不确定 nul 是什么意思,只是从引用的链接复制/粘贴。
  • 理解 goto :EOF...这只是示例代码
  • 您似乎选择在 Jeb 的回答中仅使用部分所需代码。

标签: windows batch-file colors stdout


【解决方案1】:

您可以考虑使用批处理文件中的PowerShell,而不是使用FindStr

PowerShell -NoProfile "'This is written to a file and also printed to the console in blue'|Add-Content 'output.log' -PassThru|Write-Host -ForegroundColor Blue"

使用别名可以缩短一点:

PowerShell -NoP "'This is written to a file and also printed to the console in blue'|AC 'output.log' -Pas|Write-Host -F Blue"

您甚至可以同时指定背景颜色,[-BackgroundColor|-B]:

PowerShell -NoP "'This is written to a file and also printed to the console in blue with a yellow background'|AC 'output.log' -Pas|Write-Host -F Blue -B Yellow"

允许的颜色为BlackDarkBlueDarkGreenDarkCyanDarkRedDarkMagentaDarkYellowGrayDarkGray、@98765433 GreenCyanRedMagentaYellowWhite

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多