-
-
Save mark05e/745afaf5604487b804ede2cdc38a977f to your computer and use it in GitHub Desktop.
#------------------------------------------------------------------# | |
#- 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" |
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?
The fix for the one line eror is;
Write-Error "An error occurred while removing cache files from $($path:: $_)"
This is even cleaner;
<#
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:USERPROFILE)
$cachePaths = @(
"$user\AppData\Local\Temp",
"$user\AppData\Local\Microsoft\Windows\WER",
"$user\AppData\Local\Microsoft\Windows\INetCache",
"$user\AppData\Local\Microsoft\Windows\INetCookies",
"$user\AppData\Local\Microsoft\Windows\IECompatCache",
"$user\AppData\Local\Microsoft\Windows\IECompatUaCache",
"$user\AppData\Local\Microsoft\Windows\IEDownloadHistory",
"$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:USERPROFILE)
$chromeCachePath = "$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:USERPROFILE)
$edgeCachePath = "$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:USERPROFILE)
$firefoxProfilesPath = "$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:USERPROFILE)
$teamsCachePath = "$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"
Bugs:
Clear-EdgeCacheFiles doesn't exist, should be Clear-EdgeCache
Additionally the paths in this function are poorly formed and missing a "\" symbol
"C:\Users$user" should be "C:\Users\$user"
"$EdgeAppData$cachePath" should be "$EdgeAppData\$cachePath"
Thank you for sharing @secnnet