Batch - 忽略FORFILES “no files found” error

Posted frankcui

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Batch - 忽略FORFILES “no files found” error相关的知识,希望对你有一定的参考价值。

ref:https://stackoverflow.com/questions/16820681/suppress-forfiles-no-files-found-error

 

Solution:

The solution is to capture the output of the FORFILES command in a FOR loop, search it for strings starting with ERROR, and store the result in a variable. From there, you can use IF/ELSE directives to set the errorlevel accordingly. Here‘s the code (minus some logging and comments):

cd /d C:WindowsSystem32
SET _CmdResult=NONE
FOR /F "tokens=*" %%a IN (‘FORFILES /P "[file path...]IDOC_ARCHIVE" /M *.* /D -14 /C "cmd /c DEL @file" 2^>^&1 ^| FINDSTR ERROR‘) DO SET _CmdResult=%%a
IF "%_CmdResult%" == "ERROR: No files found with the specified search criteria." ( 
    SET errorlevel=0 
 ) ELSE ( 
    SET errorlevel=1
 )
IF "%_CmdResult%" == "NONE" SET errorlevel=0

 

Just make sure to escape any characters such as >&| in the FOR loop.

 

Test Code:

ECHO "Remove old takara book dump files from network directory \global.comgmEUunitycredit_devACETraderMetricsSybaseTakaraBookData older than 7 days"

SET _CmdResult=NONE
FOR /F "tokens=*" %%a IN (‘FORFILES /P "\global.comgmEUunitycredit_devACETraderMetricsSybaseTakaraBookData" /M *.* /D -7 /C "cmd /c echo @path" 2^>^&1 ^| FINDSTR ERROR‘) DO SET _CmdResult=%%a
IF "%_CmdResult%" == "ERROR: No files found with the specified search criteria." (
    SET errorlevel=0
 ) ELSE (
    SET errorlevel=1
 )
IF "%_CmdResult%" == "NONE" SET errorlevel=0

ECHO "Find all 7 days older files in certain path, PRINT its FILE PATH..."
PushD "\global.comgmEUunitycredit_devACETraderMetricsSybaseTakaraBookData" &&(
    forfiles -s -m *.* /D -7 /C "cmd /c echo @path"
     ) & PopD

ECHO "Find all 7 days older files in certain path, DELETE it..."
PushD "\global.comgmEUunitycredit_devACETraderMetricsSybaseTakaraBookData" &&(
    forfiles -s -m *.* /D -7 /C "cmd /c del @path"
     ) & PopD

IF "%ERRORLEVEL%"=="0" (
    set ERRORLEVEL=0
    exit /B 0

) ELSE (
    ECHO "ERRORLEVEL=%ERRORLEVEL%"
    exit /B %ERRORLEVEL%
)

 

以上是关于Batch - 忽略FORFILES “no files found” error的主要内容,如果未能解决你的问题,请参考以下文章

[转帖]FORFILES 的简单介绍。

字段投影中忽略的 batchSize 字段名称

Windows forfiles(删除历史文件)

如何摆脱扩展的“forfiles”变量中的双引号?

如何在忽略类中使用 pytorch 闪电精度?

如何使用FORFILES命令来删除SQL Server备份