Solved How to skip error in batch file if no files found to delete

February 20, 2018 at 08:11:01
Specs: Windows 10
We are trying to delete log files older than 30 days from a server path using a batch script. Our intention is that if files older than 30 days are not found batch file should not give error.

Can someone please help how to achieve this by using If else statement in batch file

See More: How to skip error in batch file if no files found to delete

Report •

February 21, 2018 at 01:04:56
✔ Best Answer
batch cant calculate date diffrences accuratly, try a call to VBScript, but this batch file can do roughly 30 days.

anyways, here i go:

note that %temp% has to be replaced with your path to your directory/folder you want to run this script on.
& this is not tested, so make a backup of the folder& or test it on a smaller folder.

::----start of test.bat----
@echo off&setlocal enabledelayedexpansion
set "dirpath=%temp%"
pushd "!dirpath!"
set datum=%date:~-10%
for /f "tokens=1,2,3,*" %%a in ('dir/A-D ^| find ".log"') do (
if exist "%%d" (
set filedate=%%a
::checking if date differs 30 days or more
set/a filedatesum=!filedate:~-4!*365+!filedate:~0,2!+!filedate:~3,2!*30+30
set/a datumsum=%datum:~-4%*365+%datum:~0,2%+%datum:~3,2%*30
if !filedatesum! GTR !datumsum! del "%%d"
echo script has finished&pause&exit/b
::----end of test.bat----

i5-6600K[delid]@4.814GHz/4.613GHz cache@1.385v | 2x4GB Crucial-DDR4-2133@14-14-14-28 1T 2808MHz@1.37v
Samsung 250GB SSD 850 EVO
MSI Armor RX 570 4GB@1340c/1965m BiosMod

Report •
Related Solutions

Ask Question