Ying Li at myITforum.com

PowerShell & System Center

PowerShell script to delete files older than certain days

Here is a PowerShell script to delete files(logs) older than however many days you defined.

BECAREFUL, THIS CAN REALLY DO DAMAGE! USE AT YOUR OWN RISK!


Function GetOldFile
{
 param ($strComputer = $(Read-Host "Please Enter The Server Name")),
       ($Dir = $(Read-host "Please Enter The Directory Path"))
       ($Days = $(Read-Host "How Many Days?"))

 $TargetFolder = "\\" + $strComputer + "\" + $Dir
 
 
 if (Test-Path $TargetFolder)
 {

 #Warn you the targeted folder, so you can double check
  Write-host "The Targeted Folder is:" $TargetFolder -foregroundcolor "Red"
  Write-Host `a `a `a `a `a
  Write-Host "If This Is Not The Intended Target, Press 'Ctrl + C' To Exit" -foregroundcolor "Yellow"
  Start-sleep -s 15

  $Now = Get-Date

 # Notice the minus sign before $days
  $LastWrite = $Now.AddDays(-$days)
  $Files = get-childitem $TargetFolder -include *.log -recurse |Where {$_.LastWriteTime -le "$LastWrite"} 
  foreach ($File in $Files)

 #You can add -whatif to see the consequence – Remove-item $File -Whatif
  {write-host "Deleting File $File" -foregroundcolor "Red"; Remove-Item $File | out-null}
 }
 Else
 {Write-Host "The Folder $TargetFolder Does Not Exist!"}
}
GetOldFile

Posted: Oct 02 2007, 09:20 PM by yli628 | with 2 comment(s)
Filed under:

Comments

GadgetGadget.info - Gadgets on the web » PowerShell script to delete files older than certain days said:

Pingback from  GadgetGadget.info - Gadgets on the web » PowerShell script to delete files older than certain days

# October 2, 2007 10:03 PM

older hp servers said:

Pingback from  older hp servers

# May 26, 2008 6:11 PM