Search code examples
batch-filecmdforfiles

If file older than X days -> run command -- CMD


I'm writing a script for DriveSnapshot run on various Windows Server versions. I want to run a specific batchfile (fullbackup) if there is a file older than 6 days in a folder. If there are no such files -> run a differential backup.

I tried:

ForFiles /p "path\to\folder" /d -6 /c "cmd /c set var=1"
if %var% == 1 (
   fullbackup.bat
) else (
   diffbackup.bat
)

But it seems you can't just run any command within ForFiles.

It seems the variable never gets assigned the proper value.

The Microsoft Docs page for ForFiles reads:

Runs the specified command on each file. Command strings should be enclosed in quotation marks.*

I know my command would set var=1 for every file it finds, but should still work, right?

If there is any better way to go at this problem, please enlighten me...


Solution

  • The command line behind the /C switch of the forfiles command are not running in the hosting cmd instance, you are actually even explicitly creating a new one (by cmd /C).

    But there is a simpler approach, utilising the exit code of forfiles together with conditional execution operators && and ||:

    forfiles /P "D:\path\to\folder" /D -6 > nul 2>&1 && (
        "D:\path\to\fullbackup.bat"
    ) || (
        "D:\path\to\diffbackup.bat"
    )
    

    Usually I recommend to use call to run another batch file from a batch file, but here in this case I intentionally skipped it, because call "fullbackup.bat" may return an exit code of the batch file in its own that might unintentionally be recognised by ||.

    If you do need to use call when there are other commands following I would use this:

    forfiles /P "D:\path\to\folder" /D -6 > nul 2>&1 && (
        call "D:\path\to\fullbackup.bat" & goto :NEXT
    ) || (
        call "D:\path\to\diffbackup.bat"
    )
    :NEXT
    

    Note that forfiles also iterates over directories but not just files.