Automate Windows 11 Disk Cleanup with PowerShell
Automating routine disk cleaning and maintenance tasks in Windows 11 helps maintain peak system performance, reclaim valuable storage space, and extend the lifespan of your drives. This guide covers how to write a PowerShell maintenance script to clear temporary files, empty the Recycle Bin, run disk optimization (TRIM/Defrag), and automate the entire process using Windows Task Scheduler.
Step 1: Write the PowerShell Maintenance Script
Create a PowerShell script (.ps1) that executes the
primary disk cleanup and maintenance commands.
Open a text editor like Notepad or VS Code, paste the following
script, and save it as DiskMaintenance.ps1:
# Run with Administrator Privileges
Write-Output "Starting Disk Maintenance..."
# 1. Empty the Recycle Bin on all drives silently
try {
Clear-RecycleBin -Force -ErrorAction SilentlyContinue
Write-Output "Recycle Bin cleared successfully."
} catch {
Write-Output "Failed to clear Recycle Bin."
}
# 2. Delete User Temporary Files
$UserTemp = "$env:TEMP\*"
try {
Remove-Item -Path $UserTemp -Recurse -Force -ErrorAction SilentlyContinue
Write-Output "User temporary files removed."
} catch {
Write-Output "Some user temporary files could not be removed."
}
# 3. Delete System Temporary Files
$SystemTemp = "C:\Windows\Temp\*"
try {
Remove-Item -Path $SystemTemp -Recurse -Force -ErrorAction SilentlyContinue
Write-Output "System temporary files removed."
} catch {
Write-Output "Some system temporary files could not be removed."
}
# 4. Clean Windows Update Download Cache
$UpdateCache = "C:\Windows\SoftwareDistribution\Download\*"
try {
Remove-Item -Path $UpdateCache -Recurse -Force -ErrorAction SilentlyContinue
Write-Output "Windows update cache cleared."
} catch {
Write-Output "Windows update cache could not be cleared."
}
# 5. Optimize and Re-trim Drives (SSD TRIM and HDD Defrag)
try {
Write-Output "Optimizing Drive C:..."
Optimize-Volume -DriveLetter C -ReTrim -Verbose
Write-Output "Drive C: optimization completed."
} catch {
Write-Output "Volume optimization failed."
}
Write-Output "Disk maintenance process finished."Step 2: Test the Script Locally
Before automating the execution, test the script to ensure it runs without syntax errors.
Right-click the Windows Start menu and select Terminal (Admin) or PowerShell (Admin).
Set the execution policy to allow running local scripts if you haven’t already:
Set-ExecutionPolicy RemoteSigned -Scope CurrentUserRun your script by providing its full path:
& "C:\Scripts\DiskMaintenance.ps1"
Step 3: Automate Execution Using Task Scheduler
To execute this script automatically on a recurring schedule (e.g., weekly), configure a Windows Scheduled Task using PowerShell.
Run the following command in an elevated PowerShell session:
# Define the action to run PowerShell silently with the script
$Action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File `"C:\Scripts\DiskMaintenance.ps1`""
# Define the trigger (Runs every Sunday at 2:00 AM)
$Trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Sunday -At 2:00AM
# Define the task settings
$Settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries:$false -DontStopIfGoingOnBatteries -StartWhenAvailable
# Register the scheduled task with administrative privileges
Register-ScheduledTask -TaskName "Automated Disk Cleanup" -Action $Action -Trigger $Trigger -Settings $Settings -User "NT AUTHORITY\SYSTEM" -RunLevel HighestStep 4: Verify the Scheduled Task
To confirm the scheduled task is created and active:
- Press
Win + R, typetaskschd.msc, and press Enter. - Click Task Scheduler Library in the left sidebar.
- Locate Automated Disk Cleanup in the middle pane.
- Right-click the task and select Run to verify that it executes successfully in the background.