Here is an adaptation of a Windows Powershell script we use to delete old SimplyReports files. We schedule this to run via Task Scheduler.
TEST - TEST - TEST before running in production!!!
# This script DELETES FILES and COULD delete your entire system BREAKING EVERYTHING!!!!!!!!!!!!!!!!!!
# Set some parameters for your system
$days = 30 # The script will delete anything MODIFIED more than this many days ago
$logpath = "C:\inetpub\logs\LogFiles\DeleteOld"
$paths = @("c:\ProgramData\Polaris\SRServiceRoot\PRODSR", "c:\ProgramData\Polaris\SRServiceRoot\DEVSR") # These file paths are recursively examined
$fileTypes = @("log", "txt", "bak") # Add "all" to delete all file types
# Create log file with timestamp
$now = Get-Date -format yyyy-MM-dd_HH-mm-ss
$logfile = "$logpath\$now.log"
New-Item -Path $logfile -ItemType file -Force | Out-Null
# Calculate the cutoff date
$start = (Get-Date).AddDays(-$days)
# Process each path
foreach ($path in $paths) {
Write-Output "Processing path: $path" | Out-File $logfile -Append
# Check if "all" is specified in the file types
if ($fileTypes -contains "all") {
Write-Output "Checking for all file types" | Out-File $logfile -Append
# Get all files older than the specified number of days
$files = Get-ChildItem "$path\*" -File -Recurse | Where-Object { $_.LastWriteTime -lt $start }
$filesCount = $files.Count
Write-Output "Found $filesCount files older than $days days in $path" | Out-File $logfile -Append
$count = 0
$files | ForEach-Object {
Remove-Item $_ -Force
$count++
}
Write-Output "Removed $count files successfully from $path" | Out-File $logfile -Append
} else {
# Process each file type
foreach ($fileType in $fileTypes) {
Write-Output "Checking for *.$fileType files" | Out-File $logfile -Append
# Get files older than the specified number of days
$files = Get-ChildItem "$path\*.$fileType" -File -Recurse | Where-Object { $_.LastWriteTime -lt $start }
$filesCount = $files.Count
Write-Output "Found $filesCount $fileType files older than $days days in $path" | Out-File $logfile -Append
# Remove the files and count the removed files
$count = 0
$files | ForEach-Object {
Remove-Item $_ -Force
$count++
}
Write-Output "Removed $count $fileType files successfully from $path" | Out-File $logfile -Append
}
}
}
Write-Output "Log file created at: $logfile"