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 }
This works perfect for cleaning up .txt and log files on many servers for me older then 14 days in my case. Thank you.