Search code examples
windowsbatch-filecommand-lineforfiles

If statement for ForFiles based on file date


I have a batch file that I call via SQL server agent.

Currently I have:

ForFiles /p "C:\folder\subfolder" /d -7 /c "cmd /c del @file"

The command works fine if there is a file older than 7days.

If there isn't a file that meets the criteria then the script fails causing SQL to report failure.

Ideally I need to add and if statement that if a file exists that is older than 7 days then carry out the delete command otherwise ignore it.

Any guidance?


Solution

  • Try this:

    cd /d C:\folder\subfolder
    SET _CmdResult=NONE
    FOR /F "tokens=*" %%a IN ('forfiles -p "C:\folder\subfolder" -s -m *.* -d -7 -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
    

    it checks for an error, and will put the error into a variable and then we set the errorlevel to zero if found.