Powershell – Deleting files X days old

Here’s a powershell script you can use to delete files in a directory (and all sub-directories) X days old or older.

 

$Now= Get-Date

$Days = 3

$TargetFolder = u:\backup

$LastWrite = $Now.AddDays($days)

$Files = get-childitem $TargetFolder -include *.txt, *.log, *.bak -recurse | Where {$_.LastWriteTime -le “$LastWrite”}

foreach ($File in $Files)

{

  write-host “Deleting File $File” -foregroundcolor Red

  Remove-Item -path $File.FullName -force

}

 

You should change the Days and TargetFolder variables (highlighted), specify the file types you want after –include and remove the –recurse option if you don’t want to include subdirectories in the TargetFolder.