Windows PowerShell


Windows PowerShell - Delete Temp Files

Windows PowerShell - Delete Temp FilesPowerShell, Remove-item

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

Our mission is to create a PowerShell script which deletes all files in a user's temp folder.  The point of this exercise is to free up disk space and possibly speed up a machine's performance.  What the script does is remove files left behind by programs that are unable to clear up after they close.  My idea would be to run this script just after machine startup or just before 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 this Temp folder in all Microsoft Operating systems. To cut a long story short, script this variable in PowerShell by employing: $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.

Guy Recommends: SolarWinds Engineer's Toolset v10Engineer's Toolset v10

The Engineer's Toolset v10 provides a comprehensive console of utilities for troubleshooting computer problems.  Guy says it helps me monitor what's occurring on the network, and the tools teaches me more about how the system literally operates.

There are so many good gadgets, it's like having free rein of a sweetshop. Thankfully the utilities are displayed logically: monitoring, discovery, diagnostic, and Cisco tools.  Download your copy of the Engineer's Toolset v 10

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:
Press: 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 occur under both 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 and thus create a cmdlet.  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
$GuyTemp = "$Env:temp"
set-location $GuyTemp
$Dir = get-Childitem $GuyTemp -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}

Guy Recommends: SolarWinds LANSurveyorSolarwinds LANSurveyor

LANSurveyor will produce a neat diagram of your network topology.  But that's just the start; LANSurveyor can create an inventory of the hardware and software of your machines and network devices.  Other neat features include dynamic update for when you add new devices to your network.  I also love the ability to export the diagrams to Microsoft Visio.

Finally, Guy bets that if you take a free trial of LANSurveyor then you will find a device on your network that you had forgotten about, or someone else installed without you realizing!

Download a Free Trial of LANSurveyor

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. 

# List Temp Files --> Output to a File
# Warning C:\ is a silly destination
# Better edit to: "C:\scripts\ListTemp.txt"
$File = "C:\ListTemp.txt"
$GuyTemp = "$Env:temp"
set-location $GuyTemp
$Dir = get-Childitem $GuyTemp -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 on this page 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 test-bed. 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.

See more Windows PowerShell real life tasks

PowerShell Home  • Real life tasks  • IpConfig  • Exchange  • Com objects  • Services  • Syntax

Please write in if you see errors of any kind.  Please report any factual mistakes, grammatical errors or broken links, I will be happy to not only to correct the fault, but also to give you credit.

Download my ebook:Getting Started with PowerShell
Getting Started with PowerShell - only $9.25

You get 36 topics organized into these 3 sections:
   1) Getting Started
   2) Real-life tasks
   3) Examples of Syntax.

In addition to the ebook, you get a PDF version of this  Introduction to PowerShell ebook  It runs to 120 pages of A4.

 *


Google

Web  This website

Review of Orion NPMGuy Recommends: Orion's NPM - Network Performance Monitor

Orion's performance monitor is designed for detecting network outages. A network-centric view make it easy to see what's working, and what needs your attention.

This utility guides you through troubleshooting by indicating whether the root cause is faulty equipment or resource overload.

Download a free trial of the Network Performance Monitor

 

Home Copyright © 1999-2009 Computer Performance LTD All rights reserved

Please report a broken link, or an error.