Cleaning Week: Deleting TEMP Files

by May 27, 2016

In a previous tip you learned how to check for left-over files in both your own temp folder and the one maintained by Windows. Today, let’s see how these folders can be cleaned up by PowerShell.

This code removes all files that haven’t changed in 3 months. Since the script cleans the Windows temp files, you need Administrator privileges to run it.

#requires -Version 3
#Requires -RunAsAdministrator
# must run with admin privileges!

# look at temp files older than 3 months
$cutoff = (Get-Date).AddMonths(-3)

# use an ordered hash table to store logging info
$sizes = [Ordered]@{}

# find all files in both temp folders recursively
Get-ChildItem "$env:windir\temp", $env:temp -Recurse -Force -File |
# calculate total size before cleanup
ForEach-Object { 
  $sizes['TotalSize'] += $_.Length 
  $_
} |
# take only outdated files
Where-Object { $_.LastWriteTime -lt $cutoff } |
# try to delete. Add retrieved file size only
# if the file could be deleted
ForEach-Object {
  try 
  { 
    $fileSize = $_.Length
    # ATTENTION: REMOVE -WHATIF AT OWN RISK
    # WILL DELETE FILES AND RETRIEVE STORAGE SPACE
    # ONLY AFTER YOU REMOVED -WHATIF
    Remove-Item -Path $_.FullName -ErrorAction SilentlyContinue -WhatIf
    $sizes['Retrieved'] += $fileSize
  }
  catch {}
}


# turn bytes into MB
$Sizes['TotalSizeMB'] = [Math]::Round(($Sizes['TotalSize']/1MB), 1)
$Sizes['RetrievedMB'] = [Math]::Round(($Sizes['Retrieved']/1MB), 1)

New-Object -TypeName PSObject -Property $sizes

Note that the code will not actually delete anything. It just reports what would have been deleted, and how much space you could retrieve. You must remove the -WhatIf parameter in the code (on your own risk) to actually delete things.

The result looks similar to this:

 
TotalSize Retrieved TotalSizeMB RetrievedMB
--------- --------- ----------- -----------
199690046  87763299       190,4        83,7
 

Twitter This Tip! ReTweet this Tip!