PoshCode Logo PowerShell Code Repository

PurgeFile script. by Bergle 20 months ago
embed code: <script type="text/javascript" src="http://PoshCode.org/embed/1897"></script>download | new post

Simple script to purge files recursively given path, extension, max age.
Works fine with unc paths.

  1. <#
  2. .SYNOPSIS
  3.         Purgefiles - recursively remove files with given extension and maximum age from a given path.
  4. .DESCRIPTION
  5.         Read the synopsis
  6.         Example
  7.                 PurgeFiles.psq -path C:\temp -ext .tmp -max 24
  8. .EXAMPLE
  9.         PurgeFiles.psq -path C:\temp -ext .tmp -max 24
  10.  
  11. #>
  12. # HISTORY
  13. # 2010/01/29
  14. # rluiten       Created
  15.  
  16. param(
  17.          [Parameter(Mandatory=$true)][string] $path
  18.         ,[Parameter(Mandatory=$true)][string] $extension
  19.         ,[Parameter(Mandatory=$true)][int] $maxHours
  20.         ,[switch] $deleteMode = $false
  21.         ,[switch] $listMode = $false
  22. )
  23.  
  24. function delete-file([string]$path, [string]$extension, [datetime]$oldestAllowed, [bool] $deleteMode, [bool] $listMode)
  25. {
  26.         $filesToRemove = Get-Childitem $path -recurse |
  27.                         ?{      !$_.PSIsContainer -and
  28.                                 $($_.LastWriteTime -lt $oldestAllowed) -and
  29.                                 ($_.Extension -eq $extension)
  30.                         }
  31.                        
  32.         if ($listMode -and $filesToRemove) {
  33.                 $filesToRemove | %{write-host "FILE: $($_.LastWriteTime) ""$($_.FullName)""`r`n"}
  34.         }
  35.        
  36.         if ($deleteMode -and $filesToRemove) {
  37.                 write-host "Removing Files...`r`n"
  38.                 $filesToRemove | remove-item -force
  39.         }
  40. }
  41.  
  42. $oldestAllowed = (get-date).AddHours(-$maxHours)
  43.  
  44. if (-not $deleteMode) {
  45.         write-host "Running in trial mode, no files will be deleted.`r`n"
  46. }
  47. delete-file $path $extension $oldestAllowed $deleteMode $listMode

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me