PowerShell Script to Clean Up Old Files Based on Age

Here’s an extremely concise PowerShell script to remove old files.  You could use it to enforce a policy that keeps 90 days of ETL input files on a server.  Files older than that would purged with this script.  The script would be invoked by a SQLAgent CMDExec task or a Windows Task Scheduler job.


#Powershell Script to delete files older than a certain age

 

$intFileAge = 90  #age of files in days

$strFilePath = “c:\archive” #path to clean up

 

#create filter to exclude folders and files newer than specified age

Filter Select-FileAge 

      {

      param($days)

      If ($_.PSisContainer) {}

              # Exclude folders from result set

      ElseIf ($_.LastWriteTime -lt (Get-Date).AddDays($days * -1))

            {$_}

      }

 

      get-Childitem -recurse $strFilePath | Select-FileAge $intFileAge ‘CreationTime’ | remove-item 

3 Responses to “PowerShell Script to Clean Up Old Files Based on Age”

  1. JWest says:

    Nice and concise. Helped with a cleanup task I had.

  2. Joshua says:

    Great post… Could be used as a script using parameters real easy.

Leave a Reply