Question

I'm trying to use forfiles to check a folder for an updated .xlsx file (less than 1 day old) and then run another bat file depending on whether there was an updated file or not.

Initially I had a script that sort of did this, but some days there were multiple new .xlsx files, so the script "looped" and would run the success.bat file multiple times.

If no updated file is found, cmd will exit with an error, so I made use of that to run the fail.bat file.

This is what I have at the moment:

@echo on
set found=0
forfiles /p C:\ /m *.xlsx /d 0 /c "cmd /k set found=1"
if /i %found%==1 (
Call Success.bat
) else (
if /i %found%==0 (
Call Fail.bat  
)
PAUSE

Now this works fine for when there are updated files.. i.e. it gets rid of the loop problem.

BUT I now have the problem with cmd exiting if no updated file is found and using

if ERRORLEVEL 1 call fail.bat

doesn't seem to work for me anymore... I'm just no good with this if/else stuff with .bat files

Was it helpful?

Solution

forfiles /p c:\ /m *.xlsx /d 0 2>nul && call Success.bat || call Fail.bat

2>nul will suppress error messages, you can also add >nul to suppress standard output (any files found by forfiles). If no files exist with the extension then an errorlevel will be set - the commands following || will only occur if an error level is set.

Therefore, if no files are found with the specified extension this will call Fail.bat, and goto the end of the script. If files are found, it will call Success.bat.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top