PowerShell Script to Delete Temp Files
I sense a changing of the guard – out with VBScript, and in with PowerShell. To date, my best work has been persuading over 2,000 people to download PowerShell from Microsoft’s site. However, downloading is not the same as using in a production network. Therefore, my new project is to provide a bank of handy cmdlet scripts; each cmdlet will automate a task in Windows Server 2003 / XP / Longhorn / Vista, and thus turn dabblers into believers. This week we tackle deleting temp files.
Topics – Delete Temp Files Using PowerShell
- This Week’s Secret
- This Week’s 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
- Windows 7 PowerShell Scripts
♣
This Week’s Secret
I am disappointed because over the last 3 months I have spent little time with PowerShell. Also, I am slightly surprised that there has not been more information in the press about PowerShell. One obvious comment is – Guy you have been reading the wrong articles!
What I am pleased with is how easy it is to get back in the saddle. It has been straightforward to pick up where I left off in December. The verb-noun pairs, the output pipe (|), and the syntax have all come flooding back.
Ezine 139 – Correction / Update
The main mission in Ezine 139 was to delete temporary files and my Example 2 worked a treat. The problem was with Example 1, which merely listed files. I only tested it with my OnScript editor, thus I overlooked that if I ran the script as suggested, it created about 97 message boxes, each with the name of one temporary file. Apologies. I have now amended the code in the online copy of Ezine 139, as a result the script gives just one message box. Thanks to Dan Weiner to alerting me to the problem.
This week’s mission
This Week’s Mission is once again to delete temporary files. However, the twist is we will use PowerShell rather than VBScript. It will be fascinating to compare how the old and the new scripting languages delete the temporary files.
Trap
Some installation files rely on temporary files, thus if you delete the temporary files on shutdown you could prevent the application completing.
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 you can check your operating system’s temp and windir variables
Windows Key +r (Run dialog box appears):
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.
Guy Recommends: Tools4ever’s UMRA
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 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]
cls
$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 to research the correct syntax for : $Env:temp.
Note 2: Set-location is much like CD (Change Directory)
Note 3: get-childitem, together with -recurse 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 two type of bracket (condition) {Do Stuff}
Note 6: See more on PowerShell's Environmental Variables.
Example 2: List Temp Files –> Output to a File
After last week’s debacle, 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.
cls
# 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, 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.
Guy Recommends: The Free IP Address Tracker (IPAT) 
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 3a Delete Temporary Files
As John McEnroe would say, ‘You cannot be serious’. How could such a tiny script 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.
Method 2 (Better) – Copy the code below 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]
cls
get-childitem $env:Temp | remove-item -recurse -force
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.
# get-childitem $env:Temp *.* -recurse | remove-item -force
$Dir = get-childitem $Env:temp -recurse
$Dir | remove-item -force
foreach ($_ in $Dir ){$count = $count +1}
"Number of files = " +$count
Summary – PowerShell Script 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.
See here for updates to this PowerShell Script to Delete Temporary Files
If you like this page then please share it with your friends
See more Microsoft PowerShell tutorials
• PowerShell Tutorials • Methods • Cmdlets • PS Snapin • Profile.ps1 • Exchange 2007
• Command & Expression Mode • PowerShell pipeline (|) • PowerShell ‘where‘ • PowerShell ‘Sort’
• Windows PowerShell Modules • Import-Module • PowerShell Module Directory
If you see an error of any kind, do let me know. Please report any factual mistakes, grammatical errors or broken links.