Public/Optimize-SystemFiles.ps1

<#
    .SYNOPSIS
    Removes common system-wide temporary files and folders older than $Days old.
    OPTIONAL: Clears Windows Recycle Bin
    Folders:
        "$env:SystemRoot\Temp"
        "$env:SystemRoot\Logs\CBS"
        "$env:SystemRoot\Downloaded Program Files"
        "$env:ProgramData\Microsoft\Windows\WER"
 
    .NOTES
    Author: Tom de Leeuw
    Website: https://ucsystems.nl / https://tech-tom.com
#>

function Optimize-SystemFiles {
    [CmdletBinding()]
    param(
        # Only remove files and folders older than $Days old.
        [Parameter(Mandatory = $true, Position = 0)]
        [int] $Days,

        # Removes common system-wide temporary files and folders older than $Days old.
        [switch] $TempFiles,

        # Clears Windows Recycle Bin
        [switch] $RecycleBin
    )

    begin {
        # Verify if running as Administrator
        Assert-RunAsAdministrator

        # Start timer
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew()

        # Get disk space for comparison afterwards
        $Before = Get-DiskSpace

        # Folders to clean up
        $Folders = @(
            "$env:SystemRoot\Temp",
            "$env:SystemRoot\Logs\CBS",
            "$env:SystemRoot\Downloaded Program Files",
            "$env:ProgramData\Microsoft\Windows\WER"
        )
    }

    process {
        # Common temp files
        if ($TempFiles -eq $true) {
            Write-Verbose "Cleaning SYSTEM folders/files older than $Days days old..."
            $FilesToClean = ForEach ($Folder in $Folders) {
                if (Test-Path -Path $Folder) {
                    try {
                        Get-ChildItem -Path $Folder -Recurse -Force -ErrorAction 'SilentlyContinue' |
                            Where-Object { ($_.CreationTime -and $_.LastWriteTime -lt $(Get-Date).AddDays(-$Days)) }
                    }
                    catch {
                        Write-Error $_
                    }
                }
            }
            $FilesToClean | ForEach-Object {
                if ($_.PSIsContainer) {
                    Write-Information "Cleaning directory: $($_.FullName)"
                }
                Remove-Item $_.FullName -Recurse -Force -ErrorAction 'SilentlyContinue'
            }
            Write-Information "Finished removing System temp files."
        }

        # Empty Recycle Bin
        if ($RecycleBin -eq $true) {
            try {
                Write-Verbose 'Clearing Recycle Bin'
                Clear-RecycleBin -Force
            }
            catch {
                Write-Error $_
            }
        }
    } # end Process

    end {
        New-CleanupReport -Name "SystemFiles"
    }
}