Guy’s Ezine 139 – Deleting Temporary Files

Guy’s Scripting Ezine 139 – Deleting Temporary Files

This week we have a dangerous mission, to delete all the temporary files in a user’s profile.  I say dangerous, only because any script which deletes, can cause unexpected problems in the hands of a Psycho. (Every newsletter has 2 or 3 Psychos amongst its readership.)

During our journey to clear the %temp% folder, we will learn about scripting Environmental Variables.  In addition, before we delete the files in Example 2, we will merely list them in Example 1.  This is but one of several safety checks to prevent a rogue delete script from wrecking your system.

Topics for Deleting Temporary Files

 ♣

This Week’s Secret

How do you rate on Guy’s scripting assessment?

Grade A – Can write your own scripts from first principles.

Grade B – You can troubleshoot scripts.  (In addition to Grade C, D and E below.)

Grade C – You get the job done by bolting two scripts together.

Grade D – After copying and pasting, you can change values and variables.

Grade E – You copy and paste other people’s scripts.

I confess that even on my own grading system, I only make Grade B.

How do you learn scripting?

The ‘correct’ answer to ‘How should you learn scripting’, is to enrol at a college, or to take a structured VBScript course.  To let you into a secret, I have no formal scripting training, I learned by copying and pasting other peoples scripts, then adapting them to my own situation.  I have been lucky to have had exposure to a wide variety of scripts.  My experience started with mapping network drives, encompassed WMI scripts, and moved on to manipulating users in Active Directory.

Whether it’s learning about a mechanical object, or a script, only when you take it to pieces, repair a fault, and then re-assemble the parts, that you truly understand how something works.  Thanks to my readers’ letters, I have had considerable practice at repairing VBScripts.

