Batch File Success and Error logging

后端 未结 2 839
伪装坚强ぢ
伪装坚强ぢ 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.

    0 讨论(0)
  • 2021-01-16 10:09

    This is simple logging - just checks if the drive was mapped and if the filename appears on the mapped drive, and writes the log to your desktop.

    @echo off
    if [%1]==[] goto usage
    echo mapping l: to %1\c$
    net use * /delete /y
    net use l: \\%1\c$ password /user:%1\administrator
    if not exist L:\ (echo %1 failed mapping drive letter>>"%userprofile%\desktop\net use log.txt"& goto :EOF)
    
    echo copying link file to C: Drive
    copy "c:\_\CopyFileToHost\logoff.cmd" l:\
    if not exist "L:\logoff.cmd" (echo %1 failed copying "c:\_\CopyFileToHost\logoff.cmd">>"%userprofile%\desktop\net use log.txt")
    
    echo deleting l: mapping
    net use l: /delete /y
    
    goto :eof
    
    :usage
    echo Usage: %0 hostname
    exit /B 1
    
    0 讨论(0)
提交回复
热议问题