Public/Remove-specOldFiles.ps1
Function Remove-specOldFiles { <# .SYNOPSIS Deletes files of a specified type older than a specified number of days in the given path(s). .DESCRIPTION The Remove-specOldFiles function identifies and deletes files of a specified type that are older than a specified number of days within the provided path(s). It is designed to handle various file types such as 'txt', 'log', 'log.*', 'tmp', 'temp', 'ps1'. .PARAMETER Path Specifies the path(s) where files will be searched. This parameter is mandatory and supports pipeline input. .PARAMETER FileType Specifies the type of files to search for. Valid values include 'txt', 'log', 'log.*', 'tmp', 'temp', 'ps1'. This parameter is mandatory. .PARAMETER DaysOldOrMore Specifies the number of days that determine whether a file is considered old. Files older than this specified number of days will be deleted. This parameter is mandatory. .EXAMPLE Remove-specOldFiles -Path "C:\Logs" -FileType "log" -DaysOldOrMore 7 Deletes log files in the "C:\Logs" directory that are older than 7 days. .EXAMPLE "C:\Archives", "D:\Backup" | Remove-specOldFiles -FileType "txt" -DaysOldOrMore 30 Deletes text files in the "C:\Archives" and "D:\Backup" directories that are older than 30 days. .NOTES Author : owen.heaume Version : 1.0 #> [cmdletbinding(SupportsShouldProcess)] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [string[]]$Path, [Parameter(Mandatory = $true)] [ValidateSet ('txt', 'log', 'log.*', 'tmp', 'temp', 'ps1')] [string]$FileType, [Parameter(Mandatory = $true)] [ValidateRange(0, 180)] [int]$DaysOldOrMore ) begin { write-host "Deleting files older than $DaysOldOrMore days:`n" -ForegroundColor DarkCyan } process { $Files = Get-specOldFiles -Path $Path -FileType $FileType -DaysOldOrMore $DaysOldOrMore Write-host "File Path: $Path" -ForegroundColor DarkGray write-host "Total number of files to delete: $($files.count)" -ForegroundColor DarkGray foreach ($File in $Files) { $formattedDate = $file.lastwritetime.ToString("dd-MMMM-yyyy") if ($PSCmdlet.shouldprocess("$($file.fullname)", "Delete")) { write-host "deleting $($file.fullname)" -ForegroundColor DarkYellow Remove-Item -Path $File.FullName -Force } } write-host } end {} } |