在 FOR 循环中使用 FORFILES 并尝试覆盖错误
Using FORFILES in a FOR loop and trying to override the error
我正在编写一个 for 循环来对 .xml 和 .psr 文件执行 forfiles 命令。目前,如果它找到一种文件类型但找不到另一种文件类型,它将显示 "ERROR: No files found with the specified search criteria",但我希望错误提示未找到哪种文件类型。我在 for 循环中有一个 if 语句,它应该覆盖错误,但它不起作用。这是循环:
FOR %%G IN (.xml, .psr) DO (
FORFILES /P "%xmlDir%" /M *%%G /D -%days% /C "CMD /C DEL @FILE"
IF %ERRORLEVEL% NEQ 0 (
ECHO No matches found for %%G files older than %days% days
)
)
编辑:感谢您的回答。我的 for 循环现在按预期工作并最终看起来像这样:
FOR %%G IN (.xml, .psr) DO (
FORFILES /P "%xmlDir%" /M *%%G /D -%days% /C "CMD /C DEL @FILE" >nul 2>nul
IF ERRORLEVEL 1 (
ECHO No %%G files %days% days old or older were found.
) ELSE (
ECHO %%G files as old as %days% days or older have been deleted.
)
)
标准 delayed expansion
错误 - 您需要调用 delayedexpansion [数百篇关于它的 SO 文章 - 使用搜索功能] 才能显示或使用在其中更改的任何变量的 run-time 值带括号的一系列指令(又名 "code block")。
IF %ERRORLEVEL% NEQ 0 (
是问题 - 当遇到 for
时,errorlevel
被其值替换。
解决此问题的简单方法是使用常规 errorlevel
处理:
if errorlevel 1 (
即。如果 errorlevel
是(1 或大于 1)
至于消息,请尝试 2>nul
将错误消息重定向到 nul
或使用
if exist "%xmldir%\%%G" (forfiles...
) else (echo no %%G files found)
我正在编写一个 for 循环来对 .xml 和 .psr 文件执行 forfiles 命令。目前,如果它找到一种文件类型但找不到另一种文件类型,它将显示 "ERROR: No files found with the specified search criteria",但我希望错误提示未找到哪种文件类型。我在 for 循环中有一个 if 语句,它应该覆盖错误,但它不起作用。这是循环:
FOR %%G IN (.xml, .psr) DO (
FORFILES /P "%xmlDir%" /M *%%G /D -%days% /C "CMD /C DEL @FILE"
IF %ERRORLEVEL% NEQ 0 (
ECHO No matches found for %%G files older than %days% days
)
)
编辑:感谢您的回答。我的 for 循环现在按预期工作并最终看起来像这样:
FOR %%G IN (.xml, .psr) DO (
FORFILES /P "%xmlDir%" /M *%%G /D -%days% /C "CMD /C DEL @FILE" >nul 2>nul
IF ERRORLEVEL 1 (
ECHO No %%G files %days% days old or older were found.
) ELSE (
ECHO %%G files as old as %days% days or older have been deleted.
)
)
标准 delayed expansion
错误 - 您需要调用 delayedexpansion [数百篇关于它的 SO 文章 - 使用搜索功能] 才能显示或使用在其中更改的任何变量的 run-time 值带括号的一系列指令(又名 "code block")。
IF %ERRORLEVEL% NEQ 0 (
是问题 - 当遇到 for
时,errorlevel
被其值替换。
解决此问题的简单方法是使用常规 errorlevel
处理:
if errorlevel 1 (
即。如果 errorlevel
是(1 或大于 1)
至于消息,请尝试 2>nul
将错误消息重定向到 nul
或使用
if exist "%xmldir%\%%G" (forfiles...
) else (echo no %%G files found)