Script to clear temporary files

This is a script I put together a few years ago, but have ended up using at some point at every employer since.

Installing an application (or even just running one) can create lots of temporary files. It’s not unusual to see hundreds of megabytes, or even gigabytes of data in your temp folder. This is wasted space which slows your machines down! I have used this script on workstations and servers, it’s a very quick way to get a big speed increase, especially for older boxes.

The script below will clear out C:\Windows\Temp as well as any %USERPROFILE%\Local Settings\Temp\ folders that it has access to. It can be run on any Windows machine newer than XP or Server 2003. For especially troublesome machines I recommend creating a scheduled task. Several times I have created a task that runs 30 minutes before the Defrag script, this helps to keen your hard disk clear and optimised.

You can easily expand the script to include additional directories, such as C:\Windows\SoftwareDistribution\Download\ if you want to clear up WSUS files.

'*Script Name: ClearTempFiles.vbs
'*Created on:  02/03/2009
'*Author:      Tom Anderson
'*Purpose:     This script clears all temp files from C:\%PROFILEFOLDER%\%USER%\Local
'*             Settings\Temp and C:\Windows\Temp\.

'*****First the script checks to see if C:\Users\ exists. If so then the machine is running
'*****Vista or 7, otherwise it runs XP.

Set Filesys = CreateObject("Scripting.FileSystemObject")
If Filesys.FolderExists ("C:\Users\") Then
path = "C:\Users\"
path = "C:\Documents and settings\"
End If

'*****Checks all profile folders and deletes all files from %USERPROFILE%\Local Settings\Temp\

Set objShell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(path)
Set subFolders = folder.SubFolders

For Each folderObject in SubFolders
If fso.FolderExists(path & folderObject.Name & "\Local Settings\Temp\") Then
objShell.currentdirectory = path & folderObject.Name & "\Local Settings\Temp\"
objShell.Run "cmd.exe /c rd ..\temp\ /s /q"
End If

'*****Clears the C:\WINDOWS\Temp\ directory

objShell.currentdirectory = "C:\WINDOWS\Temp\"
objShell.Run "cmd.exe /c rd ..\temp\ /s /q"

Posted in Guides Tagged with: , ,
0 comments on “Script to clear temporary files
1 Pings/Trackbacks for "Script to clear temporary files"
  1. […] Script to clear temporary files Tagged with: Administration, VBScript Posted in […]

Leave a Reply

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