PowerShell Script to Clean Temp Files Quickly
Get-ChildItem -Path $env:TEMP -Recurse | Remove-Item -Force -ErrorAction SilentlyContinue in PowerShell to clean temp files recursively and quietly.Examples
How to Think About It
$env:TEMP. Then, list all files and folders inside it recursively. Finally, delete these files and folders safely, ignoring errors like locked files.Algorithm
Code
Write-Output "Cleaning temp files in $env:TEMP" Get-ChildItem -Path $env:TEMP -Recurse -Force | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue Write-Output "Temp files cleaned successfully."
Dry Run
Let's trace cleaning temp files in a folder with 2 files and 1 subfolder containing 1 file.
Identify temp folder
Temp folder path is C:\Users\User\AppData\Local\Temp
List files recursively
Found: file1.tmp, file2.tmp, subfolder\file3.tmp
Delete files and folders
Deleted file1.tmp, file2.tmp, file3.tmp, then subfolder
| Item | Action |
|---|---|
| file1.tmp | Deleted |
| file2.tmp | Deleted |
| subfolder\file3.tmp | Deleted |
| subfolder | Deleted |
Why This Works
Step 1: Get temp folder path
Using $env:TEMP gets the current user's temp folder path dynamically.
Step 2: List all files and folders
The Get-ChildItem -Recurse command lists all files and folders inside the temp folder and its subfolders.
Step 3: Delete items safely
The Remove-Item -Force -Recurse -ErrorAction SilentlyContinue deletes all items, forcing deletion and ignoring errors like locked files.
Alternative Approaches
Write-Output "Cleaning only temp files in $env:TEMP" Get-ChildItem -Path $env:TEMP -Recurse -File | Remove-Item -Force -ErrorAction SilentlyContinue Write-Output "Temp files cleaned, folders kept."
Write-Output "Clearing content of large temp log files" Get-ChildItem -Path $env:TEMP -Recurse -Filter *.log | ForEach-Object { Clear-Content $_.FullName } Write-Output "Log files cleared."
Complexity: O(n) time, O(1) space
Time Complexity
The script visits each file and folder once, so time grows linearly with the number of items in the temp folder.
Space Complexity
The script uses constant extra space as it processes items one by one without storing them all simultaneously.
Which Approach is Fastest?
Deleting only files is slightly faster than deleting files and folders recursively because it skips folder removal steps.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Delete files and folders recursively | O(n) | O(1) | Complete cleanup including folders |
| Delete only files | O(n) | O(1) | Keep folder structure intact |
| Clear content of log files | O(m) | O(1) | Free space without deleting files |
-Recurse causes only top-level temp files to be deleted, leaving nested files untouched.