Skip to content

Instantly share code, notes, and snippets.

@mark05e
Forked from pmsmith/DriveClean.ps1
Last active March 13, 2024 19:04
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 12 You must be signed in to fork a gist
  • Save mark05e/745afaf5604487b804ede2cdc38a977f to your computer and use it in GitHub Desktop.
Save mark05e/745afaf5604487b804ede2cdc38a977f to your computer and use it in GitHub Desktop.
Simple script to clear temp files and browser cache/history
#------------------------------------------------------------------#
#- Clear-GlobalWindowsCache #
#------------------------------------------------------------------#
Function Clear-GlobalWindowsCache {
Remove-CacheFiles 'C:\Windows\Temp'
Remove-CacheFiles "C:\`$Recycle.Bin"
Remove-CacheFiles "C:\Windows\Prefetch"
C:\Windows\System32\rundll32.exe InetCpl.cpl, ClearMyTracksByProcess 255
C:\Windows\System32\rundll32.exe InetCpl.cpl, ClearMyTracksByProcess 4351
}
#------------------------------------------------------------------#
#- Clear-UserCacheFiles #
#------------------------------------------------------------------#
Function Clear-UserCacheFiles {
# Stop-BrowserSessions
ForEach($localUser in (Get-ChildItem 'C:\users').Name)
{
Clear-ChromeCache $localUser
Clear-EdgeCacheFiles $localUser
Clear-FirefoxCacheFiles $localUser
Clear-WindowsUserCacheFiles $localUser
Clear-TeamsCacheFiles $localUser
}
}
#------------------------------------------------------------------#
#- Clear-WindowsUserCacheFiles #
#------------------------------------------------------------------#
Function Clear-WindowsUserCacheFiles {
param([string]$user=$env:USERNAME)
Remove-CacheFiles "C:\Users\$user\AppData\Local\Temp"
Remove-CacheFiles "C:\Users\$user\AppData\Local\Microsoft\Windows\WER"
Remove-CacheFiles "C:\Users\$user\AppData\Local\Microsoft\Windows\INetCache"
Remove-CacheFiles "C:\Users\$user\AppData\Local\Microsoft\Windows\INetCookies"
Remove-CacheFiles "C:\Users\$user\AppData\Local\Microsoft\Windows\IECompatCache"
Remove-CacheFiles "C:\Users\$user\AppData\Local\Microsoft\Windows\IECompatUaCache"
Remove-CacheFiles "C:\Users\$user\AppData\Local\Microsoft\Windows\IEDownloadHistory"
Remove-CacheFiles "C:\Users\$user\AppData\Local\Microsoft\Windows\Temporary Internet Files"
}
#Region HelperFunctions
#------------------------------------------------------------------#
#- Stop-BrowserSessions #
#------------------------------------------------------------------#
Function Stop-BrowserSessions {
$activeBrowsers = Get-Process Firefox*,Chrome*,Waterfox*,Edge*
ForEach($browserProcess in $activeBrowsers)
{
try
{
$browserProcess.CloseMainWindow() | Out-Null
} catch { }
}
}
#------------------------------------------------------------------#
#- Get-StorageSize #
#------------------------------------------------------------------#
Function Get-StorageSize {
Get-WmiObject Win32_LogicalDisk |
Where-Object { $_.DriveType -eq "3" } |
Select-Object SystemName,
@{ Name = "Drive" ; Expression = { ( $_.DeviceID ) } },
@{ Name = "Size (GB)" ; Expression = {"{0:N1}" -f ( $_.Size / 1gb)}},
@{ Name = "FreeSpace (GB)" ; Expression = {"{0:N1}" -f ( $_.Freespace / 1gb ) } },
@{ Name = "PercentFree" ; Expression = {"{0:P1}" -f ( $_.FreeSpace / $_.Size ) } } |
Format-Table -AutoSize | Out-String
}
#------------------------------------------------------------------#
#- Remove-CacheFiles #
#------------------------------------------------------------------#
Function Remove-CacheFiles {
param([Parameter(Mandatory=$true)][string]$path)
BEGIN
{
$originalVerbosePreference = $VerbosePreference
$VerbosePreference = 'Continue'
}
PROCESS
{
if((Test-Path $path))
{
if([System.IO.Directory]::Exists($path))
{
try
{
if($path[-1] -eq '\')
{
[int]$pathSubString = $path.ToCharArray().Count - 1
$sanitizedPath = $path.SubString(0, $pathSubString)
Remove-Item -Path "$sanitizedPath\*" -Recurse -Force -ErrorAction SilentlyContinue -Verbose
}
else
{
Remove-Item -Path "$path\*" -Recurse -Force -ErrorAction SilentlyContinue -Verbose
}
} catch { }
}
else
{
try
{
Remove-Item -Path $path -Force -ErrorAction SilentlyContinue -Verbose
} catch { }
}
}
}
END
{
$VerbosePreference = $originalVerbosePreference
}
}
#Endregion HelperFunctions
#Region Browsers
#Region ChromiumBrowsers
#------------------------------------------------------------------#
#- Clear-ChromeCache #
#------------------------------------------------------------------#
Function Clear-ChromeCache {
param([string]$user=$env:USERNAME)
if((Test-Path "C:\users\$user\AppData\Local\Google\Chrome\User Data\Default"))
{
$chromeAppData = "C:\Users\$user\AppData\Local\Google\Chrome\User Data\Default"
$possibleCachePaths = @('Cache','Cache2\entries\','Cookies','History','Top Sites','VisitedLinks','Web Data','Media Cache','Cookies-Journal','ChromeDWriteFontCache')
ForEach($cachePath in $possibleCachePaths)
{
Remove-CacheFiles "$chromeAppData\$cachePath"
}
}
}
#------------------------------------------------------------------#
#- Clear-EdgeCache #
#------------------------------------------------------------------#
Function Clear-EdgeCache {
param([string]$user=$env:USERNAME)
if((Test-Path "C:\Users$user\AppData\Local\Microsoft\Edge\User Data\Default"))
{
$EdgeAppData = "C:\Users$user\AppData\Local\Microsoft\Edge\User Data\Default"
$possibleCachePaths = @('Cache','Cache2\entries','Cookies','History','Top Sites','Visited Links','Web Data','Media History','Cookies-Journal')
ForEach($cachePath in $possibleCachePaths)
{
Remove-CacheFiles "$EdgeAppData$cachePath"
}
}
}
#Endregion ChromiumBrowsers
#Region FirefoxBrowsers
#------------------------------------------------------------------#
#- Clear-FirefoxCacheFiles #
#------------------------------------------------------------------#
Function Clear-FirefoxCacheFiles {
param([string]$user=$env:USERNAME)
if((Test-Path "C:\users\$user\AppData\Local\Mozilla\Firefox\Profiles"))
{
$possibleCachePaths = @('cache','cache2\entries','thumbnails','cookies.sqlite','webappsstore.sqlite','chromeappstore.sqlite')
$firefoxAppDataPath = (Get-ChildItem "C:\users\$user\AppData\Local\Mozilla\Firefox\Profiles" | Where-Object { $_.Name -match 'Default' }[0]).FullName
ForEach($cachePath in $possibleCachePaths)
{
Remove-CacheFiles "$firefoxAppDataPath\$cachePath"
}
}
}
#------------------------------------------------------------------#
#- Clear-WaterfoxCacheFiles #
#------------------------------------------------------------------#
Function Clear-WaterfoxCacheFiles {
param([string]$user=$env:USERNAME)
if((Test-Path "C:\users\$user\AppData\Local\Waterfox\Profiles"))
{
$possibleCachePaths = @('cache','cache2\entries','thumbnails','cookies.sqlite','webappsstore.sqlite','chromeappstore.sqlite')
$waterfoxAppDataPath = (Get-ChildItem "C:\users\$user\AppData\Local\Waterfox\Profiles" | Where-Object { $_.Name -match 'Default' }[0]).FullName
ForEach($cachePath in $possibleCachePaths)
{
Remove-CacheFiles "$waterfoxAppDataPath\$cachePath"
}
}
}
#Endregion FirefoxBrowsers
#Endregion Browsers
#Region CommunicationPlatforms
#------------------------------------------------------------------#
#- Clear-TeamsCacheFiles #
#------------------------------------------------------------------#
Function Clear-TeamsCacheFiles {
param([string]$user=$env:USERNAME)
if((Test-Path "C:\users\$user\AppData\Roaming\Microsoft\Teams"))
{
$possibleCachePaths = @('cache','blob_storage','databases','gpucache','Indexeddb','Local Storage','application cache\cache')
$teamsAppDataPath = (Get-ChildItem "C:\users\$user\AppData\Roaming\Microsoft\Teams" | Where-Object { $_.Name -match 'Default' }[0]).FullName
ForEach($cachePath in $possibleCachePaths)
{
Remove-CacheFiles "$teamsAppDataPath\$cachePath"
}
}
}
#Endregion CommunicationPlatforms
#------------------------------------------------------------------#
#- MAIN #
#------------------------------------------------------------------#
$StartTime = (Get-Date)
Get-StorageSize
Clear-UserCacheFiles
Clear-GlobalWindowsCache
Get-StorageSize
$EndTime = (Get-Date)
Write-Verbose "Elapsed Time: $(($StartTime - $EndTime).totalseconds) seconds"
@jdthird
Copy link

jdthird commented Aug 10, 2021

Just wanted to leave a note to say thank you for this. I've had multiple scripts I've used over the years on terminal servers, but the ones I had used for the last couple years was no longer getting anything out of the firefox cache2\entries folder for some reason and nothing I could tweak seemed to help with it. Neither PS nor simple CMD files would actually delete the files. No errors, just didn't clear them out anymore. So I tried this one and it worked well.

Thanks!

@mark05e
Copy link
Author

mark05e commented Aug 10, 2021

Thank you for letting me know. I also have a crude version that I use sometimes - mark05e/quick-purge-cache.ps1

@inode64
Copy link

inode64 commented Aug 11, 2021

I make a new repository https://github.com/inode64/WindowsClearCache from your version

Changes:

  • Prepare for the split in two scripts (Cache / Cookies and History), to run separately
  • Fix name of function Clear-EdgeCacheFiles
  • Include more folders for clear in chrome and Windows
  • Include support for Thunderbird, Adobe acrobat, iTunes and Libreoffice
  • Fix a problem that files are never deleted in InetCache

@inode64
Copy link

inode64 commented Aug 11, 2021

I had not seen your last post

@mark05e
Copy link
Author

mark05e commented Aug 11, 2021

@inode64 - all good. thank you for letting me know.

@LreyesFN
Copy link

LreyesFN commented Apr 4, 2023

Hello new to PowerShell and I'm trying to clear just the Chrome and Edge Cache. what would I need to modify just so I could clear those two. Thank you very much?

@mark05e
Copy link
Author

mark05e commented Apr 4, 2023

Comment line 224 Clear-GlobalWindowsCache
Comment lines 19-23 based on what you do not need

        Clear-ChromeCache $localUser
        Clear-EdgeCacheFiles $localUser
        Clear-FirefoxCacheFiles $localUser
        Clear-WindowsUserCacheFiles $localUser
        Clear-TeamsCacheFiles $localUser

@LreyesFN
Copy link

LreyesFN commented Apr 4, 2023

@mark05e If I just wanted
Clear-ChromeCache $localUser
Clear-EdgeCacheFiles $localUser
Clear-FirefoxCacheFiles $localUser
leave everything as is and just remove teams and windowsusers on comment line 19-23

@secnnet
Copy link

secnnet commented Jun 15, 2023

I have an improved version. I made the following changes:

  • I added a script description at the beginning for better documentation.
  • Updated the Remove-CacheFiles function to include proper error handling and error messages.
  • Added additional cache paths to clear in the Clear-GlobalWindowsCache function.
  • Improved error handling and error messages in case the cache folders or files don't exist.
  • Modified the Stop-BrowserSessions function to work with multiple browser names.
  • Enhanced the Get-StorageSize function to display drive information in a more readable format.
  • I updated the comments throughout the script for better clarity.

These improvements aim to enhance the functionality, maintainability, and readability of the script. However, it's essential to thoroughly test the modified script in your specific environment to ensure it meets your requirements and functions as expected. 😊

<# 
    Script: Cache-Cleanup.ps1
    Description: A script to clear cache files for Windows and popular browsers.
#>

# Function to remove cache files
Function Remove-CacheFiles {
    param([Parameter(Mandatory=$true)][string]$path)
    
    try {
        if (Test-Path $path) {
            if (Get-Item -Path $path -ErrorAction SilentlyContinue) {
                # Clearing a directory
                Remove-Item -Path "$path\*" -Recurse -Force -ErrorAction SilentlyContinue
            } else {
                # Clearing a file
                Remove-Item -Path $path -Force -ErrorAction SilentlyContinue
            }
        }
    } catch {
        Write-Error "An error occurred while removing cache files from $path: $_"
    }
}

# Function to clear global Windows cache
Function Clear-GlobalWindowsCache {
    Remove-CacheFiles 'C:\Windows\Temp' 
    Remove-CacheFiles 'C:\$Recycle.Bin'
    Remove-CacheFiles 'C:\Windows\Prefetch'
    Remove-CacheFiles 'C:\Windows\Temp\*' # Additional cache path
    # Additional cache paths can be added here
}

# Function to clear cache files for each user
Function Clear-UserCacheFiles {
    # Stop-BrowserSessions
    $userFolders = Get-ChildItem 'C:\users' -Directory

    foreach ($userFolder in $userFolders) {
        $localUser = $userFolder.Name
        Clear-ChromeCache -User $localUser
        Clear-EdgeCache -User $localUser
        Clear-FirefoxCacheFiles -User $localUser
        Clear-WindowsUserCacheFiles -User $localUser
        Clear-TeamsCacheFiles -User $localUser
    }
}

# Function to clear cache files for a specific Windows user
Function Clear-WindowsUserCacheFiles {
    param([string]$user = $env:USERNAME)
    $cachePaths = @(
        "C:\Users\$user\AppData\Local\Temp",
        "C:\Users\$user\AppData\Local\Microsoft\Windows\WER",
        "C:\Users\$user\AppData\Local\Microsoft\Windows\INetCache",
        "C:\Users\$user\AppData\Local\Microsoft\Windows\INetCookies",
        "C:\Users\$user\AppData\Local\Microsoft\Windows\IECompatCache",
        "C:\Users\$user\AppData\Local\Microsoft\Windows\IECompatUaCache",
        "C:\Users\$user\AppData\Local\Microsoft\Windows\IEDownloadHistory",
        "C:\Users\$user\AppData\Local\Microsoft\Windows\Temporary Internet Files"
    )

    foreach ($cachePath in $cachePaths) {
        Remove-CacheFiles $cachePath
    }
}

# Function to stop browser sessions
Function Stop-BrowserSessions {
    $browsers = @('Firefox', 'Chrome', 'Waterfox', 'Edge')

    foreach ($browser in $browsers) {
        $processes = Get-Process -Name "$browser*" -ErrorAction SilentlyContinue

        foreach ($process in $processes) {
            try {
                $process.CloseMainWindow() | Out-Null 
            } catch { }
        }
    }
}

# Function to get storage size
Function Get-StorageSize {
    $drives = Get-WmiObject Win32_LogicalDisk | Where-Object { $_.DriveType -eq 3 }

    foreach ($drive in $drives) {
        $driveInfo = @{
            SystemName = $drive.SystemName
            Drive = $drive.DeviceID
            'Size (GB)' = "{0:N1}" -f ($drive.Size / 1GB)
            'FreeSpace (GB)' = "{0:N1}" -f ($drive.FreeSpace / 1GB)
            'PercentFree' = "{0:P1}" -f ($drive.FreeSpace / $drive.Size)
        }
        New-Object PSObject -Property $driveInfo
    }
}

# Function to clear Chrome cache
Function Clear-ChromeCache {
    param([string]$user = $env:USERNAME)
    $chromeCachePath = "C:\Users\$user\AppData\Local\Google\Chrome\User Data\Default"
    $chromeCachePaths = @(
        'Cache',
        'Cache2\entries',
        'Cookies',
        'History',
        'Top Sites',
        'VisitedLinks',
        'Web Data',
        'Media Cache',
        'Cookies-Journal',
        'ChromeDWriteFontCache'
    )

    foreach ($path in $chromeCachePaths) {
        Remove-CacheFiles "$chromeCachePath\$path"
    }
}

# Function to clear Microsoft Edge cache
Function Clear-EdgeCache {
    param([string]$user = $env:USERNAME)
    $edgeCachePath = "C:\Users\$user\AppData\Local\Microsoft\Edge\User Data\Default"
    $edgeCachePaths = @(
        'Cache',
        'Cache2\entries',
        'Cookies',
        'History',
        'Top Sites',
        'Visited Links',
        'Web Data',
        'Media History',
        'Cookies-Journal'
    )

    foreach ($path in $edgeCachePaths) {
        Remove-CacheFiles "$edgeCachePath\$path"
    }
}

# Function to clear Firefox cache files
Function Clear-FirefoxCacheFiles {
    param([string]$user = $env:USERNAME)
    $firefoxProfilesPath = "C:\users\$user\AppData\Local\Mozilla\Firefox\Profiles"
    $firefoxProfile = Get-ChildItem $firefoxProfilesPath | Where-Object { $_.Name -match 'Default' } | Select-Object -First 1 -ErrorAction SilentlyContinue

    if ($firefoxProfile) {
        $firefoxCachePaths = @(
            'cache',
            'cache2\entries',
            'thumbnails',
            'cookies.sqlite',
            'webappsstore.sqlite',
            'chromeappstore.sqlite'
        )

        $firefoxAppDataPath = $firefoxProfile.FullName

        foreach ($path in $firefoxCachePaths) {
            Remove-CacheFiles "$firefoxAppDataPath\$path"
        }
    }
}

# Function to clear Microsoft Teams cache files
Function Clear-TeamsCacheFiles {
    param([string]$user = $env:USERNAME)
    $teamsCachePath = "C:\users\$user\AppData\Roaming\Microsoft\Teams"
    $teamsCachePaths = @(
        'cache',
        'blob_storage',
        'databases',
        'gpucache',
        'Indexeddb',
        'Local Storage',
        'application cache\cache'
    )

    foreach ($path in $teamsCachePaths) {
        Remove-CacheFiles "$teamsCachePath\$path"
    }
}

# Main script execution
$StartTime = Get-Date

Get-StorageSize

Clear-UserCacheFiles
Clear-GlobalWindowsCache

Get-StorageSize

$EndTime = Get-Date
Write-Host "Elapsed Time: $(($EndTime - $StartTime).TotalSeconds) seconds"

@mark05e
Copy link
Author

mark05e commented Jun 16, 2023

Thank you for sharing @secnnet

@renatopejon
Copy link

Thank you for the codes @mark05e and @secnnet

@KenHetz
Copy link

KenHetz commented Feb 3, 2024

Secnet - I ran the script you posted (Thank you very much by the way) and received the following error:

  • ... e-Error "An error occurred while removing cache files from $path: $_"

Variable reference is not valid. ':' was not followed by a valid variable name character. Consider using ${} to
delimit the name.

  • CategoryInfo : ParserError: (:) [], ParseException
  • FullyQualifiedErrorId : InvalidVariableReferenceWithDrive

Thoughts?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment