The Temp Directory (Space eater)
The never ending directory that fills up with almost everything. As IT Admins, one of the first places we look to clear up space is the directory “C:\Windows\Temp” as this folder can grow pretty large over time causing issues on a server.
Managing a large number of servers does take time away, especially when you need to clear files on all of them.
I had a simple PowerShell script but tweaked it as some programs that write to the Temp directory, do not allow an Administrator, Domain Admin to delete the files and folders as no permissions are set for that user.
Modifying the script to take ownership of these stubborn files and folders allows us to delete them.
The script also creates a logging text file of what was set and what was deleted. You should be able to add this to a scheduled task to run and email you the logging file.
Here is the PowerShell script, tested on Windows PowerShell and PowerShell ISE:
$limit = (Get-Date).AddDays(-2)
$path = "C:\Windows\Temp\*"
$logFile = "C:\Windows\Temp\cleanup_log.txt"
# Initialize log file
"Cleanup started at $(Get-Date)" | Out-File -FilePath $logFile -Append
# Take ownership and grant full control
Get-ChildItem -Path $path -Recurse | ForEach-Object {
try {
takeown /f $_.FullName /a /r /d y
icacls $_.FullName /grant administrators:F /t
"Ownership and permissions set for: $($_.FullName)" | Out-File -FilePath $logFile -Append
} catch {
"Failed to set ownership/permissions for: $($_.FullName) - Error: $($_.Exception.Message)" | Out-File -FilePath $logFile -Append
}
}
# Get files and folders older than the $limit
$items = Get-ChildItem -Path $path -Recurse | Where-Object { $_.CreationTime -lt $limit }
# Log the items to be deleted
"Items to be deleted:" | Out-File -FilePath $logFile -Append
$items | ForEach-Object { $_.FullName | Out-File -FilePath $logFile -Append }
# Delete items older than the $limit
$items | ForEach-Object {
try {
Remove-Item -Path $_.FullName -Force -Recurse
"Deleted: $($_.FullName)" | Out-File -FilePath $logFile -Append
} catch {
"Failed to delete: $($_.FullName) - Error: $($_.Exception.Message)" | Out-File -FilePath $logFile -Append
}
}
"Cleanup completed at $(Get-Date)" | Out-File -FilePath $logFile -Append
It takes a few minutes to run, depending on the number of files and folders it has to set ownership on and remove
Hope you find it helpful.