如何读取批处理文件中的错误输出流?

How to read error output stream in batch file?

我有一个启动服务器的批处理脚本。 该服务器然后将其日志打印到 STDOUT 和 STDERR 以防出现错误。

我想将 STDOUT 和 STDERR 都重定向到一个 tee 命令以拆分输出。 使用 UnxUtils 中的 tee 命令效果很好。

然而,为了使我的应用程序可移植,我不能依赖 UnxUtils,所以我需要编写自己的 tee 命令。

我写了一个批处理脚本,按照 this answer(2. 代码块)中的建议读出 STDOUT。

这有效,但仅适用于重定向的 STDOUT,不适用于 STDERR。

注意:文件和命令行中都缺少 STDERR 的输出。

如何让它读取两个流?

如何重定向输出(%1 是服务器,%2 是我希望日志转到的文件)?

%1 2>&1 | %~dp0tee.bat -a %2

这工作正常(因为它调用 UnxUtils,而不是我的批处理脚本):

%1 2>&1 | tee -a %2

我如何读取 tee.bat 中的输入:

for /F "tokens=*" %%a in ('findstr /n $') do (
    set "line=%%a"
    setlocal EnableDelayedExpansion
    set "line=!line:*:=!"

    echo(!line!

    if %append%==true (
        echo(!line! >> %output%
    ) else (
        echo(!line! > %output%
    )
    endlocal
)

PowerShell 有一个 Tee-Object cmdlet。 $Input 变量接收标准输入。

echo asf 2>&1 | powershell -NoLogo -NoProfile -Command "$Input | Tee-Object -FilePath './tee.txt'"

另请参阅: