Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 187
  • Last Modified:

Need a script to delete all files older than 3 days from C:\windows\temp on Windows 2008R2 server

I need to write a script to run as a regular task, most likely from Task Scheduler script that will delete all files from the C:\Windows\temp directory that are older than 3 days. Can anyone assist with how to write that given the "older than" or time relationship needed? I'm thinking it would delete anything older than the current time... How would that be written?
0
Noah_Williams35
Asked:
Noah_Williams35
  • 4
  • 2
  • 2
1 Solution
 
becraigCommented:
Powershell

gci c:\temp -recurse | ? {$_.creationtime -gt (Get-Date).AddDays(-3)} | Remove-Item -recurse -Force -whatif

Open in new window


This should find all 3day old files and force a delete.
0
 
oBdACommented:
You can use robocopy for that (without really copying anything); the following batch script is in test mode and will only display the files it would normally delete; remove the uppercase ECHO in front of "del" to run it for real:
@echo off
for /f "tokens=1*" %%a in ('robocopy.exe "%Systemroot%\Temp" "C:\Garbage" *.* /minage:3 /r:0 /l /bytes /nc /ndl /njh /njs') do (ECHO del "%%b")

Open in new window

0
 
oBdACommented:
Oh, and then there's of course the tool I forget on a regular basis: forfiles.exe; again in test mode, same as above:
@echo off
forfiles.exe /p "C:\Windows\Temp" /m *.* /d -3 /c "cmd.exe /c ECHO del @path"

Open in new window

0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
Noah_Williams35Author Commented:
oBdA,

The forfiles command is great! I forgot about that myself! It asks me to confirm the delete. How do I supress that and just delete, so that it can be automated?

Thank you!
0
 
oBdACommented:
Oh, sorry. These would be subdirectories found inside the folder in question; do you want subfolders to be removed as well, or rather skip them and process only files?
0
 
Noah_Williams35Author Commented:
Yes, files and subdirectories are to be deleted...
0
 
becraigCommented:
I am guessing you do not need a powershell solution since the script above would do just that.
0
 
oBdACommented:
This now handles subdirectories; again in test mode (note that there are two ECHOs now):
@echo off
forfiles.exe /p "C:\Windows\Temp" /m * /d -3 /c "cmd /c if @isdir==TRUE (ECHO rd /s /q @path) else (ECHO del /f @path)"

Open in new window

0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

  • 4
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now