How to delete files with specific names in windows 10 using batch file?

Could you please help me with a command for batch file to delete the files with Name of the file.

I need to delete the files which are older than 6 months according to their File name. I need to schedule the script in Task scheduler, So it will delete the files in specific location every day which are older than 6 months from current date according to their file name.

Location of files:


File Names:


1 answer

  • answered 2020-10-23 11:14 Gerhard

    Here is a modified version of Aacini's post, from back in 2013. I only amended it to use powershell to get today's date, instead of using the locale specific %date% variable and some changes to accomodate your environment. So I take no credit for this whatsoever.

    @echo off
    setlocal EnableDelayedExpansion
    pushd "K:\Bck"
    for /f "tokens=*" %%i in ('PowerShell -Command "& {Get-Date -format 'yyyyMMdd'}"') do set todayDate=%%i
    call :DateToJDN %todayDate% todayJDN=
    for /F "tokens=1-4* delims=_" %%a in ('dir /B /A-D "Backup_*.txt"') do (
       call :DateToJDN %%b%%c%%~nd fileJDN=
       set /A daysOld=todayJDN - fileJDN
       if !daysOld! gtr 180 (
          echo File "%%a_%%b_%%c_%%d" is !daysOld! days old
          echo del "%%a_%%b_%%c_%%d" /Q
    goto :eof
    :DateToJDN yyyymmdd jdn=
    set yyyymmdd=%1
    set /A yyyy=%yyyymmdd:~0,4%, mm=1%yyyymmdd:~4,2% %% 100, dd=1%yyyymmdd:~6% %% 100
    set /A a=(mm-14)/12, %2=(1461*(yyyy+4800+a))/4+(367*(mm-2-12*a))/12-(3*((yyyy+4900+a)/100))/4+dd-32075
    exit /B

    This will NOT yet delete anything. It will simply echo the commands to the screen. If you are sure the echo'd results resemble what you want, you can remove the echo from the line echo del "%%a_%%b_%%c_%%d" /Q

    You also need to set your days accordingly in the line if !daysOld! gtr 180 (