Created
December 28, 2018 07:56
-
-
Save PsCustomObject/d73c19c85296b6436d9de33ba25197cc to your computer and use it in GitHub Desktop.
PowerShell Remove Older Files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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