Windows · PowerShell

Clean Up Temporary Files on Windows

Deletes files older than 7 days in the Windows Temp folder and every user's Temp folder. Reports the space recovered.

Script Library
Live data
28scripts
  • Windows18
  • macOS5
  • Linux5
By category
  • Network3
  • Disk and storage4
  • Inventory4
  • Security9
  • Updates4
  • Maintenance4
Last reviewed: November 6, 2026
CODE

Script

clear-temp-files-windows.ps1
$cutoff = (Get-Date).AddDays(-7)
$paths = @("$env:SystemRoot\Temp") + (Get-ChildItem 'C:\Users' -Directory -ErrorAction SilentlyContinue | ForEach-Object { Join-Path $_.FullName 'AppData\Local\Temp' })
$freed = 0
foreach ($path in $paths) {
    if (-not (Test-Path $path)) { continue }
    Get-ChildItem $path -Recurse -File -Force -ErrorAction SilentlyContinue |
        Where-Object { $_.LastWriteTime -lt $cutoff } |
        ForEach-Object {
            $size = $_.Length
            Remove-Item $_.FullName -Force -ErrorAction SilentlyContinue
            if (-not (Test-Path $_.FullName)) { $freed += $size }
        }
}
Write-Output ("Freed {0:N1} MB" -f ($freed / 1MB))
Caution: Running a script is a sensitive action. Do not run code you have not read. A non-zero exit code shows as a failure in Moftgate output.
HOW IT WORKS

Run it on every device with Moftgate

  1. 01

    Add the script

    In the Moftgate console, open Scripts > New script and paste the code.

  2. 02

    Select the OS

    Select Windows as the target operating system.

  3. 03

    Test it

    Run it on one test device first and read the output.

  4. 04

    Roll out

    Send it to all targets by group, profile or tag. Each device result is recorded separately.

Read the Scripts guide →

ENTERPRISE SECURITY & BUSINESS RESILIENCE

Manage scripts from one console

Target selection, a confirmation step, per-device output and an audit log. The first 200 endpoints are free for a year.