-2

I need help to create a batch file that will delete log files in D:/folderx on Server:\serverx This is to eliminate the manual process of cleaning up the disk to avoid a page out of low disk space. Files with extension .txt, .trc and .phd that are older then 5 days to be deleted.

Anyone any idea?

Thanks in advance

Dan

  • 1
    please provide us work that you did so far and where you're actually stuck... – alexus Feb 27 '15 at 21:09
  • 3
    Stop using batch files. Use Powershell. This is an opportunity to learn powershell. This script should be trivial in powershell, and I bet you could find tons of examples on how to do this in powershell via a Google search. – Zoredache Feb 27 '15 at 21:23
  • I'm with @Zoredache on this one. You can get away with using VBS as well for this if you need something a bit simpler or PS seems overwhelming. Let's see what you've already done first though. – MikeAWood Feb 27 '15 at 22:37

2 Answers2

2

I just happen to have something like this lying around.

forfiles -p "D:/folderx"  -s -m *.* /D -5 /C "cmd /c del @path /q

That's all files; to specify extensions you'd modify the *.* bit.

forfiles -p "D:/folderx"  -s -m *.txt /D -5 /C "cmd /c del @path /q
forfiles -p "D:/folderx"  -s -m *.trc /D -5 /C "cmd /c del @path /q
forfiles -p "D:/folderx"  -s -m *.phd /D -5 /C "cmd /c del @path /q

(I still kick it old skool sometimes because I have a library of old skool stuff lying around I can reuse. I'm rewriting that library in powershell, though, as time goes by.)

Katherine Villyard
  • 18,550
  • 4
  • 37
  • 59
2

I agree with other comments that PowerShell should be used going forward for these kinds of automation tasks. Here's a small script that would perform the cleanup you describe. You can find various ways to run PowerShell from a batch file if you need to for some reason, e.g. this answer. Better yet, just run directly from a scheduled task or an automation tool.

Example script:

$DIRECTORY = "D:\folderx"
$MAX_AGE_DAYS = 5
$matchedFiles = Get-ChildItem $DIRECTORY | where {$_.Extension.ToLower() -match "txt|trc|phd" -and $_.CreationTime -lt (Get-Date).AddDays(-1*$MAX_AGE_DAYS)}
$matchedFiles | Remove-Item
Noah Stahl
  • 453
  • 2
  • 8