CBC Computer Services

PowerShell Script to Delete Temp Files.

You can use a PowerShell script to automatically delete temporary files from your system. Here’s a simple script that targets common temporary file directories such as the Windows Temp folder and the user’s Temp folder.

PowerShell Script to Delete Temp Files

# Define the paths to the temp folders
$TempPaths = @(
    "$env:Temp",              # User's temp folder
    "$env:SystemRoot\Temp"     # Windows temp folder
)

# Loop through each path and remove files
foreach ($TempPath in $TempPaths) {
    if (Test-Path $TempPath) {
        Write-Host "Cleaning temp folder: $TempPath"

        # Get all files and subfolders
        Get-ChildItem -Path $TempPath -Recurse -Force | ForEach-Object {
            try {
                # Remove files and folders, force delete, and suppress errors
                Remove-Item $_.FullName -Force -Recurse -ErrorAction SilentlyContinue
                Write-Host "Deleted: $($_.FullName)"
            }
            catch {
                Write-Host "Failed to delete: $($_.FullName)" -ForegroundColor Red
            }
        }
    }
    else {
        Write-Host "Path not found: $TempPath" -ForegroundColor Yellow
    }
}

Write-Host "Temporary files cleanup complete."

How to Use This Script:

  1. Open Notepad and paste the script above.
  2. Save the file with a .ps1 extension, e.g., DeleteTempFiles.ps1.
  3. Run the script by opening PowerShell as an Administrator:
  • Right-click the Start button and choose Windows PowerShell (Admin).
  • Navigate to the folder where you saved the script using cd.
  • Run the script with the following command:
    powershell .\DeleteTempFiles.ps1

Explanation:

  • $env:Temp: Refers to the user’s temp folder.
  • $env:SystemRoot\Temp: Refers to the Windows temp folder.
  • Get-ChildItem -Recurse: Recursively lists files and folders.
  • Remove-Item -Force: Deletes files and folders.
  • -ErrorAction SilentlyContinue: Ignores errors like files in use or permission issues.

You can schedule this PowerShell script using Task Scheduler to run periodically for automatic cleanup.