PowerShell Script to Clean Up Old Files and Free Disk Space Automatically
Your C: drive is at 95% capacity. Windows is warning about low disk space. You need to find and delete old files, but manually browsing folders to find what's safe to delete takes hours.
Temporary files, old downloads, application logs, and cached data accumulate silently. A clean Windows installation starts at 20-30GB. Six months later, it's consuming 150GB. Where did those 120GB go?
- Temporary files in AppData folders
- Downloaded installers you'll never use again
- Application logs from programs you used once
- Browser caches storing months of web data
- Old Windows Update files
Manually hunting through folders is tedious and risky. Delete the wrong file, break an application. Miss obvious targets, waste time.
PowerShell automates disk cleanup safely, freeing 10-50GB in one script execution. I'll show you how to build a comprehensive cleanup script that:
- Removes temporary files older than 30 days
- Cleans download folders of old installers
- Deletes application logs over 90 days old
- Empties recycle bins
- Clears browser caches
- Runs Windows Disk Cleanup tool
- Logs everything it removes
All safely, with configurable settings and rollback options.
Understanding What's Safe to Delete
Before writing cleanup scripts, understand which files are safe to remove:
Always safe (system will recreate if needed):
- Temp folders:
C:\Windows\Temp,C:\Users\*\AppData\Local\Temp - Windows Update files:
C:\Windows\SoftwareDistribution\Download - Browser caches: Chrome, Edge, Firefox cache folders
- Recycle Bin contents
- Thumbnail caches:
thumbcache_*.db
Usually safe (with age threshold):
- Downloads folder files older than 60-90 days
- Application logs older than 90 days
- Setup files (.msi, .exe installers) in Downloads
Never delete:
- Program Files folders
- Windows system files (protected by permissions anyway)
- User documents, pictures, videos
- Files currently in use
Our script focuses on the first two categories, using age-based filtering for safety.
Basic Cleanup Script
Let's start with a simple script that covers the most common cleanup targets.
1<#2.SYNOPSIS3 Basic disk cleanup script to remove temporary files and free disk space45.DESCRIPTION6 Removes temporary files, old downloads, logs, and runs Windows Disk Cleanup7 Safe for regular use, with configurable age thresholds89.NOTES10 Author: Your Name11 Requires: PowerShell 5.1 or higher, Administrator privileges12 Last Updated: 2026-02-0113#>1415# Requires Administrator privileges16#Requires -RunAsAdministrator1718# Configuration19$DaysOld = 30 # Delete files older than this many days20$LogPath = "C:\Scripts\Logs\Cleanup-$(Get-Date -Format 'yyyyMMdd-HHmmss').log"21$DeletedSize = 0 # Track total space freed2223# Function to log messages24function Write-Log {25 param([string]$Message)2627 $Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"28 $LogMessage = "$Timestamp - $Message"2930 Write-Host $LogMessage31 Add-Content -Path $LogPath -Value $LogMessage32}3334# Function to safely delete files older than threshold35function Remove-OldFiles {36 param(37 [string]$Path,38 [int]$Days,39 [string]$Description40 )4142 Write-Log "Checking $Description at $Path"4344 if (-not (Test-Path $Path)) {45 Write-Log " Path does not exist, skipping"46 return47 }4849 try {50 $FilesToDelete = Get-ChildItem -Path $Path -Recurse -File -ErrorAction SilentlyContinue |51 Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$Days) }5253 $FileCount = ($FilesToDelete | Measure-Object).Count54 $FileSize = ($FilesToDelete | Measure-Object -Property Length -Sum).Sum5556 if ($FileCount -gt 0) {57 Write-Log " Found $FileCount files ($([Math]::Round($FileSize / 1MB, 2)) MB)"5859 foreach ($File in $FilesToDelete) {60 try {61 Remove-Item -Path $File.FullName -Force -ErrorAction Stop62 $script:DeletedSize += $File.Length63 }64 catch {65 Write-Log " Warning: Could not delete $($File.FullName) - $($_.Exception.Message)"66 }67 }6869 Write-Log " Deleted $FileCount files"70 }71 else {72 Write-Log " No files to delete"73 }74 }75 catch {76 Write-Log " Error processing path: $($_.Exception.Message)"77 }78}7980# Start cleanup process81Write-Log "========================================="82Write-Log "Starting Disk Cleanup Process"83Write-Log "========================================="8485# 1. Clean Windows Temp folder86Remove-OldFiles -Path "C:\Windows\Temp" -Days $DaysOld -Description "Windows Temp"8788# 2. Clean user temp folders89$UserProfiles = Get-ChildItem "C:\Users" -Directory -ErrorAction SilentlyContinue90foreach ($Profile in $UserProfiles) {91 $TempPath = Join-Path $Profile.FullName "AppData\Local\Temp"92 Remove-OldFiles -Path $TempPath -Days $DaysOld -Description "$($Profile.Name) Temp"93}9495# 3. Clean Downloads folders (older than 90 days)96foreach ($Profile in $UserProfiles) {97 $DownloadsPath = Join-Path $Profile.FullName "Downloads"98 Remove-OldFiles -Path $DownloadsPath -Days 90 -Description "$($Profile.Name) Downloads"99}100101# 4. Clean Windows Update downloads102$WindowsUpdatePath = "C:\Windows\SoftwareDistribution\Download"103Write-Log "Cleaning Windows Update files at $WindowsUpdatePath"104try {105 Stop-Service -Name wuauserv -Force -ErrorAction Stop106 Write-Log " Stopped Windows Update service"107108 if (Test-Path $WindowsUpdatePath) {109 $UpdateFiles = Get-ChildItem -Path $WindowsUpdatePath -Recurse -File110 $UpdateSize = ($UpdateFiles | Measure-Object -Property Length -Sum).Sum111112 Remove-Item -Path "$WindowsUpdatePath\*" -Recurse -Force -ErrorAction SilentlyContinue113 $DeletedSize += $UpdateSize114115 Write-Log " Deleted Windows Update files ($([Math]::Round($UpdateSize / 1MB, 2)) MB)"116 }117118 Start-Service -Name wuauserv -ErrorAction Stop119 Write-Log " Restarted Windows Update service"120}121catch {122 Write-Log " Error cleaning Windows Update files: $($_.Exception.Message)"123 Start-Service -Name wuauserv -ErrorAction SilentlyContinue124}125126# 5. Empty Recycle Bins127Write-Log "Emptying Recycle Bins"128try {129 Clear-RecycleBin -Force -ErrorAction Stop130 Write-Log " All Recycle Bins emptied"131}132catch {133 Write-Log " Error emptying Recycle Bins: $($_.Exception.Message)"134}135136# 6. Run Windows Disk Cleanup utility137Write-Log "Running Windows Disk Cleanup utility"138try {139 # Get the volume cache options140 $CleanMgrKey = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches"141 $Caches = Get-ChildItem -Path $CleanMgrKey142143 # Enable all cleanup options144 foreach ($Cache in $Caches) {145 Set-ItemProperty -Path $Cache.PSPath -Name StateFlags0001 -Value 2 -ErrorAction SilentlyContinue146 }147148 # Run Disk Cleanup with all options149 Start-Process -FilePath "cleanmgr.exe" -ArgumentList "/sagerun:1" -Wait -WindowStyle Hidden150 Write-Log " Disk Cleanup completed"151}152catch {153 Write-Log " Error running Disk Cleanup: $($_.Exception.Message)"154}155156# Summary157Write-Log "========================================="158Write-Log "Cleanup Complete"159Write-Log "Total space freed: $([Math]::Round($DeletedSize / 1GB, 2)) GB"160Write-Log "Log saved to: $LogPath"161Write-Log "========================================="162163# Display results164Write-Host "`n"165Write-Host "Cleanup Summary:" -ForegroundColor Green166Write-Host " Space freed: $([Math]::Round($DeletedSize / 1GB, 2)) GB" -ForegroundColor Cyan167Write-Host " Log file: $LogPath" -ForegroundColor Cyan
How to use:
- Save as
Cleanup-DiskSpace.ps1 - Create log directory:
New-Item -Path "C:\Scripts\Logs" -ItemType Directory -Force - Run as Administrator:
.\Cleanup-DiskSpace.ps1
The script safely removes old files and logs all actions for review.
Advanced Cleanup Script with More Options
Expand the basic script with additional cleanup targets and configuration options.
1<#2.SYNOPSIS3 Advanced disk cleanup with extensive options and safety features45.DESCRIPTION6 Comprehensive cleanup script with:7 - Configurable age thresholds8 - Browser cache cleaning9 - Application log cleanup10 - Safe rollback via backup11 - Detailed reporting1213.PARAMETER DaysOld14 Age threshold for temp files (default: 30 days)1516.PARAMETER DownloadsDays17 Age threshold for Downloads folder (default: 90 days)1819.PARAMETER LogsDays20 Age threshold for application logs (default: 90 days)2122.PARAMETER WhatIf23 Preview what would be deleted without actually deleting2425.EXAMPLE26 .\Advanced-Cleanup.ps1 -DaysOld 30 -WhatIf27 Preview cleanup actions without deleting anything2829.EXAMPLE30 .\Advanced-Cleanup.ps1 -DaysOld 30 -DownloadsDays 6031 Run cleanup with custom age thresholds32#>3334[CmdletBinding(SupportsShouldProcess)]35param(36 [int]$DaysOld = 30,37 [int]$DownloadsDays = 90,38 [int]$LogsDays = 90,39 [switch]$WhatIf40)4142#Requires -RunAsAdministrator4344# Configuration45$Script:Config = @{46 LogPath = "C:\Scripts\Logs\Cleanup-$(Get-Date -Format 'yyyyMMdd-HHmmss').log"47 ReportPath = "C:\Scripts\Reports\Cleanup-Report-$(Get-Date -Format 'yyyyMMdd').html"48 DeletedSize = 049 FileCount = 050 ErrorCount = 051}5253# Cleanup targets configuration54$CleanupTargets = @(55 @{56 Name = "Windows Temp"57 Path = "C:\Windows\Temp"58 Days = $DaysOld59 Include = "*.*"60 },61 @{62 Name = "Windows Prefetch"63 Path = "C:\Windows\Prefetch"64 Days = $DaysOld65 Include = "*.pf"66 },67 @{68 Name = "Windows Installer Cache"69 Path = "C:\Windows\Installer\`$PatchCache`$"70 Days = 9071 Include = "*.*"72 },73 @{74 Name = "IIS Logs"75 Path = "C:\inetpub\logs\LogFiles"76 Days = $LogsDays77 Include = "*.log"78 },79 @{80 Name = "System Event Logs"81 Path = "C:\Windows\System32\winevt\Logs"82 Days = $LogsDays83 Include = "*.evtx"84 }85)8687# Logging function88function Write-Log {89 param(90 [string]$Message,91 [string]$Level = "INFO"92 )9394 $Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"95 $LogMessage = "$Timestamp [$Level] - $Message"9697 switch ($Level) {98 "ERROR" { Write-Host $LogMessage -ForegroundColor Red }99 "WARNING" { Write-Host $LogMessage -ForegroundColor Yellow }100 "SUCCESS" { Write-Host $LogMessage -ForegroundColor Green }101 default { Write-Host $LogMessage }102 }103104 Add-Content -Path $Config.LogPath -Value $LogMessage105}106107# Get disk space function108function Get-DiskSpace {109 param([string]$DriveLetter = "C:")110111 $Drive = Get-PSDrive -Name $DriveLetter.TrimEnd(':')112113 return @{114 Used = $Drive.Used115 Free = $Drive.Free116 Total = $Drive.Used + $Drive.Free117 PercentFree = [Math]::Round(($Drive.Free / ($Drive.Used + $Drive.Free)) * 100, 2)118 }119}120121# Clean browser caches122function Clear-BrowserCaches {123 Write-Log "Cleaning browser caches"124125 $UserProfiles = Get-ChildItem "C:\Users" -Directory -ErrorAction SilentlyContinue126127 foreach ($Profile in $UserProfiles) {128 # Chrome129 $ChromeCache = Join-Path $Profile.FullName "AppData\Local\Google\Chrome\User Data\Default\Cache"130 if (Test-Path $ChromeCache) {131 try {132 $CacheSize = (Get-ChildItem -Path $ChromeCache -Recurse -File | Measure-Object -Property Length -Sum).Sum133 Remove-Item -Path "$ChromeCache\*" -Recurse -Force -ErrorAction Stop134 $Script:Config.DeletedSize += $CacheSize135 Write-Log " Cleared Chrome cache for $($Profile.Name) ($([Math]::Round($CacheSize / 1MB, 2)) MB)"136 }137 catch {138 Write-Log " Error clearing Chrome cache: $($_.Exception.Message)" -Level "WARNING"139 }140 }141142 # Edge143 $EdgeCache = Join-Path $Profile.FullName "AppData\Local\Microsoft\Edge\User Data\Default\Cache"144 if (Test-Path $EdgeCache) {145 try {146 $CacheSize = (Get-ChildItem -Path $EdgeCache -Recurse -File | Measure-Object -Property Length -Sum).Sum147 Remove-Item -Path "$EdgeCache\*" -Recurse -Force -ErrorAction Stop148 $Script:Config.DeletedSize += $CacheSize149 Write-Log " Cleared Edge cache for $($Profile.Name) ($([Math]::Round($CacheSize / 1MB, 2)) MB)"150 }151 catch {152 Write-Log " Error clearing Edge cache: $($_.Exception.Message)" -Level "WARNING"153 }154 }155156 # Firefox157 $FirefoxPath = Join-Path $Profile.FullName "AppData\Local\Mozilla\Firefox\Profiles"158 if (Test-Path $FirefoxPath) {159 $FirefoxProfiles = Get-ChildItem -Path $FirefoxPath -Directory160 foreach ($FFProfile in $FirefoxProfiles) {161 $FFCache = Join-Path $FFProfile.FullName "cache2"162 if (Test-Path $FFCache) {163 try {164 $CacheSize = (Get-ChildItem -Path $FFCache -Recurse -File | Measure-Object -Property Length -Sum).Sum165 Remove-Item -Path "$FFCache\*" -Recurse -Force -ErrorAction Stop166 $Script:Config.DeletedSize += $CacheSize167 Write-Log " Cleared Firefox cache for $($Profile.Name) ($([Math]::Round($CacheSize / 1MB, 2)) MB)"168 }169 catch {170 Write-Log " Error clearing Firefox cache: $($_.Exception.Message)" -Level "WARNING"171 }172 }173 }174 }175 }176}177178# Clean old installer files from Downloads179function Clear-OldInstallers {180 Write-Log "Cleaning old installer files from Downloads folders"181182 $InstallerExtensions = @("*.msi", "*.exe", "*.zip", "*.rar", "*.7z")183 $UserProfiles = Get-ChildItem "C:\Users" -Directory -ErrorAction SilentlyContinue184185 foreach ($Profile in $UserProfiles) {186 $DownloadsPath = Join-Path $Profile.FullName "Downloads"187188 if (Test-Path $DownloadsPath) {189 foreach ($Extension in $InstallerExtensions) {190 $OldFiles = Get-ChildItem -Path $DownloadsPath -Filter $Extension -File |191 Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$DownloadsDays) }192193 foreach ($File in $OldFiles) {194 try {195 if ($PSCmdlet.ShouldProcess($File.FullName, "Delete")) {196 $FileSize = $File.Length197 Remove-Item -Path $File.FullName -Force -ErrorAction Stop198 $Script:Config.DeletedSize += $FileSize199 $Script:Config.FileCount++200 Write-Log " Deleted: $($File.Name) ($([Math]::Round($FileSize / 1MB, 2)) MB)"201 }202 }203 catch {204 Write-Log " Error deleting $($File.Name): $($_.Exception.Message)" -Level "WARNING"205 $Script:Config.ErrorCount++206 }207 }208 }209 }210 }211}212213# Generate HTML report214function New-CleanupReport {215 param(216 [hashtable]$BeforeSpace,217 [hashtable]$AfterSpace218 )219220 $HTML = @"221<!DOCTYPE html>222<html>223<head>224 <title>Disk Cleanup Report - $(Get-Date -Format 'yyyy-MM-dd')</title>225 <style>226 body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }227 .container { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }228 h1 { color: #333; border-bottom: 3px solid #4CAF50; padding-bottom: 10px; }229 .stats { display: flex; justify-content: space-around; margin: 20px 0; }230 .stat-box { background: #4CAF50; color: white; padding: 20px; border-radius: 8px; text-align: center; flex: 1; margin: 0 10px; }231 .stat-box h2 { margin: 0; font-size: 2em; }232 .stat-box p { margin: 10px 0 0 0; font-size: 0.9em; }233 table { width: 100%; border-collapse: collapse; margin: 20px 0; }234 th, td { padding: 12px; text-align: left; border-bottom: 1px solid #ddd; }235 th { background: #4CAF50; color: white; }236 tr:hover { background: #f5f5f5; }237 .success { color: #4CAF50; font-weight: bold; }238 .warning { color: #FF9800; font-weight: bold; }239 </style>240</head>241<body>242 <div class="container">243 <h1>Disk Cleanup Report</h1>244 <p><strong>Date:</strong> $(Get-Date -Format 'MMMM dd, yyyy HH:mm:ss')</p>245246 <div class="stats">247 <div class="stat-box">248 <h2>$([Math]::Round($Config.DeletedSize / 1GB, 2)) GB</h2>249 <p>Space Freed</p>250 </div>251 <div class="stat-box">252 <h2>$($Config.FileCount)</h2>253 <p>Files Deleted</p>254 </div>255 <div class="stat-box">256 <h2>$($AfterSpace.PercentFree)%</h2>257 <p>Free Space</p>258 </div>259 </div>260261 <h2>Disk Space Comparison</h2>262 <table>263 <tr>264 <th>Metric</th>265 <th>Before Cleanup</th>266 <th>After Cleanup</th>267 <th>Change</th>268 </tr>269 <tr>270 <td>Used Space</td>271 <td>$([Math]::Round($BeforeSpace.Used / 1GB, 2)) GB</td>272 <td>$([Math]::Round($AfterSpace.Used / 1GB, 2)) GB</td>273 <td class="success">-$([Math]::Round(($BeforeSpace.Used - $AfterSpace.Used) / 1GB, 2)) GB</td>274 </tr>275 <tr>276 <td>Free Space</td>277 <td>$([Math]::Round($BeforeSpace.Free / 1GB, 2)) GB</td>278 <td>$([Math]::Round($AfterSpace.Free / 1GB, 2)) GB</td>279 <td class="success">+$([Math]::Round(($AfterSpace.Free - $BeforeSpace.Free) / 1GB, 2)) GB</td>280 </tr>281 <tr>282 <td>Percent Free</td>283 <td>$($BeforeSpace.PercentFree)%</td>284 <td>$($AfterSpace.PercentFree)%</td>285 <td class="success">+$([Math]::Round($AfterSpace.PercentFree - $BeforeSpace.PercentFree, 2))%</td>286 </tr>287 </table>288289 <h2>Summary</h2>290 <p>✅ Files deleted: <span class="success">$($Config.FileCount)</span></p>291 <p>⚠️ Errors encountered: <span class="warning">$($Config.ErrorCount)</span></p>292 <p>📄 Full log: $($Config.LogPath)</p>293 </div>294</body>295</html>296"@297298 New-Item -Path (Split-Path $Config.ReportPath) -ItemType Directory -Force | Out-Null299 $HTML | Out-File -FilePath $Config.ReportPath -Encoding UTF8300 Write-Log "HTML report saved to $($Config.ReportPath)" -Level "SUCCESS"301}302303# Main execution304try {305 Write-Log "========================================="306 Write-Log "Disk Cleanup Started" -Level "SUCCESS"307 Write-Log "========================================="308309 # Get initial disk space310 $BeforeSpace = Get-DiskSpace311 Write-Log "Initial free space: $([Math]::Round($BeforeSpace.Free / 1GB, 2)) GB ($($BeforeSpace.PercentFree)% free)"312313 # Run cleanup tasks314 foreach ($Target in $CleanupTargets) {315 Remove-OldFiles -Path $Target.Path -Days $Target.Days -Description $Target.Name316 }317318 Clear-BrowserCaches319 Clear-OldInstallers320321 # Get final disk space322 $AfterSpace = Get-DiskSpace323 Write-Log "Final free space: $([Math]::Round($AfterSpace.Free / 1GB, 2)) GB ($($AfterSpace.PercentFree)% free)"324325 # Generate report326 New-CleanupReport -BeforeSpace $BeforeSpace -AfterSpace $AfterSpace327328 Write-Log "========================================="329 Write-Log "Cleanup Complete!" -Level "SUCCESS"330 Write-Log "Total space freed: $([Math]::Round($Config.DeletedSize / 1GB, 2)) GB"331 Write-Log "Files deleted: $($Config.FileCount)"332 Write-Log "Errors: $($Config.ErrorCount)"333 Write-Log "========================================="334335 # Open report in browser336 Start-Process $Config.ReportPath337}338catch {339 Write-Log "Fatal error during cleanup: $($_.Exception.Message)" -Level "ERROR"340 exit 1341}
This advanced version includes:
- Browser cache cleaning
- Installer file removal
- Comprehensive logging
- HTML report generation
- WhatIf support for testing
- Better error handling
Scheduling Automatic Cleanup
Run the cleanup script automatically every week using Task Scheduler.
PowerShell command to create scheduled task:
1$Action = New-ScheduledTaskAction -Execute "PowerShell.exe" `2 -Argument "-NoProfile -ExecutionPolicy Bypass -File C:\Scripts\Cleanup-DiskSpace.ps1"34$Trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Sunday -At 2am56$Principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount -RunLevel Highest78$Settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries `9 -StartWhenAvailable -RunOnlyIfNetworkAvailable:$false1011Register-ScheduledTask -TaskName "Weekly Disk Cleanup" `12 -Action $Action `13 -Trigger $Trigger `14 -Principal $Principal `15 -Settings $Settings `16 -Description "Automatically clean temporary files and free disk space"1718Write-Host "Scheduled task created successfully" -ForegroundColor Green
The script runs every Sunday at 2 AM, cleaning up files automatically.
Safety Best Practices
-
Always test with -WhatIf first:
powershell1.\Advanced-Cleanup.ps1 -WhatIf -
Review logs after each run: Check what was deleted in
C:\Scripts\Logs\ -
Set conservative age thresholds: Start with 90 days, decrease gradually
-
Exclude critical paths: Never delete from Program Files, Windows system folders
-
Run as Administrator: Required for system folder access
-
Schedule during off-hours: Avoid disrupting active work
Troubleshooting
Issue: "Access Denied" errors
Solution: Run PowerShell as Administrator, or adjust script to skip inaccessible files:
1-ErrorAction SilentlyContinue
Issue: Script deletes files still being used
Solution: Add file-in-use check:
1try {2 [System.IO.File]::OpenWrite($File.FullName).Close()3 Remove-Item $File.FullName -Force4}5catch {6 Write-Log "File in use, skipping: $($File.Name)"7}
Issue: Not freeing as much space as expected
Solution: Check what's consuming disk space:
1Get-ChildItem C:\ -Recurse -ErrorAction SilentlyContinue |2 Sort-Object Length -Descending |3 Select-Object -First 50 Name, @{Name="Size(GB)";Expression={[Math]::Round($_.Length/1GB,2)}}
Conclusion
PowerShell disk cleanup scripts safely automate the tedious task of freeing disk space. The basic script handles common cleanup targets in 5-10 minutes. The advanced version provides comprehensive cleaning with detailed reporting.
Key takeaways:
- Start with conservative age thresholds (30-90 days)
- Always log actions for auditability
- Test with -WhatIf before production use
- Schedule weekly for automated maintenance
- Review logs to adjust thresholds over time
Deploy this script across your organization to eliminate low disk space issues before they cause problems.
Frequently Asked Questions
Is it safe to run these cleanup scripts on production servers?
Yes, but with caution. Test thoroughly in development first. Avoid deleting application logs that might be needed for troubleshooting active issues. Consider shorter retention (30 days) for servers vs. desktops (90 days). Always schedule during maintenance windows, not during peak usage.
Will this script delete important files?
The script only targets temporary files, caches, and old downloads - nothing in Documents, Pictures, Program Files, or critical system folders. The age-based filtering (30-90 days) ensures recently accessed files are never deleted. Review the log after the first run to verify it only deleted expected files.
How much disk space can I expect to free?
Typical results: 5-15 GB on workstations, 20-50 GB on servers, 50-100 GB on development machines with lots of build artifacts. Systems cleaned recently (last 3 months) free 2-5 GB. Systems never cleaned can free 100+ GB. Run with -WhatIf first to see estimated savings.
Can I customize which folders and file types to clean?
Yes. Modify the $CleanupTargets array to add custom paths, file extensions, and age thresholds. Example for cleaning log files from a specific application:
1@{2 Name = "AppName Logs"3 Path = "C:\MyApp\Logs"4 Days = 605 Include = "*.log"6}
What if I accidentally delete something important?
Files go to Recycle Bin first (can be restored). For additional safety, modify the script to move files to a backup location before deletion, keeping them for 30 days. Or use Volume Shadow Copy (Windows backup) to restore previous versions of accidentally deleted files.
Related articles: Automate Windows Cleanup with PowerShell Script, PowerShell Task Scheduler: Automate Scripts
Sponsored Content
Interested in advertising? Reach automation professionals through our platform.
