• No results found

Deleting Temp Files

Here are step-by-step instructions to delete a user's

temporary files using PowerShell commands. I will also show you how to script environmental variables, such as Temp or windir.

Topics - Delete Temp Files Using PowerShell

• Our Mission

• Scripting Environmental Variables

• Example 1: PowerShell Script to List the Temp Files • Example 2: List Temp Files --> Output to a File

• Example 3a: PowerShell Script to Delete Temporary Files • Example 3b: Delete Temporary Files

• Summary - PowerShell Script to Delete Files Our Mission

Our mission is to create a PowerShell script which deletes all of a user's temp files. The point of this exercise is to speed up a machine's performance by removing unnecessary files left by programs that are unable to clear up after they close. My idea would be to run this script at machine startup or at shutdown.

In XP most, but not all, temp files are stored in the folder which corresponds to: %USERPROFILE%\Local Settings\Temp

or in Vista:

%USERPROFILE%\AppData\Local\Temp

The key point is that %temp% environmental variable controls the location of the temp files in all Microsoft Operating systems. To cut a long story short, to script this variable in PowerShell employ: $env:temp.

Trap

I do not like disclaimers. However, let me say two things: 'Firstly, take extra care with ANY script which deletes data. Secondly, abandon the usual method of mindlessly copying and pasting the code, and instead, take the time to understand each component. '

Addendum

Jo Enright wrote in saying that a program that he was trying to install would not work. The reason was that it needed temp files after the reboot. Sadly, the PowerShell script deleted those temp files. Preparation

Download PowerShell from Microsoft's site. One interesting point is that there are different versions of PowerShell for XP, Windows Server 2003 and Vista.

Scripting Environmental Variables

To make sense of this script you must understand Environmental Variables. Here is how to check your operating system's temp and windir variables

Windows Key +r (Run dialog box appears): Type: %temp%.

You can also try: Start, Run, %windir%.

What I would like to do next is make the connection between what happens when you 'Run' these %variables%, with what you see in this location: 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 already know, in XP the %USERPROFILE% is stored under the Documents and Settings folder.

Example 1: PowerShell Script to List the Temp Files

To gain confidence, and for the sake of safety, I want start by just listing the temporary files. Instructions

Method 1 - Copy and paste the code below into a PowerShell command box.

Left-click on the PowerShell symbol (Top Right of box), select Edit, Paste and then press Enter twice. Method 2 (Better) - Copy the code below into a text file.Save with .ps1 extension e.g.

C:\scripts\List.ps1 .

Navigate in PowerShell to C:\scripts. Type dir, you should see a file called list.ps1 (Type) .\list [Dot backslash filename]

# PowerShell Script to List the Temp Files $PathTemp = "$Env:temp"

set-location $PathTemp

$Dir = get-childitem $PathTemp -recurse

$List = $Dir | Where-object {$_.extension -eq ". tmp"} foreach ($_ in $List ){$_.name

$count = $count +1} "Number of files " +$count

Note 1: It is hard to believe, but the most difficult part of this project was researching the correct syntax for : $Env:temp.

Note 2: Set-location is much like CD (Change Directory)

Note 3: get-childitem, with used with the –recurse parameter, is like the dos /s switch. Note 4: Where-object is just a safety clause to make sure that we only list . tmp files.

Note 5: The key to PowerShell's loop syntax is to examine the two types of bracket (condition) {Do Stuff}

Example 2: List Temp Files --> Output to a File

Here is extra code, which outputs the list to a file.The key point is to pipe (|) the result to out- file.Instructions, see and modify those is Example 1.

# List Temp Files --> Output to a File # Warning C:\ is a silly destination # Better edit to: "C:\scripts\ListTemp.txt" $File = "C:\ListTemp.txt"

$PathTemp = "$Env:temp" set-location $PathTemp

$Dir = get-childitem $PathTemp -recurse

$List = $Dir | Where-object {$_.extension -eq ". tmp"} foreach ($_ in $List ){$Temp = $Temp + "`t" + $_.name $count = $count +1}

"Number of files " +$count $Temp | out-file -filepath $File

Note 1: I hope that you changed this line: $File = "C:\ListTemp.txt". It is bad practice to save such files to the root; however, my problem is that I do not know if you have a c:\scripts folder, so I dare not save to a non-existent folder.

Note 2: `t is PowerShell's tab command; the equivalent of VbTab. Example 3a Delete Temporary Files

As John McEnroe would say, 'You cannot be serious'. How could the tiny script below have the ability to find, and then delete all the temporary files? Part of the answer is: 'PowerShell punches above its weight; every word is loaded with meaning. The other answer is more mundane, the script does not delete ALL the temporary files because some are in use!

Instructions

Method 1 - Copy and paste the code below into a PowerShell command box.

Left-click on the PowerShell symbol (Top Right of box), select Edit, Paste and then press Enter twice. # PowerShell code to delete Temporary Files

get-childitem $env:Temp | remove-item -recurse -force

Method 2 (Better) - Copy the code same code (above) into a text file.Save with .ps1 extension e.g. C:\scripts\DelTemp.ps1 .

Navigate in PowerShell to C:\scripts. Type dir, you should see list.ps1 (Type) .\DelTemp [Dot backslash filename]

Example 3b: Delete Temporary Files

While this script has more code than Example 3a, it is no better. However, it has the interesting feature that it displays the number of temporary files. When I ran Example 1 (Listing) I had 256 tmp files. Once I ran Example 3b, I only had 12 tmp files, and they are in needed by programs running on my machine. Thus the remove-item command is working.

# # PowerShell cmdlet to delete Temporary Files. Note -force $Dir = get-childitem $Env:temp -recurse

$Dir | remove-item -force

foreach ($_ in $Dir ){$count = $count +1} "Number of files = " +$count

Conclusion - PowerShell's Scripts to Delete Files

With PowerShell a little code goes along way. Here is a potent script, which is useful for deleting a user's temporary files.

Summary of Deleting Temporary Files

As usual, I like to split a PowerShell task into chunks. My strategy is to master each chunk of code, then bolt together all the components, thus creating the final script. In the case of PowerShell, these chunks are exceedingly small. The part that took me the longest was to master the special

environmental variable: $env:Temp. Fretting about just these 9 characters looks silly now, but it does emphasise the efficiency of writing code in PowerShell.

Remove-item was another chunk of code that I experimented with in its own testbed. I am still nervous that you could mis-read or mis-apply this command, and consequently delete all of your Windows files. Consequently, do be careful, think about what you are doing and make sure that you understand the implications of the -recurse and -force switches.