Hi @Nick Eckermann ,
I have provided my detection and remediation script, so you can review it.
#Start Detection Script
Function Config_fn_WriteLog {
param(
[Parameter(Mandatory = $true)][string]$ReportModule = "General",
[Parameter(Mandatory = $true)][string] $LogMessage,
[Parameter(Mandatory = $true)]
[ValidateSet('Debug', 'Info', 'Warning', 'Error')]
[string]$Severity = 'Info'
)
if (!($IsDebugLogRequired) -and ($Severity -eq "Debug")) {
return
}
Try {
#Format Log Message
$FormattedDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$LevelText = ""
switch ($Severity) {
'Error' {
Write-Error $LogMessage
$LevelText = 'ERROR:'
}
'Warning' {
Write-Warning $LogMessage
$LevelText = 'WARNING:'
}
'Info' {
Write-Host $LogMessage
$LevelText = 'INFO:'
}
'Debug' {
Write-Host $LogMessage -ForegroundColor Gray
$LevelText = 'DEBUG:'
}
}
$FormattedMsg = $FormattedDate + " " + $LevelText + " " + $ReportModule + " `t" + $LogMessage
#Check Log File
if (Test-Path "$env:SystemRoot\Logs") {
# Format Log File Name - Generate new file Perday
$FileNameDateFormat = Get-Date -Format "yyyyMMdd"
$LogFileName = "DiskOptimizerDetection_" + $FileNameDateFormat + ".log"
$LogFilePath = "$env:SystemRoot\Logs" + "\" + $LogFileName
if (!(Test-Path $LogFilePath)) {
$NewLogFile = New-Item $LogFilePath -Force -ItemType File
}
#Write to log file
$FormattedMsg | Out-File -FilePath $LogFilePath -Append
}
# Add log message to the RemediationResults array
$RemediationResults += $FormattedMsg
}
Catch {
# Do Nothing
Write-Host "Error while writing Log"
}
}
try {
$ReportModuleName = "Disk Optimizer [Detection]"
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity INFO -LogMessage "Started Executing - ($ReportModuleName)"
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity INFO -LogMessage "Checking C: drive's disk space"
$drive = Get-WmiObject Win32_LogicalDisk | Where-Object { $_.DeviceID -eq "C:" }
if ($drive -eq $null) {
Write-Output "Error: C: drive not found."
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity Error -LogMessage "Error: C: drive not found."
exit 0
}
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity INFO -LogMessage "Calculating space information..."
$sizeGB = "{0:N1}" -f ($drive.Size / 1GB)
$freeSpaceGB = "{0:N1}" -f ($drive.FreeSpace / 1GB)
$percentFree = "{0:P1}" -f ($drive.FreeSpace / $drive.Size)
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity INFO -LogMessage "C: Drive Size: $sizeGB GB"
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity INFO -LogMessage "Free Space: $freeSpaceGB GB"
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity INFO -LogMessage "Free Space Percentage: $percentFree"
$percentFreeValue = [double]::Parse($percentFree.TrimEnd('%')) / 100
if ($percentFreeValue -lt 0.65) {
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity INFO -LogMessage "AvailableSpace:$percentFree"
Write-Output "AvailableSpace:$percentFree"
exit 1
}
else {
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity INFO -LogMessage "AvailableSpace:$percentFree"
Write-Output "AvailableSpace:$percentFree"
exit 0
}
}
catch {
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity Error -LogMessage "Error: $_"
Write-Output "Error: $_"
exit 0
}
#Start Remediation Script
try {
$ReportModuleName = "Disk Optimizer"
$FormattedDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$RemedationResults = @()
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity INFO -LogMessage "Started Executing Script - ($ReportModuleName)"
$RemedationResults += "DateTime:$FormattedDate,RemoteAction:$ReportModuleName,ScriptStatus:Started,Remark:Started Executing Script - ($ReportModuleName)"
# 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
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity INFO -LogMessage "Removing cache files from directory: $path"
Remove-Item -Path "$path\*" -Recurse -Force -Confirm:$false -ErrorAction SilentlyContinue
}
else {
# Clearing a file
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity INFO -LogMessage "Removing cache file: $path"
Remove-Item -Path $path -Recurse -Force -Confirm:$false -ErrorAction SilentlyContinue
}
}
}
catch {
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity INFO -LogMessage "An error occurred while removing cache files from $path : $_"
}
}
# Function to clear global Windows cache
Function Clear-GlobalWindowsCache {
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity INFO -LogMessage "Clearing global Windows cache..."
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 {
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity INFO -LogMessage "Clearing cache files for each user..."
# 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)
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity INFO -LogMessage "Clearing cache files for Windows user: $user"
$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 in GB
Function Get-StorageSize {
$drive = Get-WmiObject Win32_LogicalDisk | Where-Object { $_.DeviceID -eq "C:" }
return [math]::Round(($drive.FreeSpace / 1GB), 2)
}
# Function to clear Chrome cache
Function Clear-ChromeCache {
param([string]$user = $env:USERNAME)
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity INFO -LogMessage "Clearing Chrome cache for user: $user"
$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)
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity INFO -LogMessage "Clearing Microsoft Edge cache for user: $user"
$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)
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity INFO -LogMessage "Clearing Firefox cache files for user: $user"
$firefoxProfilesPath = "C:\users\$user\AppData\Local\Mozilla\Firefox\Profiles"
if (Test-Path $firefoxProfilesPath) {
$firefoxProfile = Get-ChildItem $firefoxProfilesPath | Where-Object { $_.Name -eq '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)
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity INFO -LogMessage "Clearing Microsoft Teams cache files for user: $user"
$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
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity INFO -LogMessage "Script execution started at: $StartTime"
$SizeBefore = Get-StorageSize
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity INFO -LogMessage "Storage size before cleanup: $SizeBefore GB"
Clear-UserCacheFiles
Clear-GlobalWindowsCache
$SizeAfter = Get-StorageSize
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity INFO -LogMessage "Storage size after cleanup: $SizeAfter GB"
$EndTime = Get-Date
$ElapsedTime = ($EndTime - $StartTime).TotalMinutes
#Write-Output "Elapsed Time: $ElapsedTime minutes"
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity INFO -LogMessage "Script execution completed in: $ElapsedTime minutes"
$FreedSpaceInGB = $SizeAfter - $SizeBefore
$FreedSpaceInMB = $FreedSpaceInGB * 1024
if ($FreedSpaceInGB -lt 1) {
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity INFO -LogMessage "FreedSpace:$FreedSpaceInMB MB,SizeBeforeCleanup:$SizeBefore GB,SizeAfterCleanup:$SizeAfter GB"
#Write-Output "FreedSpace:$FreedSpaceInMB MB,SizeBeforeCleanup:$SizeBefore GB,SizeAfterCleanup:$SizeAfter GB"
# Exit with a success code
$RemedationResults += "DateTime:$FormattedDate,RemoteAction:$ReportModuleName,ScriptStatus:InProgress,Remark:FreedSpace-$FreedSpaceInMB MB,SizeBeforeCleanup-$SizeBefore GB,SizeAfterCleanup-$SizeAfter GB"
$RemedationResults += "DateTime:$FormattedDate,RemoteAction:$ReportModuleName,ScriptStatus:Completed,Remark:Successfully Completed Executing Script - ($ReportModuleName)"
Write-Output -InputObject ($RemedationResults -join ';')
#exit 0
}
else {
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity INFO -LogMessage "FreedSpace:$FreedSpaceInGB GB,SizeBeforeCleanup:$SizeBefore GB,SizeAfterCleanup:$SizeAfter GB"
#Write-Output "FreedSpace:$FreedSpaceInGB GB,SizeBeforeCleanup:$SizeBefore GB,SizeAfterCleanup:$SizeAfter GB"
# Exit with a success code
$RemedationResults += "DateTime:$FormattedDate,RemoteAction:$ReportModuleName,ScriptStatus:InProgress,Remark:$FreedSpaceInGB GB,SizeBeforeCleanup-$SizeBefore GB,SizeAfterCleanup-$SizeAfter GB"
$RemedationResults += $RemedationResults += "DateTime:$FormattedDate,RemoteAction:$ReportModuleName,ScriptStatus:Completed,Remark:Successfully Completed Executing Script - ($ReportModuleName)"
Write-Output -InputObject ($RemedationResults -join ';')
#exit 0
}
}
catch {
# Output the error message
Config_fn_WriteLog -ReportModule $ReportModuleName -Severity INFO -LogMessage "An error occurred: $_"
#Write-Output "An error occurred: $_"
$RemedationResults += "DateTime:$FormattedDate,RemoteAction:$ReportModuleName,ScriptStatus:Error,Remark:Error Occured while Executing Script - ($ReportModuleName)"
$RemedationResults += $RemedationResults += "DateTime:$FormattedDate,RemoteAction:$ReportModuleName,ScriptStatus:Error,Remark:Error Occured while Executing Script - ($ReportModuleName)"
Write-Output -InputObject ($RemedationResults -join ';')
# Exit with a failure code
#exit 1
}