Cleanup Windows User Temporary Files

This script will cleanup all users temporary files in their AppData\Local\Temp for Windows 7 and newer.

# Define the base directory for user profiles
$usersPath = "C:\Users"
$totalBeforeCleanup = 0
$totalAfterCleanup = 0

# Loop through each user folder in the Users directory
Get-ChildItem -Path $usersPath -Directory | ForEach-Object {
$userTempPath = Join-Path -Path $_.FullName -ChildPath "AppData\Local\Temp"
$userBeforeSize = 0
$userAfterSize = 0

# Check if the Temp folder exists
if (Test-Path -Path $userTempPath) {
# Calculate size before cleanup
$userBeforeSize = (Get-ChildItem -Path $userTempPath -Recurse -Force -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum).Sum / 1MB
$totalBeforeCleanup += $userBeforeSize

# Remove all files in the Temp folder
Get-ChildItem -Path $userTempPath -Recurse -Force -ErrorAction SilentlyContinue | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue

# Calculate size after cleanup (to check if any files were in use and not deleted)
$userAfterSize = (Get-ChildItem -Path $userTempPath -Recurse -Force -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum).Sum / 1MB
$totalAfterCleanup += $userAfterSize

# Output results for each user
Write-Output ("User: {0}`nSize before cleanup: {1:N2} MB`nSize after cleanup: {2:N2} MB`nCleaned up: {3:N2} MB" -f $_.Name, $userBeforeSize, $userAfterSize, ($userBeforeSize - $userAfterSize))
} else {
Write-Output "No Temp folder found for user: $($_.Name)"
}
}

# Output total cleanup summary
$totalCleanedUp = $totalBeforeCleanup - $totalAfterCleanup
Write-Output ("`nTotal size before cleanup: {0:N2} MB" -f $totalBeforeCleanup)
Write-Output ("Total size after cleanup: {0:N2} MB" -f $totalAfterCleanup)
Write-Output ("Total cleaned up: {0:N2} MB" -f $totalCleanedUp)

Published by

Rich

Just another IT guy.

Leave a Reply

Your email address will not be published. Required fields are marked *