Public/Clear-BrowserCache.ps1

<#
    .SYNOPSIS
    Clears browser cache files for all users.
    Browsers: Microsoft Edge, Internet Explorer, Google Chrome and Firefox.
 
    .NOTES
    Author: Tom de Leeuw
    Website: https://ucsystems.nl / https://tech-tom.com
#>

function Clear-BrowserCache {
    [CmdletBinding(ConfirmImpact='Medium', SupportsShouldProcess = $true)]
    param(
        # Enabling this parameter will skip confirmation.
        [Parameter(ValuefromPipeline = $True)]
        [Switch] $Force,

        [ValidateNotNullOrEmpty()]
        [ValidateSet("All", "Chrome", "Edge", "IE", "Firefox")]
        [Alias('Browser')]
        [string[]] $Browsers = "All"
    )

    begin {
        # Verify if running as Administrator
        Assert-RunAsAdministrator

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

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

        # Get all user folders, exclude administrators and default users
        $Users = Get-UserFolders

        # Edge (Chromium)
        $EdgeFolders = @(
            'AppData\Local\Microsoft\Edge\User Data\Default\Cache',
            'AppData\Local\Microsoft\Edge\User Data\Default\Cache\Cache_Data'
        )

        # Internet Explorer
        $IEFolders = @(
            'AppData\Local\Microsoft\Windows\Temporary Internet Files',
            'AppData\Local\Microsoft\Windows\WebCache',
            'AppData\Local\Microsoft\Windows\INetCache\Content.IE5',
            'AppData\Local\Microsoft\Windows\INetCache\Low\Content.IE5',
            'AppData\Local\Microsoft\Internet Explorer\DOMStore'
        )

        # Google Chrome
        $ChromeFolders = @(
            'AppData\Local\Google\Chrome\User Data\Default\Cache',
            'AppData\Local\Google\Chrome\User Data\Default\Cache2\entries',
            'AppData\Local\Google\Chrome\User Data\Default\Media Cache',
            'AppData\Local\Google\Chrome\User Data\Default\Code Cache'
        )

        # Firefox
        $FireFoxFolders = @(
            'AppData\Local\Mozilla\Firefox\Profiles\*.default\cache',
            'AppData\Local\Mozilla\Firefox\Profiles\*.default\cache2\entries',
            'AppData\Local\Mozilla\Firefox\Profiles\*.default\thumbnails',
            'AppData\Local\Mozilla\Firefox\Profiles\*.default\webappsstore.sqlite',
            'AppData\Local\Mozilla\Firefox\Profiles\*.default\chromeappsstore.sqlite'
        )

        # Initialize empty arrays to add folders to
        $Folders = @()
        $BrowserProcesses = @()

        switch ($Browsers) {
            { $_ -match 'All' } { 
                $Folders = $EdgeFolders + $IEFolders + $ChromeFolders + $FireFoxFolders
                $Browsers = @("Chrome","Edge","IE","Firefox")
                $BrowserProcesses = @('msedge', 'iexplore', 'chrome', 'firefox')
            }
            { $_ -match 'Edge' } { 
                $Folders = $Folders + $EdgeFolders
                $BrowserProcesses = $BrowserProcesses + 'msedge'
            }
            { $_ -match 'IE' } { 
                $Folders = $Folders + $IEFolders
                $BrowserProcesses = $BrowserProcesses + 'iexplore'
            }
            { $_ -match 'Chrome' } {
                $Folders = $Folders + $ChromeFolders
                $BrowserProcesses = $BrowserProcesses + 'chrome'
            }
            { $_ -match 'Firefox' } { 
                $Folders = $Folders + $FireFoxFolders
                $BrowserProcesses = $BrowserProcesses + 'firefox'
            }
        }
    }

    process {
        Write-Verbose "Starting browser cache cleanup process..."

        # Prompt for user verification before continuing
        if ( -not ($Force)) {
            Get-UserConfirmation -WarningMessage "This will stop all running Browser processes!"
        }

        # Kill browser process(es)
        foreach ($Browser in $BrowserProcesses) {
            try {
                Write-Verbose "Killing $Browser process(es)..."
                Get-Process -ProcessName $Browser -ErrorAction 'SilentlyContinue' | Stop-Process -Force -Confirm:$false
            }
            catch [System.SystemException] {
                Write-Error "No running $($_.Exception.ProcessName) processes."
            }
            catch {
                Write-Error "$($Browser): $($_.Exception.Message)"
            }
        }

        # Start cleaning files
        ForEach ($UserName In $Users) {
            $FilesToClean = ForEach ($FolderName In $Folders) {
                $FolderToClean = "$env:SYSTEMDRIVE\Users\$UserName\$FolderName"
                If (Test-Path -Path $FolderToClean) {
                    try {
                        Get-ChildItem -Path $FolderToClean -Recurse -Force -ErrorAction 'SilentlyContinue'
                    }
                    catch [System.IO.IOException] {
                        Write-Error "File in use: $($_.TargetObject)"
                    }
                    catch [System.UnauthorizedAccessException] {
                        Write-Error "Access denied for path: $($_.TargetObject)"
                    }
                    catch {
                        Write-Error "$($Username): $($_.Exception.Message)"
                    }
                }
            }
            $FilesToClean | ForEach-Object {
                if ($_.PSIsContainer) {
                    Write-Information "Cleaning directory: $($_.FullName)"
                }
                Remove-Item $_.FullName -Recurse -Force -ErrorAction 'SilentlyContinue'
            }
            Write-Information "Finished removing browser cache files for $Username."
        }
    }

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