如何记录批处理文件的错误和成功。

huangapple go评论42阅读模式
英文:

How to log a Batch file error and success

问题

我有一个简单的程序,根据文件扩展名删除文件,该程序由Windows任务触发。我想创建一个日志文件,如果运行成功,它会显示“成功”,如果失败,它会显示“删除失败”。我不确定如何为此创建日志文件。

@echo off
del "D:\BACnet-CSV\Test csv files\Test1\*.csv"
IF %ERRORLEVEL% NEQ 0 goto ERROR
echo SUCCESSFUL
exit /b 0

:ERROR
echo Delete Failed
exit /b 1

我已经搜索了网络并尝试了几种方法,只是无法正确显示。

英文:

I have a simple program which deletes a file based on the extension, which is triggered by a Windows Task. I would like to create a log file which if ran would say successful or if it failed would say Delete Failed. I'm not sure how to create the log file for this.

@echo off
del "D:\BACnet-CSV\Test csv files\Test1\*.csv" 
IF %ERRORLEVEL% NEQ 0 goto ERROR
echo SUCCESSFUL
exit /b 0

:ERROR
echo Delete Failed
exit /b 1

Thanks

I've searched the Web and tried several things, just couldn't get it to show correctly.

答案1

得分: -1

你可以这样检查文件是否已被删除:

@echo off
set LOFILE=D:\BACnet-CSV\Delete_Log_Files\log.txt
echo %DATE% %TIME% >> %LOGFILE%

if not exist "D:\BACnet-CSV\Test csv files\Test1\*.csv" (
  echo NOTHING TO DELETE >> %LOGFILE%
  exit /b 0
)
del "D:\BACnet-CSV\Test csv files\Test1\*.csv"

if exist "D:\BACnet-CSV\Test csv files\Test1\*.csv" (
  echo FAILED >> %LOGFILE%
  exit /b 1
) else (
  echo SUCCESSFUL >> %LOGFILE%
  exit /b 0
)

DEL不会设置ERRORLEVEL,如果它没有删除文件,因此你需要稍作调整。

如果你想摆脱删除消息,可以使用:

```batch
del "D:\BACnet-CSV\Test csv files\Test1\*.csv" 2>nul

你还需要确保你的日志目录存在,否则你将看不到日志文件。

英文:

You can check if the files have been deleted like so:

@echo off
set LOFILE=D:\BACnet-CSV\Delete_Log_Files\log.txt
echo %DATE% %TIME% >>%LOGFILE%

if not exist "D:\BACnet-CSV\Test csv files\Test1\*.csv" (
  echo NOTHING TO DELETE >>%LOGFILE%
  exit /b 0
)
del "D:\BACnet-CSV\Test csv files\Test1\*.csv"

if exist "D:\BACnet-CSV\Test csv files\Test1\*.csv" (
  echo FAILED >>%LOGFILE%
  exit /b 1
) else (
  echo SUCCESSFUL >>%LOGFILE%
  exit /b 0
)

DEL does not set ERRORLEVEL if it doesn't delete a file, so you have to work around this a little.

If you want to get rid of the deletion message, use

del "D:\BACnet-CSV\Test csv files\Test1\*.csv" 2>nul

You also need to make sure that your log directory exists, or else you won't see the logfile.

huangapple
  • 本文由 发表于 2023年4月6日 22:10:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75950501.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定