Cleaning Temp folder

Windows uses a temporary folder as a scratch pad and dumping ground for all sorts of temporary files.  There are a couple of issues with the temporary folder. Firstly by default its part your profile and each user has their own. Secondly there isn’t any real clean up performed on it.

The first issue can be dealt with by editing the contents of the TEMP and TMP environmental variables. I’ll show a script for this another time.  The second we can deal with quite easily with these functions.

We can use Get-TempContents to determine the current contents of the temporary folder.  I’ve grouped by extension just to get a feel of the file distribution.  If you want to see the whole listing then leave the group command out.

001
002
003
function Get-TempContents {
    Get-ChildItem $env:temp | group extension
}

 

PowerShell exposes a number data stores via providers. One of these is the environmental variables. These can be accessed using

Get-ChildItem env:

where env: is the PowerShell drive for the environmental variables. Using aliases this becomes

ls env:   or  dir env:

Now we have an idea of what files we have we can remove them.

001
002
003
004
005
006
function Remove-TempContents {
    $extensions = ".tmp", ".log", ".sig", ".cvr", ".txt", ".xml", ".HxC", ".cfg", ".exe", ".msi"
    $td = (Get-Date).AddDays(-7)
   
    Get-ChildItem $env:temp | where {$extensions -contains $_.Extension -and $_.LastWriteTime -lt $td} | Remove-Item -Verbose
}

 

We can start by defining a list of file extensions that we want to delete. I have decided to only delete files older than 7 days so we generate a date for this time last week using the AddDays method of the DateTime object that Get-Date returns.

We can then get the contents of the temporary folder. Check the extension and the LastWriteTime and remove those files that match the criteria.

Next job is to schedule this job which is a topic for another day.

Published Wed, Nov 4 2009 13:39 by RichardSiddaway
Filed under:

Comments

# Cleaning the Temp folder - Scheduling

When I posted about cleaning the temp folder msmvps.com/.../11

Thursday, November 12, 2009 1:44 PM by Richard Siddaway's Blog

Leave a Comment

(required) 
(required) 
(optional)
(required)