PowerShell Script to Clean Up Old Files and Alert on High Disk Usage
powershellRecursively deletes files older than a specified number of days, logs all actions, and checks disk usage against a threshold. Built for Windows and Windows Server homelab environments. Read more here.
powershellwindowshomelabautomationdisk managementcleanupmonitoring
Script Code
PowerShellpowershell
param(
[string]$TargetPath = "C:\Logs",
[int]$DaysOld = 14,
[string]$LogFile = "C:\Logs\homelab_cleanup.log",
[string]$DriveLetter = "C",
[int]$DiskThreshold = 85,
[switch]$WhatIf
)
function Write-Log {
param([string]$Message)
$ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
"$ts $Message" | Out-File -FilePath $LogFile -Append -Encoding utf8
}
Write-Log "=== Cleanup start ==="
Write-Log "TargetPath=$TargetPath DaysOld=$DaysOld Drive=$DriveLetter Threshold=${DiskThreshold}% WhatIf=$($WhatIf.IsPresent)"
if (-not (Test-Path $TargetPath)) {
throw "TargetPath does not exist: $TargetPath"
}
$cutoff = (Get-Date).AddDays(-$DaysOld)
$files = Get-ChildItem -Path $TargetPath -File -Recurse -ErrorAction SilentlyContinue |
Where-Object { $_.LastWriteTime -lt $cutoff }
Write-Log "Found $($files.Count) files older than $DaysOld days."
if ($files.Count -gt 0) {
if ($WhatIf) {
Write-Log "WHATIF: Listing files that would be deleted:"
$files.FullName | ForEach-Object { Write-Log $_ }
} else {
foreach ($f in $files) {
try {
Remove-Item -LiteralPath $f.FullName -Force -ErrorAction Stop
Write-Log "Deleted: $($f.FullName)"
} catch {
Write-Log "ERROR deleting $($f.FullName): $($_.Exception.Message)"
}
}
}
}
$drive = Get-CimInstance Win32_LogicalDisk -Filter "DeviceID='$DriveLetter`:'"
$usedPct = [math]::Round((($drive.Size - $drive.FreeSpace) / $drive.Size) * 100, 0)
Write-Log "Disk usage on ${DriveLetter}: is ${usedPct}%."
if ($usedPct -ge $DiskThreshold) {
Write-Log "ALERT: Disk usage high (${usedPct}% >= ${DiskThreshold}%)."
Write-Output "ALERT: Disk usage high on ${DriveLetter}: (${usedPct}%)."
}
Write-Log "=== Cleanup end ==="Get new scripts weekly.
Subscribe to receive fresh PowerShell scripts, automation tips, and IT workflow improvements.
Subscribe to Newsletter