If I could distil my experience into one phrase it would be this, ‘collect verbs’ for example, get or create.  Scripters absorb the syntax rules via the hard school of knocks, but the secret of progress is to home in on scripting verbs.  In particular, watch out for verbs that connect to Active Directory (GetObject("LDAP://rootDSE"), to a server (MapNetworkDrive), or in the case of this week’s script, (GetObject("Scripting.FileSystemObject).

This Week’s Mission

This Week’s Mission to delete temporary files.  In particular, we will delete files in the %temp% folder.  While our objectives are clear, we need to be on the lookout for ambushes by the environmental variables.  In addition, we must guard against shooting ourselves in the foot with the ‘delete’ command.  Because I am so nervous about the reader from hell misunderstanding, and deleting the wrong files, I am creating the script in two parts.  This is rather like keeping detonators and their shells in separate buildings, then giving you the task of assembling the ammunition and firing off the missile.

In part one I will explain the role of environmental variables and FileSystemObject (FSO), in part two I will move on to listing files, then finally, to showing you how to actually delete files in the %temp% folder.

Scripting Environmental Variables

To see what I mean by an environmental variable try this: Start, Run and type: %temp%.  Also try Start, Run, %windir%.  Now link what happens when you use these %variables%, with what you see in the System Icon, Advanced, Environmental Variables.  Note in passing that Temp and Tmp both occur under the User and System variables.  Also be aware that the User’s %temp%, which we will use in our script, corresponds to %USERPROFILE%\Local Settings\Temp.  As you may know, in XP the %USERPROFILE% is stored under the Documents and Settings folder.

To let you into secret, the hardest task in this script was mastering ExpandEnvironmentStrings, eventually I produced:

strEnv = objShell.ExpandEnvironmentStrings("%temp%")

FileSystemObject

FSO (FileSystemObject) is an old friend.  If you are of a mind to learn about this important object, study the role of CreateObject, and then GetFolder.  Incidentally, if you get a good script editor such as OnScript, then you can see the properties and methods available to each object that you create.  If you examine my example script you will see that strFile supports the properties .name and .type.  OnScript also shows us that strFile supports the methods .copy and .delete – more of .delete later.

Guy Recommends: Tools4ever’s UMRAUMRA The User Management Resource Administrator

Tired of writing scripts? The User Management Resource Administrator solution by Tools4ever offers an alternative to time-consuming manual processes.

It features 100% auto provisioning, Helpdesk Delegation, Connectors to more than 130 systems/applications, Workflow Management, Self Service and many other benefits. Click on the link for more information onUMRA.

Example Script 1: To List Temporary Files

Please note, that this is only what I call a stepping-stone script.  Our main mission in Example 2 is to delete temporary files; here in Example 1 we merely echo the temporary filenames to a WSH message box.  My idea behind including Example 1 is to give you practice before you undertake the serious mission of deleting files, albeit temporary files.

This script connects to the %temp% folder, which stored in the users profile, and then displays the names of all the .tmp files.

Instructions

  1. Copy and paste the script below into notepad, or get a script editor such as OnScript.
  2. Save the file with .vbs extension e.g. ListFiles.vbs
  3. Double-click the ListFiles.vbs file and observe a list of .tmp files

‘ Sample VBScript to list TMP files using FileSystemObject
‘ Author Guy Thomas https://computerperformance.co.uk/
‘ Version 1.8 – April 2007
‘ —————————————————————‘
Option Explicit
Dim objFSO, objFiles, objShell, intCount
Dim strFile, strName, strLongName, strDirectory, strEnv, strExt
Set objShell = CreateObject("Wscript.Shell")
strEnv = objShell.ExpandEnvironmentStrings("%temp%")
intcount = 0

‘ Create the File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFSO = objFSO.GetFolder(strEnv)
Set objFiles = objFSO.Files
For each strFile in objFiles
   strExt = strFile.Type
     If ucase(strExt) = "TMP FILE" Then
     strName = strFile.Name
     strLongName = strLongName & strName & VBTab & VBTab
     intCount = intCount +1
   End if
next
WScript.Echo "The number of temp files is: " & intCount
WScript.Echo strLongName & VbCr & intCount
set objFSO = nothing
set strFile = nothing
set objFiles = nothing
WScript.Quit

Learning Points for Listing Files

Note 1:  I have added an extra safety check in Example 1.  The ‘If’ statement ensures that the script lists only TMP files.  Be aware that in the script below I have removed this ‘safety catch’ and consequently Example 2 deletes all files in the folder specified by strEnv.

Note 2: Most scripts that list, or delete, need a loop.  In this example I employ: For Each…. Next, to make the script cycle through all the files.

Guy Recommends: The Free IP Address Tracker (IPAT) IP Tracker

Calculating IP Address ranges is a black art, which many network managers solve by creating custom Excel spreadsheets.  IPAT cracks this problem of allocating IP addresses in networks in two ways:

For Mr Organized there is a nifty subnet calculator, you enter the network address and the subnet mask, then IPAT works out the usable addresses and their ranges. 

For Mr Lazy IPAT discovers and then displays the IP addresses of existing computers. Download the Free IP Address Tracker

Example Script 2: To Delete All Temporary Files

The purpose of this script is to delete files.  At the moment it’s rather like a gun which fires blanks.  What I mean is that the script, as written, merely deletes files in the D: \temp folder.  Your job is to make one tiny amendment and thus allow the script to delete all files in the %temp% folder.  To be frank, if you cannot work out how to do this, then for your own safety, you should not run scripts which use delete – for fear of deleting the wrong files. 

Good news, if you can achieve this task then you make Grade ‘C’ on Guy’s grading chart.

‘ DelFiles.vbs
‘ Sample VBScript to delete files using FileSystemObject
‘ Author Guy Thomas https://computerperformance.co.uk/
‘ Version 2.3 – April 2007
‘ ——————————————————–‘
Option Explicit
Dim objFSO, objFiles, objShell, intCount
Dim strFile, strName, strDirectory, strEnv, strExt
Set objShell = CreateObject("Wscript.Shell")
‘ ———————————————————
‘ Below is where you edit to delete files in %temp% folder
strEnv = "D:\temp"
‘ strEnv = objShell.ExpandEnvironmentStrings("%temp%")
intcount = 0

‘ Create the File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFSO = objFSO.GetFolder(strEnv)
Set objFiles = objFSO.Files
For each strFile in objFiles
On Error Resume Next
    strFile.delete
    intCount = intCount +1
next

set objFSO = nothing
set strFile = nothing
set objFiles = nothing
WScript.Echo intCount & " files were deleted"
WScript.Quit

Summary of Deleting Temporary Files

Our mission has been to rid a computer of all those temporary files which applications failed to clear up.  I hope you have enjoyed the long and varied journey through, environmental variables, FileSystemObject, listing files, and finally deleting files in the %temp% folder.  My hidden agenda has been to take readers from Grade E (Just copy and paste scripts), to Grade C, bolt two scripts together and make changes to variables.

See more about scripting files with VBScript

VBScripts  • Ezines  • WMI  • Create files  • File Open  • Ezine 12 FSO  • Permissions Analyzer

• Ezine 35 FSO  • Ezine 36 FSO II  • Ezine 43 File Create  • PowerShell Create Files

Ezine 78 Files  •Ezine 79 Files  • Ezine 104 FSO  •Ezine 139 Delete Temporary