Batch file that will delete files that are older than 6 months, but will exclude files listed in a separate text file

63 Views Asked by At

Just wanted to ask for help in batch file. I need to have a text file where the file names of excluded files would be stored in the deletion of files with 6 months above date.

Inside list.txt are trial.csv, trial2.csv which are older than 6 months but should be excluded in the deletion since it is in my list.

I have this code but can't seem to make it work. Please help

@echo off

set exclude_file=C:\Users\Desktop\Test\list.txt
set directory=C:\Users\Desktop\Test

forfiles /p %directory% /s /m *.* /c "cmd /c if @fdate < %date% -180 and not @isdir == true (find /i ""@fname"" < %exclude_file% >nul || del /q @path)"

pause
1

There are 1 best solutions below

0
GB-CCSA On

If you are okay with using Powershell, try this. Would recommend using a -whatif on the remove-item line for testing. Use at your own risk...

$protectedFiles = Get-Content -Path "C:\Users\Desktop\Test\list.txt" | Where {$_}

$oldFiles = Get-ChildItem -Path "C:\Users\Desktop\Test" -File -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt (Get-Date.AddMonths(-6)} 

Foreach($oldFile in $oldFiles){
    If ($protectedFiles -NotContains $($_.Name)){Remove-Item $_ -Force}
}