Home > Powershell > PowerShell: delete files older than x days

PowerShell: delete files older than x days

Classical script and we all need it some day. Edit the folder path and adjust the number of days to your clean-up schedule. The script works recursive so it will also clean-up subfolders.

As always, make sure you can execute PowerShell scripts

Set-ExecutionPolicy RemoteSigned

The Script…

$Now = Get-Date
$Days = "30"
$TargetFolder = "C:WINDOWSsystem32LogFiles"
$LastWrite = $Now.AddDays(-$days)
$Files = get-childitem $TargetFolder -include *.log, *.txt -recurse | Where {$_.LastWriteTime -le "$LastWrite"} 

foreach ($File in $Files){
	write-host "Deleting File $File" -foregroundcolor "Red";  Remove-Item $File | out-null
}
Categories: Powershell Tags: , ,
  1. Glen DeGeare
    January 31st, 2012 at 23:32 | #1

    This works perfect for cleaning up .txt and log files on many servers for me older then 14 days in my case. Thank you.

  1. No trackbacks yet.