修改批处理脚本以有条件地写入文件

时间:2013-05-02 11:49:56

标签: batch-file

我有一个从互联网上复制的批处理文件。 需要一些帮助。 批处理从命令或其他批处理中获取输出,并将输出回显到控制台和指定文件。回调到控制台很好,但有没有办法只在条件满足时写入文件?可能是如果回显的文本包含一些字符串说“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

1 个答案:

答案 0 :(得分: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时的错误级别。

<小时/> 要禁止“不写入日志”标志,请尝试

::实际TEE SETLOCAL enabledelayedexpansion FOR / F“tokens = 1 * delims =]”%% A IN('FIND / N / V“”')DO(   SET message = %% B   IF DEFINED消息SET message =!message:LOGMESSAGE =!

  

CON ECHO(!消息!     如果“%% B”==“!message!” &GT;&GT; %File%ECHO(%% B   )   ENDLOCAL

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