I'm writing a for loop to execute the forfiles command on both .xml and .psr files. Currently, if it finds one file type but not the other, it will display "ERROR: No files found with the specified search criteria", but I want the error to say which file type wasn't found. I have an if statement inside the for loop that's supposed to override the error, but it's not working. Here's the loop:
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
)
)
Edit: Thanks for the answers. My for loop now works as intended and ended up looking like this:
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.
)
)
Standard delayed expansion
error - You need to invoke delayedexpansion [hundreds of SO articles about that - use the search feature] in order to display or use the run-time value of any variable that's changed within a parenthesised series of instructions (aka "code block").
IF %ERRORLEVEL% NEQ 0 (
is the problem - errorlevel
is replaced by its value when the for
is encountered.
The easy way around this is to use conventional errorlevel
processing:
if errorlevel 1 (
ie. if errorlevel
is (1 or greater than 1)
As for the message, try 2>nul
to redirect errormessages to nul
OR use
if exist "%xmldir%\%%G" (forfiles...
) else (echo no %%G files found)