CBK
CBK

Reputation: 1

Windows batch script for searching files based on file name,checks if the files are older than N days, if true, it deletes those files

I am a newbie to windows batch scripting. I have researched through the web and the site and tried out the solutions but none seem to give me the desired results.

This is what I want to achieve:


  1. Search for files in a folder using a specific filename
  2. show found files
  3. Check the found files if they are older than 1 day
  4. If true,delete those files
  5. Else return message(Found files not older than 1 day)

From my research I was able to write a batch code that searches for file using a string, but unable to do step 2,3,4 and 5.

Kindly assist.

Here is my batch code:


@echo off & setlocal
set "MySearchString=Scheduled_error"
for /r %%a in (*) do for /f "delims=" %%i in ('echo("%%~na" ^| findstr /i "%MySearchString%"') do echo del "%%~fa"

Upvotes: 0

Views: 361

Answers (1)

MichaelS
MichaelS

Reputation: 6032

Seems like a perfect task for FORFILES!

forfiles /p c:\SomePath\ /s /m *.* /c "cmd /c echo @path" will show you all files older than one day. You can modify the filter replacing *.* with the file name you are looking for.

To delete these files simply replace echo @path with del /y @path and add the /d -1 parameter:

forfiles /p c:\SomePath /s /m *.* /d -1 /c "cmd /c del /y @path"

The age of the files to delete is specified with the /d -1 switch where -1 means 1 day and older.

Upvotes: 1

Related Questions