Guy recommends :
Free Solarwinds
VM Console

Solarwinds VM Console Free Download

Find out which of your VMs are a waste of space and which VMs need more resources.



Windows PowerShell - Delete Temp Files

Windows PowerShell - Delete Temp FilesPowerShell 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.

Please Note:  Unusually for me, I have been unduly cautious on this page, because if a delete script goes wrong it could be devastating.

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: WMI Monitor and It's Free!Solarwinds Free WMI Monitor

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft operating systems.  Fortunately, Solarwinds have created a Free WMI Monitor so that you can discover these gems of performance information, and thus improve your PowerShell scripts.  Take the guess work out of which WMI counters to use when scripting the operating system, Active Directory or Exchange Server.

Download your free copy of WMI Monitor

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 Temp File 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' Free Bulk Import ToolFree Download of Solarwinds  Bulk Import Tool

Import users from a spreadsheet.  Just provide a list of the users with their fields in the top row, and save as .csv file.  Then launch this FREE utility and match your fields with AD's attributes, click to import the users.  Optionally, you can provide the name of the OU where the new accounts will be born.

There are also two bonus tools in this free download, and all 3 have been approved by Microsoft:

  1. Bulk-import new users into Active Directory.
  2. Seek and zap unwanted user accounts.
  3. Find inactive computers.

Download your FREE bulk import tool.

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. 

# Powershell Temp Files List --> 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 PowerShell 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: Actually 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 Temporary Files Deletion.  Note -force parameter
$Dir = Get-Childitem $Env:temp -recurse
$Dir | Remove-Item -force
foreach ($_ in $Dir ){$count = $count +1}
"Number of files = " +$count

Note:  See more on Remove-Item here.

Conclusion - PowerShell's Scripts to Delete Temp 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 PowerShell Temp Files Deletion

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.

If you like this page then please share it with your friends

 


See More Windows PowerShell Examples of Real-life Tasks

PowerShell Tutorials  • PowerShell Examples  • IpConfig  • PowerShell NetSh

Monitor Performance - PowerShell  • Get-Counter  • PowerShell temp

PowerShell WOL (Wake-on-Lan)  • Services   • Windows PowerShell

Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.

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.

 *


Custom Search

Guy Recommends: WMI Monitor and It's Free!Solarwinds WMI Monitor

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft operating systems.

Fortunately, Solarwinds have created the Free WMI Monitor so that you can actually see and understand these gems of performance information.  Take the guess work out of which WMI counters to use for applications like Microsoft Active Directory, SQL or Exchange Server.

Download your free copy of WMI Monitor

 

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

Please report a broken link, or an error.