Batch File Success and Error logging

后端 未结 2 843
伪装坚强ぢ
伪装坚强ぢ 2021-01-16 09:33

Is there a way, within a batch file, to log the error and success of the batch file?

I am trying to copy a file from my computer to 200 machines (works great) but wa

2条回答
  •  生来不讨喜
    2021-01-16 09:54

    First, don't use

    if [%1]==[] goto usage
    

    because the square brackets don't have any special meaning here. Better is using

    if "%~1"=="" goto usage
    

    The double quote character has a special meaning because it makes it possible to compare strings containing 1 or more spaces or 1 or more of the characters &()[]{}^=;!'+,`~.

    %~1 means first argument with surrounding double quotes removed. See help output by running in a command prompt window call /? for more details.

    Second, read the Microsoft articles about Using command redirection operators and Testing for a Specific Error Level in Batch Files to understand the batch code below.

    @echo off
    if "%~1"=="" goto usage
    %SystemRoot%\System32\net.exe use L: /delete /y 2>nul
    (
        echo Mapping L: to %~1\c$ ...
        %SystemRoot%\System32\net.exe use L: "\\%~1\c$" password /user:%~1\administrator /persistent:no
        if not errorlevel 1 (
            echo Copying the file X ...
            rem copy X L:\
            echo Disconnecting network drive L: ...
            %SystemRoot%\System32\net.exe use L: /delete /y
        )
    ) >command.txt 2>&1
    goto :EOF
    
    :usage
    echo Call this batch file with name of computer as parameter.
    echo.
    pause
    

    Error messages written to stderr are appended to stdout by 2>&1 to which standard messages are written by default. And everything written to stdout is redirected to file command.txt in current directory and therefore the text file contains standard and error messages in right output order.

    If you want the commands also written to the text file to easier determine from which command which error or standard message comes, echo additionally the commands, too.

提交回复
热议问题