This PowerShell script performs a disk cleanup by deleting temporary files, clearing the Recycle Bin, and removing other unnecessary files. Run it as an administrator.
# Define paths for cleanup
$tempPaths = @("C:\Windows\Temp", "$env:TEMP", "$env:TMP")
$recycleBinPath = "C:\$Recycle.Bin" # Recycle Bin
Write-Output "Starting Disk Cleanup..."
# Clean temp directories
foreach ($path in $tempPaths) {
if (Test-Path -Path $path) {
try {
Get-ChildItem -Path $path -Recurse | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
Write-Output "Cleared temp files in $path"
} catch {
Write-Output "Failed to clear temp files in $path: $($_.Exception.Message)"
}
} else {
Write-Output "Path $path does not exist"
}
}
# Empty Recycle Bin
try {
Clear-RecycleBin -Force -ErrorAction SilentlyContinue
Write-Output "Recycle Bin emptied successfully."
} catch {
Write-Output "Failed to empty Recycle Bin: $($_.Exception.Message)"
}
# Clean Windows Update Cache
$updateCachePath = "C:\Windows\SoftwareDistribution\Download"
if (Test-Path -Path $updateCachePath) {
try {
Get-ChildItem -Path $updateCachePath -Recurse | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
Write-Output "Cleared Windows Update cache."
} catch {
Write-Output "Failed to clear Windows Update cache: $($_.Exception.Message)"
}
} else {
Write-Output "Windows Update cache path not found."
}
# Remove old log files (e.g., logs older than 30 days)
$logPaths = @("C:\Windows\Logs", "C:\Logs")
$logRetentionDays = 30
foreach ($logPath in $logPaths) {
if (Test-Path -Path $logPath) {
try {
Get-ChildItem -Path $logPath -Recurse -File | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$logRetentionDays) } | Remove-Item -Force -ErrorAction SilentlyContinue
Write-Output "Old log files cleaned in $logPath."
} catch {
Write-Output "Failed to clean old logs in $logPath: $($_.Exception.Message)"
}
} else {
Write-Output "Log path $logPath not found."
}
}
Write-Output "Disk cleanup completed successfully."
Explanation of the Script Steps
1. Temporary Files: Clears temporary files from common temp directories like C:\Windows\Temp and user-specific temp folders.
2. Recycle Bin: Empties the Recycle Bin using the Clear-RecycleBin cmdlet, removing deleted files and freeing up space.
3. Windows Update Cache: Deletes the cache of Windows Update files in the SoftwareDistribution\Download folder, which often contains unnecessary update files.
4. Old Log Files: Removes log files older than 30 days from specified log directories, reducing space usage by old, often redundant logs.