Disk Space Cleanup: PowerShell Script

An essential guide for IT professionals to automate disk space cleanup on Windows computers and improve system performance.

In this Guide:

Introduction

Low disk space is a common problem that can cause system performance issues, app crashes and annoying alerts. Manually managing disk space on individual computers is not scalable in a large organization. This guide provides a PowerShell disk space cleaner script that automates the process of finding and removing unnecessary files. By deploying this script, IT teams can proactively manage system health, prevent low disk space issues and have endpoints running at optimal performance. This is a must have in any PowerShell maintenance script arsenal.

Background

Over time Windows systems accumulate a lot of temporary files, cache data and old logs that consume disk space. This junk data serves no purpose after a certain period and can eventually cause system instability. Manually running the built-in Disk Cleanup or deleting files from different directories on hundreds of machines is not a viable option. This Windows junk file remover script solves this problem by providing a repeatable and automated process. It targets specific, safe-to-delete locations so a consistent and effective cleanup without the risk of removing user data.

Script

Here is the script. Save this as a .ps1 file and run as a scheduled task.

Copy to clipboard
# -----------------------------------------------------------------------------
# Script Name: Automated-DiskCleanup.ps1
# Description: Automates the cleanup of unnecessary files to free up disk space.
# -----------------------------------------------------------------------------

# --- CONFIGURATION ---
# Define the log file path
$logFile = "C:\Temp\DiskCleanup_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"

# Define directories to clean up (add more as needed)
$cleanupPaths = @(
    "$env:TEMP",
    "$env:LOCALAPPDATA\Temp",
    "$env:SystemRoot\SoftwareDistribution\Download",
    "$env:SystemRoot\Logs\CBS"
)

# Define file age in days for deletion
$fileAgeInDays = 7

# --- SCRIPT LOGIC ---
function Write-Log {
    param($message)
    Add-Content -Path $logFile -Value "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] $message"
    Write-Host "[$(Get-Date -Format 'HH:mm:ss')] $message"
}

Write-Log "Starting automated disk space cleanup..."
Write-Log "Log file created at: $logFile"
$totalSpaceFreed = 0

foreach ($path in $cleanupPaths) {
    if (Test-Path $path) {
        Write-Log "Scanning: $path"
        
        try {
            # Find files older than the specified age
            $filesToDelete = Get-ChildItem -Path $path -Recurse -Force -ErrorAction SilentlyContinue | Where-Object { 
                -not $_.PSIsContainer -and ($_.LastWriteTime -lt (Get-Date).AddDays(-$fileAgeInDays)) 
            }
            
            # Delete the files and calculate space freed
            foreach ($file in $filesToDelete) {
                $fileSizeMB = [math]::Round($file.Length / 1MB, 2)
                Remove-Item -Path $file.FullName -Force -ErrorAction SilentlyContinue
                $totalSpaceFreed += $file.Length
                Write-Log "Deleted: $($file.FullName) (Size: $($fileSizeMB) MB)"
            }
            
            # Clean up empty directories
            Get-ChildItem -Path $path -Directory -Recurse -ErrorAction SilentlyContinue | Where-Object {
                (Get-ChildItem -Path $_.FullName -Recurse).Count -eq 0
            } | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
            
        } catch {
            Write-Log "An error occurred while cleaning $path: $($_.Exception.Message)"
        }
    } else {
        Write-Log "Path not found: $path. Skipping." -ForegroundColor Yellow
    }
}

$totalSpaceFreedGB = [math]::Round($totalSpaceFreed / 1GB, 2)
Write-Log "Cleanup complete."
Write-Log "Total space freed: $($totalSpaceFreedGB) GB"

Detailed Breakdown

FeatureDescription
ConfigurationThe script uses variables at the top to make customization easy.
You can change the $logFile path, add or remove directories from the $cleanupPaths array,
and adjust the $fileAgeInDays to control how old a file must be before it's deleted.
This ensures the script is flexible and adaptable to different environments and policies.
LoggingA key feature of this automated temp file removal script is its robust logging.
The Write-Log function outputs messages to both the console and a timestamped log file.
This provides a clear audit trail of what was scanned, what was deleted, and how much space was reclaimed—crucial for troubleshooting and proving compliance.
Targeting Specific Files and DirectoriesThe foreach loop iterates through each path defined in the $cleanupPaths array.
For each path, Get-ChildItem with the -Recurse parameter scans all files and subdirectories.
The Where-Object clause then filters these items, ensuring only files older than the specified age are deleted.
File Deletion and Space CalculationThe script uses Remove-Item to delete files, with a try...catch block to handle permission issues gracefully.
It also calculates the size of each deleted file and maintains a running total, providing a final report of the total space freed in gigabytes.

Use Cases

  • Scheduled Maintenance: Run this script as a scheduled task on all endpoints weekly or monthly. This proactive approach means systems never get to critically low disk space and performance degrades and support tickets open.

  • Reactive Cleanup: When an IT support ticket is opened for a user with low disk space, run this script to free up disk space and resolve the issue.

  • Server Cleanup: The script can be modified to clean up log files, cache data and old backups on servers so they don’t require manual intervention.

Conclusion

Automating disk space management with a free up disk space script like this is a best practice for modern IT teams. It frees up time for support staff and the overall health of your IT estate. This script can be deployed across your entire organisation using tools like Group Policy or Microsoft Endpoint Configuration Manager. For more information on deployment methods see our guide on Deploying PowerShell Scripts with Group Policy.

Deploy this script across your Endpoints with Zecurit

Upload this script to Zecurit's Script Repository and execute it across hundreds of endpoints in minutes. Support for PowerShell, Bash, Python,and more with full audit trails and scheduling.

Frequently Asked Questions (FAQs)

  • What files are safe to delete?

    The script targets well-known, non-critical locations for temporary and cache files, which are generally safe to delete. It is important to avoid deleting files from system directories or user profiles that are not explicitly temporary. Customizing the $cleanupPaths variable allows you to target only locations that are safe for your environment.

  • How do I customize the script to delete other file types?

    You can add more directories to the $cleanupPaths array. For example, to clean up old log files in a specific application's folder, you would add its path to the list. You can also modify the Get-ChildItem cmdlet to filter for specific file extensions.

  • What permissions are needed to run the script?

    The script needs administrator privileges to access and delete files in system-level folders like C:\Windows\SoftwareDistribution. To run it effectively, it should be executed from an elevated PowerShell session or deployed via a method that grants it administrative rights, such as a scheduled task with "Run with highest privileges" enabled.

  • Can this script be used on a remote computer?

    Yes, this script can be executed on a remote computer using Invoke-Command. However, for large-scale, automated cleanup, deploying the script as a scheduled task or login script via Group Policy is a more scalable and efficient approach.