Skip to content

Instantly share code, notes, and snippets.

@PsCustomObject
Created December 28, 2018 07:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PsCustomObject/d73c19c85296b6436d9de33ba25197cc to your computer and use it in GitHub Desktop.
Save PsCustomObject/d73c19c85296b6436d9de33ba25197cc to your computer and use it in GitHub Desktop.
PowerShell Remove Older Files
# Define variables
[string]$filePath = 'C:\TestCleanup\'
[string]$fileExtension = '*.log'
[int]$fileAge = 90
[datetime]$ageTimeSpan = (Get-Date).AddDays(-$fileAge)
# Get all matching files
[array]$filesToPurge = Get-ChildItem -Path $filePath -Filter $fileExtension -File |
Where-Object { $_.LastWriteTime -lt $ageTimeSpan }
if ($filesToPurge.Count -gt 0)
{
foreach ($file in $filesToPurge)
{
# Get file full path
[string]$fileName = $file.FullName
# Remove file without confirmation
Remove-Item $fileName -Confirm:$false
}
}
else
{
# Replace with proper logging
Write-Host -Object 'No files to purge!'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment