PoshCode Archive  Artifact [31045aff1e]

Artifact 31045aff1e15f863bc5e5efa20bf7bb368379a3ffc5592ba1b888f9bd0e8b64b:

  • File PurgeFiles-script.ps1 — part of check-in [0612d775bf] at 2018-06-10 12:59:17 on branch trunk — Recursively remove files with given extension and maximum age from a given path. (user: unknown size: 1595)

# encoding: ascii
# api: powershell
# title: PurgeFiles script.
# description: Recursively remove files with given extension and maximum age from a given path.
# version: 0.1
# type: script
# license: CC0
# function: delete-file
# x-poshcode-id: 1620
# x-archived: 2010-02-26T15:59:28
#
#
<#
.SYNOPSIS
	PurgeFiles - recursively remove files with given extension and maximum age from a given path.
.DESCRIPTION
	Read the synopsis
	Example
		PurgeFiles.psq -path C:\temp -ext .tmp -max 24
.EXAMPLE
	PurgeFiles.psq -path C:\temp -ext .tmp -max 24
#>
# HISTORY
# 2010/01/29
# rluiten	Created

param(
	 [Parameter(Mandatory=$true)][string] $path
	,[Parameter(Mandatory=$true)][string] $extension
	,[Parameter(Mandatory=$true)][int] $maxHours
	,[switch] $deleteMode = $false
	,[switch] $listMode = $false
)

function delete-file([string]$path, [string]$extension, [datetime]$oldestAllowed, [bool] $deleteMode, [bool] $listMode)
{
	$filesToRemove = Get-Childitem $path -recurse |
		?{	!$_.PSIsContainer -and
			($_.LastWriteTime -lt $oldestAllowed) -and
			($_.Extension -eq $extension)
		}
	if ($listMode -and $filesToRemove) {
		$filesToRemove | %{write-host "FILE: $($_.LastWriteTime) ""$($_.FullName)""`r`n"}
	}
	if ($deleteMode -and $filesToRemove) {
		write-host "Removing Files...`r`n"
		$filesToRemove | remove-item -force
	}
}

$oldestAllowed = (get-date).AddHours(-$maxHours)

if (-not $deleteMode) {
	write-host "Running in trial mode, no files will be deleted.`r`n"
}
delete-file $path $extension $oldestAllowed $deleteMode $listMode