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 Env:temp or %windir%.

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

Topics – PowerShell Deletes Files

 ♣

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, Vista and later Windows operating systems 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, use 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.

Guy Recommends: Free WMI Monitor for PowerShellSolarwinds Free WMI Monitor for PowerShell

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft’s 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. Give this WMI monitor a try – it’s free.

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.  (In XP the %USERPROFILE% is stored under the Documents and Settings folder).  See a list of all environmental variables.

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"
$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: Environmental Variables.

Note 2: Get-Childitem, with used with the -Recurse parameter, is like the dos /s switch.

Note 3: Where-object is just a safety clause to make sure that we only list .tmp files.

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

Note 5: It’s more efficient to replace the last 3 lines with:
"Number of tmp files: " + $List.count

Guy Recommends:  A Free Trial of the Network Performance Monitor (NPM)Review of Orion NPM v11.5 v11.5

SolarWinds’ Network Performance Monitor will help you discover what’s happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems.  Its also has the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM now.

Download a free trial of Solarwinds’ Network Performance Monitor

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"
$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 6: 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 7: `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

Note 8:  See more on Remove-Item here.

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]

Engineer's Toolset v10Guy Recommends: SolarWinds Engineer’s Toolset v10

This Engineer’s Toolset v10 provides a comprehensive console of 50 utilities for troubleshooting computer problems.  Guy says it helps me monitor what’s occurring on the network, and each tool teaches me more about how the underlying system operates.

There are so many good gadgets; it’s like having free rein of a sweetshop.  Thankfully the utilities are displayed logically: monitoring, network discovery, diagnostic, and Cisco tools.  Try the SolarWinds Engineer’s Toolset now!

Download your fully functional trial copy of the Engineer’s Toolset v10

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 9: You may like to add the -Recurse parameter thus:
Remove-Item -Recurse -Force.

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.

See also how PowerShell deletes temporary Windows 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 variables

Syntax   • PowerShell Variables   • Get-PSProvider   • PowerShell Env:Path  • Free WMI Monitor

PowerShell Functions   • Get-PSDrive   • PowerShell New-PSDrive   • Remove-PSDrive

PowerShell Home   • PowerShell Environmental Variable   • PowerShell Dollar Variable

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.