0

我有一个从互联网复制的批处理文件。需要一些帮助。批处理从命令或其他批处理获取输出,并将输出回显到控制台和指定文件。回显到控制台很好,但有没有办法只有在满足条件时才写入文件?可能是回显的文本包含一些字符串,比如“LOGMESSAGE”。因此,如果命令或批处理回显了 2 条消息,则消息 1:“你好,你好吗?” 消息 2:“LOGMESSAGE 谢谢,我很好。”

消息 1 应仅显示在控制台上,消息 2 应同时显示在控制台和文件中。

@ECHO OFF
:: Check Windows version
IF NOT "%OS%"=="Windows_NT" GOTO Syntax

:: Keep variables local
SETLOCAL

:: Check command line arguments
SET Append=0
IF /I [%1]==[-a] (
    SET Append=1
    SHIFT
)
IF     [%1]==[] GOTO Syntax
IF NOT [%2]==[] GOTO Syntax

:: Test for invalid wildcards
SET Counter=0
FOR /F %%A IN ('DIR /A /B %1 2^>NUL') DO CALL :Count "%%~fA"
IF %Counter% GTR 1 (
    SET Counter=
    GOTO Syntax
)

:: A valid filename seems to have been specified
SET File=%1

:: Check if a directory with the specified name exists
DIR /AD %File% >NUL 2>NUL
IF NOT ERRORLEVEL 1 (
    SET File=
    GOTO Syntax
)

:: Specify /Y switch for Windows 2000 / XP COPY command
SET Y=
VER | FIND "Windows NT" > NUL
IF ERRORLEVEL 1 SET Y=/Y

:: Flush existing file or create new one if -a wasn't specified
IF %Append%==0 (COPY %Y% NUL %File% > NUL 2>&1)

:: Actual TEE
FOR /F "tokens=1* delims=]" %%A IN ('FIND /N /V ""') DO (
    >  CON    ECHO.%%B
    >> %File% ECHO.%%B
)

:: Done
ENDLOCAL
GOTO:EOF


:Count
SET /A Counter += 1
SET File=%1
GOTO:EOF


:Syntax
ECHO.
ECHO Tee.bat,  Version 2.11a for Windows NT 4 / 2000 / XP
ECHO Display text on screen and redirect it to a file simultaneously
ECHO.
IF NOT "%OS%"=="Windows_NT" ECHO Usage:  some_command  ¦  TEE.BAT  [ -a ]  filename
IF NOT "%OS%"=="Windows_NT" GOTO Skip
ECHO Usage:  some_command  ^|  TEE.BAT  [ -a ]  filename
:Skip
ECHO.
ECHO Where:  "some_command" is the command whose output should be redirected
ECHO         "filename"     is the file the output should be redirected to
ECHO         -a             appends the output of the command to the file,
    ECHO                        rather than overwriting the file
    ECHO.
ECHO.
ECHO Written by Rob van der Woude
ECHO http://www.robvanderwoude.com
ECHO Modified by Kees Couprie
ECHO http://kees.couprie.org
ECHO and Andrew Cameron
4

1 回答 1

0
...
:: Actual TEE
FOR /F "tokens=1* delims=]" %%A IN ('FIND /N /V ""') DO (
    >  CON    ECHO.%%B
    echo "%%B"|find "LOGMESSAGE" >nul
    IF ERRORLEVEL 1 >> %File% ECHO.%%B
)
...

额外的 FIND 尝试在要记录的消息中定位目标字符串。如果找到,errorlevel将设置为 0,否则设置为非 0。

不要尝试使用"if %errorlevel%==0"此处的语法,因为它位于语句块中,并且该构造不会解释 FIND 中的错误级别,而是FOR解析时的错误级别。


要禁止“不写入日志”标志,请尝试

:: Actual TEE SETLOCAL enabledelayedexpansion FOR /F "tokens=1* delims=]" %%A IN ('FIND /N /V ""') DO ( SET message=%%B IF DEFINED message SET message=!message:日志消息=!

CON ECHO(!message!IF "%%B"=="!message!" >> %File% ECHO(%%B) ENDLOCAL

这应该删除字符串“logmesssage”(在任何一种情况下),并且 - 这个位似乎颠倒了 - 不要将行记录到文件中,而是将行发送到控制台,并删除标志“logmessage”。也许“skiplog”会是一个更好的字符串......

于 2013-05-02T12:07:50.677 回答