PowerShell Scripts, Tips, Expert Advices, Forums, and Resources

Geek Sync Live

Welcome to PowerShell.com, the educational and community site for Windows PowerShell People. Get a quick overview.

Latest Blog Posts

05-28-2016 - Slides and Code from my WinOps 2016 talk
05-27-2016 - Cleaning Week: Deleting TEMP Files
05-26-2016 - DHCP scope

As a Powershell.com member you will have access to:

  • Daily PowerShell tips written by Microsoft MVPs and other leading Windows PowerShell experts
  • Free Windows PowerShell advice and training provided by Microsoft MVPs and other leading Windows PowerShell experts
  • Access to leading Windows PowerShell blogs
  • A free ebook, Mastering PowerShell, written by Microsoft MVP Dr. Tobias Weltner
PowerTip of the Day

Cleaning Week: Deleting TEMP Files

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!

Copyright 2012 PowerShell.com. All rights reserved.