Remove CCMCache, Windows.old, and Temp folders using Powershell script

This PowerShell script automates the cleanup of:

  1. CCM Cache Files: Removes files older than 14 days from C:\Windows\ccmcache.
  2. Temporary Files: Cleans up files older than 14 days from the user’s temp folder ($env:Temp) and the system-wide temp folder (C:\Windows\Temp).
  3. Windows.old Folder: Deletes the Windows.old folder if it’s older than 14 days. This folder is typically created during a Windows upgrade and can take up significant disk space.

The script also logs all actions to a log file (C:\TempCleanupLog.txt), making it easy to track what was deleted and troubleshoot any issues.









# Define paths

$ccmCachePath = "C:\Windows\ccmcache"

$tempPath = "$env:Temp"

$systemTempPath = "C:\Windows\Temp"

$windowsOldPath = "C:\Windows.old"

$logFile = "C:\TempCleanupLog.txt" # Change log file location if needed


# Function to clean up files and directories older than a specific number of days

function Clean-OldFiles {

    param (

        [string]$Path,

        [int]$Days

    )


    if (Test-Path -Path $Path) {

        Write-Output "Cleaning up files and directories older than $Days days in: $Path"

        Add-Content -Path $logFile -Value "Starting cleanup in: $Path at $(Get-Date)"


        $deletedFiles = 0

        $deletedSize = 0


        # Delete files older than specified days

        Get-ChildItem -Path $Path -Recurse -File | Where-Object {

            $_.LastWriteTime -lt (Get-Date).AddDays(-$Days)

        } | ForEach-Object {

            try {

                $deletedSize += $_.Length

                $_ | Remove-Item -Force -Recurse -Verbose

                $deletedFiles++

                Add-Content -Path $logFile -Value "Deleted file: $($_.FullName)"

            } catch {

                Add-Content -Path $logFile -Value "Failed to delete file: $($_.FullName) - $($_.Exception.Message)"

            }

        }


        # Delete empty directories

        Get-ChildItem -Path $Path -Recurse -Directory | Where-Object {

            ($_ | Get-ChildItem -Recurse).Count -eq 0

        } | ForEach-Object {

            try {

                Remove-Item -Path $_.FullName -Force -Recurse -Verbose

                Add-Content -Path $logFile -Value "Deleted directory: $($_.FullName)"

            } catch {

                Add-Content -Path $logFile -Value "Failed to delete directory: $($_.FullName) - $($_.Exception.Message)"

            }

        }


        Add-Content -Path $logFile -Value "Deleted $deletedFiles files totaling $([math]::Round($deletedSize / 1MB, 2)) MB in: $Path at $(Get-Date)"

        Add-Content -Path $logFile -Value "Cleanup completed in: $Path at $(Get-Date)"

    } else {

        Write-Output "Path not found: $Path"

        Add-Content -Path $logFile -Value "Path not found: $Path at $(Get-Date)"

    }

}


# Function to delete the Windows.old folder if older than specified days

function Remove-WindowsOld {

    param (

        [string]$Path,

        [int]$Days

    )


    if (Test-Path -Path $Path) {

        $folderCreationDate = (Get-Item $Path).CreationTime

        if ($folderCreationDate -lt (Get-Date).AddDays(-$Days)) {

            Write-Output "Removing Windows.old folder older than $Days days: $Path"

            Add-Content -Path $logFile -Value "Attempting to remove Windows.old folder at $(Get-Date)"

            try {

                # Take ownership of the folder before removing it

                takeown /F $Path /R /D Y | Out-Null

                icacls $Path /grant Administrators:F /T | Out-Null

                Remove-Item -Path $Path -Force -Recurse -Verbose

                Add-Content -Path $logFile -Value "Successfully removed Windows.old folder at $(Get-Date)"

            } catch {

                Add-Content -Path $logFile -Value "Failed to remove Windows.old folder: $($_.Exception.Message)"

            }

        } else {

            Write-Output "Windows.old folder is not older than $Days days. Skipping removal."

            Add-Content -Path $logFile -Value "Windows.old folder is not older than $Days days. Skipping removal at $(Get-Date)"

        }

    } else {

        Write-Output "Windows.old folder not found."

        Add-Content -Path $logFile -Value "Windows.old folder not found at $(Get-Date)"

    }

}


# Main script execution

try {

    # Clean up CCMCache, Temp, and Windows.old

    Clean-OldFiles -Path $ccmCachePath -Days 14

    Clean-OldFiles -Path $tempPath -Days 14

    Clean-OldFiles -Path $systemTempPath -Days 14

    Remove-WindowsOld -Path $windowsOldPath -Days 14


    Write-Output "Cleanup completed successfully! Log file saved to $logFile"

} catch {

    Write-Output "An error occurred during cleanup: $_"

    Add-Content -Path $logFile -Value "An error occurred during cleanup: $_ at $(Get-Date)"

}

Popular Posts

Windows 11 24H2 Upgrade using Intune Feature Updates Policy

Deploying a Script through Intune to a Linux PC

Deleting Registry.pol and Forcing Group Policy Update Using a Batch File - Deploy through SCCM

Removing Obsolete Computer Records from Active Directory Using PowerShell (Only Windows Client Versions)