Friday, May 4, 2012

PowerShell script to delete files from a directory that are more than a given number of days old.

This PowerShell
  • deletes files created more than 3 days ago.
  • logs the files it deletes.
$d = "C:\db\backup"
$today = get-date -uformat "%Y_%m_%d"
$log = "C:\db\backup\" + "Purge_" + $today + ".log"
$a = Get-ChildItem $d -recurse
foreach($x in $a)
{
$y = ((Get-Date) - $x.CreationTime).Days
if ($y -gt 3 -and $x.PsISContainer -ne $True)
{
$deleted = "Deleting - " + $x.fullname + " - Last Write Time - " + $x.LastWriteTime
add-content $log -value $deleted
$x.Delete()
}
}
view raw gistfile1.txt hosted with ❤ by GitHub

No comments:

Post a Comment