0

我想从文件夹中删除文件,如果没有要删除的文件,则应忽略错误并捕获所有其他错误。下面是我正在使用的代码。

FOR /F "tokens=*" %%a IN ('FORFILES /P "%%G" /D -3 /C "cmd /c DEL @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

IF NOT %errorlevel% EQU 0 ( 

goto delete_fail )

以下是我在运行上述代码时在命令提示符下看到的内容。

FOR /F "tokens=*" %a IN ('FORFILES /P "%G" /D -2 /C "cmd /c DEL @path" | FINDSTR ERROR') DO SET _CmdResult=%a

 IF "NONE" == "ERROR: No files found with the specified search criteria." <<<<< _CmdResult is still "NONE"

(

SET errorlevel=0  

)  ELSE (

SET errorlevel=1 )

 IF "NONE" == "NONE" SET errorlevel=0

 IF NOT 0 EQU 0 (goto delete_fail  )

根据日志,我发现当没有要删除的文件时,错误字符串没有保存到 _CmdResult 中。谁能让我知道我错过了什么,

4

3 回答 3

1
FOR /F "tokens=*" %%a IN ('FORFILES /P "%%G" /D -3 /C "cmd /c DEL @path" 2^>^&1 ^| FINDSTR ERROR') DO SET _CmdResult=%%a

%%G 表示该行作为外部 for 循环的一部分执行。如果该循环包含显示的其余代码,那么您遇到了延迟扩展的问题。当执行到达一个块(括号之间的代码)时,所有行在执行前都被解析,并且读取变量的行被改变,用它在解析块时包含的值替换对变量的引用。您将需要启用延迟扩展,而不是%var%使用 sintax,而是使用!var!sintax。

IF "%_CmdResult%" == "ERROR: No files found with the specified search criteria." ( 
    SET errorlevel=0 
) ELSE ( 
    SET errorlevel=1
)
IF "%_CmdResult%" == "NONE" SET errorlevel=0

简而言之,不要那样做。不要将 errorlevel 变量设置为任何值。它的值是动态的,读取时由 cmd 提供,但是,如果显式赋值,则无法读取动态值。%errorlevel% 将返回您设置的值。如果将其设置为 0,您将只获得该值,与命令失败的成功无关。它将是 0。

如果您需要重置 errorlevel 值,请使用类似vol > nul

于 2013-12-20T20:42:36.513 回答
0

I tried with below code and it is working as expected. Earlier I missed pasting the outer for loop and sorry for that. I have enabled delayed expansion and with help of that I am able to achieve my requirement.

SET del_op=NONE



rem ###################################
rem - Loop thru all archives to delete
rem ###################################
FOR %%G in (%arc_log%,%arc_in%,%arc_out%) DO ( 

ECHO Deleting files from "%%G" older than %var% days  >> %log_path%\%log_file% 2>>&1

FOR /F "tokens=*" %%a IN ('FORFILES /P "%%G" /D -%var% /C "cmd /c DEL @path" 2^>^&1 ^| FINDSTR ERROR') DO SET del_op=%%a

rem ####################
rem - suppressing error
rem ####################

IF "!del_op!" == "ERROR: No files found with the specified search criteria." ( 
   ECHO suppressed "!del_op!" >> %log_path%\%log_file% 2>>&1
    SET err_lv=0 
 ) ELSE ( 
    SET err_lv=1
)

IF "!del_op!" == "NONE" SET err_lv=0

IF !err_lv! EQU 1 ( 
goto delete_fail )
ECHO Successfully deleted old files from "%%G" >> %log_path%\%log_file% 2>>&1
)

Thanks all for your suggestions.

于 2013-12-24T12:32:42.110 回答
0

在上面的代码之前使用此命令并在错误级别上分支

FORFILES /P "%%G" /D -3 2>&1 |find "ERROR:" >nul
if errorlevel 1 goto :nofiles
FORFILES /P "%%G" /D -3 /C "cmd /c DEL @path"
于 2013-12-21T13:48:30.320 回答