1

I have here a batchfile wherein it will delete yesterday's files.

Why is it deleting everything instead the specified date? Any tips/hints?

@echo off


set "source=E:\test"

set day=-1

echo >"%temp%\%~n0.vbs" s=DateAdd("d",%day%,now) : d=weekday(s)
echo>>"%temp%\%~n0.vbs" WScript.Echo year(s)^& right(100+month(s),2)^& right(100+day(s),2)
for /f %%a in ('cscript /nologo "%temp%\%~n0.vbs"') do set "result=%%a"
del  "%temp%\%~n0.vbs"
set "YYYY=%result:~0,4%"
set "MM=%result:~4,2%"
set "DD=%result:~6,2%"
set "result=%yyyy%%mm%%dd%"
echo %result%

for /r "E:\test" %%G in (*%result%.txt) do (

DEL /F /Q "%%~fG" "E:\test"

if not exist "E:\test%%~nxG" (

    echo File "%%~fG" Deleted
    ) else (
    echo File "%%~fG" was not Deleted
   )
)
pause

I am trying to learn how to use this shorter method : Link

1 Answers1

1

In short, it deletes everything because you are telling it to do so:

DEL /F /Q "%%~fG" "E:\test"

When telling the del command to delete from a directory with the /Force and /Quiet options, it will forcefully and quiely delete everything in that folder. That is exactly what you are telling the command to do. You are concatenating first delete the file with the date if found, then delete everything in the directory. It should simply be:

del /F /Q "%%~fG"

To demonstrate what happens, create the following batch file. at each pause, check the result for what was deleted, before pressing any key to continue:

@echo off
mkdir E:\DelTest
echo test>E:\DelTest\test20200225.txt
echo test>E:\DelTest\test20200224.txt
echo test>E:\DelTest\test20200223.txt
del E:\DelTest\*20200224.txt
dir /b E:\DelTest
pause
del /F /Q E:\DelTest
dir /b E:\Deltest
pause
rmdir /Q E:\DelTest >nul >2&1
del %~0

del /? from cmd provides:

Specifies a list of one or more files or directories.

Gerhard
  • 22,678
  • 7
  • 27
  • 43