PowerShell – Delete Temporary Files

How to Delete Temporary Windows Files with PowerShellPowerShell Delete Temp files

These scripts are designed to delete temporary files under the windir folder.  I have other scripts to delete the internet temporary files.

The teaching highlights are Remove-Item’s use of the -Recurse and -Force parameters.

Topics – Delete Windows Temporary Files Using PowerShell

 ♣

Our Mission

The problem is that the operating system creates temporary files, which it does not clean up when they are no longer needed.  Some of these tmp files date back to installation either of the OS itself or subsequent updates.

Rather than deleting all the C:\ Windows temporary files, I want to begin by clearing-up only temporary files that are older than 500 days.  One benefit is that you can make refinements, and then change 500 to 365 – and still get worthwhile results.  Finally you may like to set the days to keep only the last month’s files.

Project Management

  1. Obtain a stream of temporary files.
  2. Filter the files based on date.
  3. Delete the resulting files.
  4. As a bonus calculate the disk space freed-up.

Stage 1: Count the Temporary Files

I have chosen the C:\ Windows\Temp folder as the target to delete files.  In these scripts I use the built-in variable $env:windir.  Please understand that \Temp is its important sub-directory. 

Also realise that windir is different from the $env:temp variable.  Be clear whether you are dealing with deleting the users AppData temporary internet files. ($env:temp), or deleting the operating system’s temp files. ($env:windir\Temp).

Let us begin with a harmless script to count the temporary files.

# PowerShell Script to List the System Temp Files
$Target = "$env:windir\Temp\"
$List = Get-ChildItem $Target -Recurse
"Number of files " +$List.Count

Note 1: As we shall see the -Recurse parameter is important if you want PowerShell to find then delete all the temp files in the sub-directories.

Stage 2: Filter Files Based on Date

If we want to use age to filter the files, then not only do we need to get today’s date, but also we need to subtract x number of days.  This why we introduce New-TimeSpan.

Clear-Host
$Target = "$env:windir\Temp\"
$Aged = (Get-Date) – (New-TimeSpan -Days 500)
$List = Get-ChildItem $Target -Recurse | `
Where-Object { $_.Length -ne $Null } | `
Where-Object { $_.LastWriteTime -lt $Aged } | `
"Number of files " +$List.Count

Note 2: Experiment by reducing -Days 500 to 200 or less.

Note 3: The word-wrapping backtick (`) is optional in PowerShell v3.

Stage 3: Actually Delete the Temporary Files

This is where you need to pay careful attention, a rogue script could delete vital files, especially if you employ the -Force parameter.  Remember that PowerShell has no verb called delete, the correct cmdlet is ‘Remove-Item’.

# PowerShell Script to delete temporary files
Clear-Host
$Target = "$env:windir\Temp\"
$Aged = (Get-Date) – (New-TimeSpan -Days 500)
$List = Get-ChildItem $Target -Recurse | `
Where-Object { $_.Length -ne $Null } | `
Where-Object { $_.LastWriteTime -lt $Aged } | `
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
"Number of files " +$List.Count

Note 4: Remove-Item is the key action.  Strangely it needs the -Recurse parameter even though it’s also used in Get-ChildItem.

Note 5: For safety you may wish to append -WhatIf to the Remove-Item command.

Note 6: While $List.Count was productive in the earlier stages, it’s not producing useful results here, hence stage 4 will calculate the disk space reclaimed by PowerShell deleting these temporary files.

SolarWinds Firewall Browser Solarwinds Free Firewall Browser

Here is an utility where you can review firewall settings such as access control lists (ACL), or troubleshoot problems with network address translation (NAT).

Other reasons to download this SolarWinds Firewall Browser include managing requests to change your firewall settings, testing firewall rules before you go live, and querying settings with the browser’s powerful search options.

Guy recommends that you download a copy of the SolarWinds free Firewall Browser.

Stage 4: Delete Temp Files and Calculate Extra Free Space

Observe how both new variables $Before and $After employ the Measure-Object cmdlet.

Clear-Host
$Target = "$env:windir\Temp\"
$Before = (Get-ChildItem $Target -Recurse | Measure-Object Length -Sum).Sum
$Aged = (Get-Date) – (New-TimeSpan -Days 500)
$List = Get-ChildItem $Target -Recurse | `
Where-Object { $_.Length -ne $Null } | `
Where-Object { $_.LastWriteTime -lt $Aged } | `
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
$After = (Get-ChildItem $Target -Recurse | Measure-Object Length -Sum).Sum
‘You now have an extra {0:0.00} MB of disk space’ -f (($Before-$After)/1MB)

Note 7: I enjoyed using the -f formatting command in this script.

Note 8: See more about PowerShell's Remove-Item.

Using PowerShell to Delete Temporary Internet Files
By simply changing the path you could delete files in other locations, this makes Remove-Item a dangerous command in the wrong hands.  If you want to delete the current user’s temporary internet files then you need to understand another system variable: $env:temp.

See more about deleting temp files »

Summary of Deleting Temporary Files with PowerShell

Delete, or in PowerShell’s language ‘Remove’, is a forceful command that could lead to unforseen consequences.  This is why I have built the script is stages and provided notes on the technique.  One of the benefits of providing feedback for each stage is that you can see how much diskspace these temporary files consume, and thus why it’s productive to have a clear out.

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.