title: Batch script to delete older backup files in a folder created by date with the exception of the newest 5 files
body: <p>I have a program that creates a backup every 30 minutes, but does not delete older files. I am looking to make a script that will run on task scheduler that will look in the folder that is created by the program. It creates folder by date as follows /year/month/day/*name of file.zip. I have done a little research and come up with</p>
  
  <pre><code>@ECHO OFF
  for /f "usebackq delims== tokens= 2" %%i in ( WMIC OS GET localdatetime /format:value ) do set localTime=%%i
  set "YYYY=%localTime:~0,4%"
  set "M=%localTime:~4,1%"
  set "MM=%localTime:~5,1%"
  set "D=%localTime:~6,1%"
  set "DD=%localTime:~7,1%"
  if %M%==0 set M=
  if %D%==0 set D=
  cd /d "~%~dp0"
  FOR /F "tokens=*" %%X IN ('dir .\%YYYY%\%M%%MM%\%D%%DD%\Backup-serversave-%YYYY%-%M%%MM%-%D%%DD%--*.zip /b /o:-d') DO set FILENAME=%%~X
  rem FILENAME now contains the last element
  if "%FILENAME%" neq "" DEL "%FILENAME%"
  pause
  </code></pre>
  
  <p>This script looks in the folder by todays date and than should delete the file that is oldest in the folder. But every time I run it, all I get is a "cannot find file" and it tells me the exact file that it says it can't find. So I need a little help to make it work. It would be also great if there is any way to make it only delete after five files are in the folder. If anyone can help me that would be amazing. </p>
  
  <p>Update. Got a good answer but need a little more help. If anyone out there can find a way to make it delete yesterdays folder at the change of the day that would be amazing I am looking all over and so far have found nothing.</p>