【问题标题】:Batch File Success and Error logging批处理文件成功和错误记录
【发布时间】:2016-06-28 12:49:25
【问题描述】:

有没有办法在批处理文件中记录批处理文件的错误和成功?

我正在尝试将文件从我的计算机复制到 200 台机器(效果很好),但想知道哪个失败以及失败的原因(因为屏幕消失得很快)。

@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 ERRORLEVEL 1 (
echo failed

 net use l: \\%1\c$ password /user:%1\administrator

) else (
goto mappingError

) > command.txt

:::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::

@echo copying link file to C: Drive
copy "c:\_\CopyFileToHost\logoff.cmd" l:\

:::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::

@echo deleting l: mapping
net use l: /delete /y

@echo off
goto :eof

:usage
@echo Usage: %0 hostname
exit /B 1

:mappingError
@echo Error mapping remote drive, exiting
exit /B 1

【问题讨论】:

  • 您可以记录命令的错误和成功,但不能记录批处理文件。 %1 是否会包含空格或非字母数字字符?是否要记录映射驱动器失败或任何文件复制错误?
  • 我想记录映射失败和任何文件复制错误。如果我只能选择一个,那么我会想要文件复制错误。和 %1 将只包含字母数字字符 - 没有空格。

标签: batch-file cmd


【解决方案1】:

首先,不要使用

if [%1]==[] goto usage

因为方括号在这里没有任何特殊含义。更好的是使用

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

双引号字符具有特殊含义,因为它可以比较包含 1 个或多个空格或 1 个或多个字符 &()[]{}^=;!'+,`~ 的字符串。

%~1 表示删除了周围双引号的第一个参数。通过在命令提示符窗口call /? 中运行查看帮助输出以了解更多详细信息。

其次,阅读微软关于Using command redirection operatorsTesting for a Specific Error Level in Batch Files的文章,了解下面的批处理代码。

@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

写入 stderr 的错误消息由2>&1 附加到 stdout,标准消息默认写入其中。写入 stdout 的所有内容都被重定向到当前目录中的文件 command.txt,因此文本文件包含正确输出顺序的标准和错误消息。

如果您希望将命令也写入文本文件,以便更轻松地确定哪个命令来自哪个错误或标准消息,echo 也可以添加命令。

【讨论】:

    【解决方案2】:

    这是简单的日志记录 - 只需检查驱动器是否已映射以及文件名是否出现在映射的驱动器上,然后将日志写入您的桌面。

    @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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-12
      • 2022-01-23
      • 2018-04-21
      • 2016-04-13
      • 2022-07-01
      • 1970-01-01
      相关资源
      最近更新 更多