Files
management-scripts/Cleanup-SystemTempFiles.ps1
T

295 lines
14 KiB
PowerShell
Raw Normal View History

2025-08-15 15:48:50 -04:00
. $([Scriptblock]::Create((New-Object Net.WebClient).DownloadString('https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/Tools.ps1')))
2023-09-15 16:47:50 -04:00
2025-01-06 12:35:23 -05:00
# Function to enumerate all user profile folders
Function Get-UserProfiles {
$ProfilePath = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList' -Name ProfilesDirectory).ProfilesDirectory
2025-01-06 12:35:23 -05:00
$UserProfilePaths = @()
ForEach ( $userProfile in (Get-ChildItem -Path $ProfilePath | Where-Object { $_.PSIsContainer }) ) {
$UserProfilePaths += ,@($userProfile.FullName)
}
Return $UserProfilePaths
}
2025-01-06 12:39:06 -05:00
# Function to determine if an app is running
Function IsRunning ([Parameter(ValueFromPipeline=$true)][string]$Name) {
$RunningInstances = Get-Process | Where-Object { $_.Name -ilike $Name }
If ( $RunningInstances ) { Return $true } Else { Return $false }
}
2022-08-18 15:39:28 -04:00
# When deleting temp files en masse, only delete files/folders older than the number of days specified here
$OlderThan = 7
$TimeDelta = New-TimeSpan -Days $OlderThan
2022-11-19 14:37:35 -05:00
# Remove all *.evtx files from system temporary files location
$EventLogs = Get-ChildItem -Path "${Env:SystemRoot}\TEMP\*" -File -Filter *.evtx
If ( $EventLogs ) {
2023-10-05 13:11:38 -04:00
Write-Output "Deleting all event logs from ${Env:SystemRoot}\TEMP"
2022-11-19 14:37:35 -05:00
ForEach ( $EventLog in $EventLogs ) { Remove-Item $EventLog -Force -ErrorAction SilentlyContinue }
}
2020-09-07 20:47:09 -04:00
2022-11-19 14:37:35 -05:00
# Remove misc logs and error reports
$MiscLogs = Get-ChildItem -Path "${Env:SystemRoot}\TEMP\*" -File -Include "${Env:COMPUTERNAME}-*.log", "AppxErrorReport_*.txt"
If ( $MiscLogs ) {
2023-10-05 13:11:38 -04:00
Write-Output "Deleting misc logs from ${Env:SystemRoot}\TEMP"
2022-11-19 14:37:35 -05:00
ForEach ( $MiscLog in $MiscLogs ) { Remove-Item $MiscLog -Force -ErrorAction SilentlyContinue }
}
2020-09-08 22:23:52 -04:00
2022-11-19 14:37:35 -05:00
# Remove archived CBS logs
$CBSLogs = Get-ChildItem -Path "${Env:SystemRoot}\Logs\CBS\*" -File -Include "CbsPersist_*.log", "CbsPersist_*.cab"
If ( $CBSLogs ) {
$TotalBytes = 0
ForEach ( $CBSLog in $CBSLogs) { $TotalBytes += $CBSLog.Length }
$TotalSize = [math]::Round(($TotalBytes / 1MB),2)
If ( $TotalSize -ge 200 ) {
2023-10-05 13:11:38 -04:00
Write-Output "Total CBS log archive size: ${TotalSize}MB"
2022-11-19 14:37:35 -05:00
Control-Service -Stop 'TrustedInstaller'
2023-10-05 13:11:38 -04:00
Write-Output "Deleting primary CBS.log file"
2022-11-19 14:37:35 -05:00
Remove-Item "${Env:SystemRoot}\Logs\CBS\CBS.log" -Force -ErrorAction SilentlyContinue
Control-Service -Start 'TrustedInstaller'
}
2023-10-05 13:11:38 -04:00
Write-Output "Deleting archived CBS logs from ${Env:SystemRoot}\Logs\CBS"
2022-11-19 14:37:35 -05:00
ForEach ( $CBSLog in $CBSLogs ) { Remove-Item $CBSLog -Force -ErrorAction SilentlyContinue }
}
2022-11-19 14:37:35 -05:00
# Remove all system temp files older than 7 days
2023-10-05 13:32:26 -04:00
$OldTempFiles = Get-ChildItem -Path "${Env:SystemRoot}\TEMP" | Where-Object { $_.LastWriteTime -lt ((Get-Date) - $TimeDelta) }
2022-11-19 14:37:35 -05:00
If ( $OldTempFiles ) {
2023-10-05 13:11:38 -04:00
Write-Output "Deleting all temp files not modified in ${OlderThan} day(s) from ${Env:SystemRoot}\TEMP"
ForEach ( $OldTempFile in $OldTempFiles ) { Remove-Item $OldTempFile.FullName -Force -Recurse -ErrorAction SilentlyContinue }
2022-11-19 14:37:35 -05:00
}
# Remove all old files from the Recycle Bin
$UserRecycleBins = Get-ChildItem -Path "${Env:SystemDrive}\`$Recycle.Bin" -Directory -ErrorAction SilentlyContinue
If ( ($UserRecycleBins | Measure-Object).Count -gt 0 ) {
Write-Output "Deleting all recycle bin items older than ${OlderThan} days from:"
ForEach ( $userRecycleBin in $UserRecycleBins ) {
$userRecycleBinFullName = $userRecycleBin.FullName
Write-Output " - $userRecycleBinFullName"
$items = Get-ChildItem -Path $userRecycleBin.FullName -Recurse -ErrorAction SilentlyContinue
ForEach ( $item in $items ) {
If ( $item.LastWriteTime -lt $TimeDelta ) {
Try {
Remove-Item -Path $item.FullName -Force -ErrorAction Continue
$itemFullName = $item.FullName
Write-Output "DELETING: ${itemFullName}"
}
Catch { Write-Error $_.Exception.Message }
}
}
}
2022-11-19 14:37:35 -05:00
}
# Turn off system hibernation if it's in use
If ( Test-Path "${Env:SystemDrive}\hiberfil.sys" ) {
2023-10-05 13:11:38 -04:00
Write-Output "Turning off system hibernation"
2022-11-19 14:37:35 -05:00
Try { Start-Process "powercfg" -ArgumentList "-h off" -Wait }
2023-10-05 13:17:18 -04:00
Catch { Write-Error $_.Exception.Message }
2022-11-19 14:37:35 -05:00
}
# Remove PDCRevocation dump files
$PDCRevocationDumpFiles = Get-ChildItem -Path "${Env:SystemRoot}\LiveKernelReports\*" -File -Include "PDCRevocation-*.dmp"
If ( $PDCRevocationDumpFiles ) {
2023-10-05 13:11:38 -04:00
Write-Output "Deleting PDCRevocation dump files from ${Env:SystemRoot}\LiveKernelReports"
ForEach ( $PDCRevocationDump in $PDCRevocationDumpFiles ) { Remove-Item $PDCRevocationDump.FullName -Force -ErrorAction SilentlyContinue }
2022-11-19 14:37:35 -05:00
}
2020-09-17 15:57:43 -04:00
2022-11-19 14:37:35 -05:00
# Remove Genetec application crash dumps
If ( Test-Path "${Env:ProgramData}\Genetec\Dumps" ) {
$GenetecCrashDumps = Get-ChildItem -Path "${Env:ProgramData}\Genetec\Dumps"
If ( $GenetecCrashDumps )
2020-09-17 15:57:43 -04:00
{
2023-10-05 13:11:38 -04:00
Write-Output "Deleting Genetec application crash dumps"
2022-11-19 14:37:35 -05:00
Try { ForEach ( $dump in $GenetecCrashDumps ) { Remove-Item $dump.FullName -Force -Recurse -ErrorAction SilentlyContinue } }
2023-10-05 13:17:18 -04:00
Catch { Write-Error $_.Exception.Message }
2020-09-17 15:57:43 -04:00
}
2022-11-19 14:37:35 -05:00
}
2020-11-18 16:42:34 -05:00
2022-11-19 14:37:35 -05:00
# Defragment Windows Elastic Search database
$ESDB = "${Env:ProgramData}\Microsoft\Search\Data\Applications\Windows\Windows.edb"
If ( Test-Path $ESDB ) {
Try {
2023-10-05 13:11:38 -04:00
Write-Output "Found Windows Elastic Search database: ""${ESDB}"""
Write-Output " - Disabling Windows Search service"
2022-11-19 14:37:35 -05:00
Start-Process "sc.exe" -ArgumentList "config wsearch start= disabled" -Wait
2023-10-05 13:11:38 -04:00
Write-Output " - Stopping Windows Search Service"
2022-11-19 14:37:35 -05:00
Start-Process "net.exe" -ArgumentList "stop wsearch" -Wait
2023-10-05 13:11:38 -04:00
Write-Output " - Defragmenting database file"
2022-11-19 14:37:35 -05:00
Start-Process "esentutl.exe" -ArgumentList "/d ""${ESDB}""" -Wait
2023-10-05 13:11:38 -04:00
Write-Output " - Enabling Windows Search Service"
2022-11-19 14:37:35 -05:00
Start-Process "sc.exe" -ArgumentList "config wsearch start= delayed-auto" -Wait
2023-10-05 13:11:38 -04:00
Write-Output " - Starting Windows Search Service"
2022-11-19 14:37:35 -05:00
Start-Process "net.exe" -ArgumentList "start wsearch" -Wait
2022-08-18 15:39:28 -04:00
}
2023-10-05 13:17:18 -04:00
Catch { Write-Error $_.Exception.Message }
2022-08-18 15:39:28 -04:00
2022-11-19 14:37:35 -05:00
}
2023-01-16 12:55:48 -05:00
# Remove any Autodesk installers at their default location
$ADSKInst = "${Env:SystemDrive}\Autodesk"
If ( Test-Path $ADSKInst ) {
$foldersToDelete = Get-ChildItem -Path $ADSKInst -ErrorAction SilentlyContinue | Where-Object { ($_.PSIsContainer) -and ($_.LastWriteTime -lt ((Get-Date) - $TimeDelta)) -and ( $_.Name -ne "WI") }
2023-11-09 12:20:20 -05:00
ForEach ( $f in $foldersToDelete ) {
$path = $f.FullName
2023-10-05 13:11:38 -04:00
Write-Output "Deleting Autodesk installer directory: ""${path}"""
Try { Remove-Item $f.FullName -Force -Recurse -ErrorAction SilentlyContinue }
2023-10-05 13:17:18 -04:00
Catch { Write-Error $_.Exception.Message }
2023-01-16 12:55:48 -05:00
}
}
2023-11-09 13:34:09 -05:00
# Delete all but most recent shadow copy of system drive
2023-11-09 12:20:20 -05:00
$SystemVolume = Get-CimInstance -ClassName Win32_Volume -ErrorAction SilentlyContinue | Where-Object { $_.Name -like "${Env:SystemDrive}\" }
$ShadowCopies = Get-CimInstance -ClassName Win32_ShadowCopy -ErrorAction SilentlyContinue | Where-Object { $_.VolumeName -like $SystemVolume.DeviceID }
2024-10-14 12:57:41 -04:00
If ( $ShadowCopies.Count -gt 1 ) {
Write-Output "Deleting all of the oldest shadow copies of ${Env:SystemDrive}"
$ShadowsToDelete = $ShadowCopies.Count - 1
2023-11-09 13:34:09 -05:00
While ( $ShadowsToDelete -gt 0 ) {
vssadmin delete shadows /For=$Env:SystemDrive /Oldest /Quiet
2024-10-14 12:57:41 -04:00
$ShadowsToDelete = $ShadowsToDelete - 1
}
2023-11-09 12:21:21 -05:00
}
2022-11-19 14:37:35 -05:00
2024-07-03 16:37:56 -04:00
# Delete old temp directories from Chocolatey cache
$ChocolateyCache = "${Env:WinDir}\Temp\chocolatey"
$ChocolateyTempDirs = Get-ChildItem -Path $ChocolateyCache -Directory -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -lt ((Get-Date) - $TimeDelta) }
If ( $ChocolateyTempDirs ) {
Write-Output "Deleting all temp directories not modified in ${OlderThan} day(s) from ""${ChocolateyCache}"""
ForEach ( $d in $ChocolateyTempDirs ) {
Try { Remove-Item $d.FullName -Force -Recurse -ErrorAction SilentlyContinue }
2024-07-03 16:37:56 -04:00
Catch { Write-Error $_.Exception.Message }
}
}
2022-11-19 14:37:35 -05:00
# Remove files from user profile directories
2023-10-06 16:14:34 -04:00
ForEach ( $userProfile in $(Get-UserProfiles) ) {
2022-11-19 14:37:35 -05:00
# Remove all user temp files older than 7 days
$OldTempFiles = Get-ChildItem -Path "${userProfile}\AppData\Local\Temp" -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -lt ((Get-Date) - $TimeDelta) }
If ( $OldTempFiles ) {
2023-10-05 13:11:38 -04:00
Write-Output "Deleting all temp files not modified in ${OlderThan} day(s) from ""${userProfile}\AppData\Local\Temp"""
ForEach ( $OldTempFile in $OldTempFiles ) { Remove-Item $OldTempFile.FullName -Force -Recurse -ErrorAction SilentlyContinue }
2020-11-18 16:42:34 -05:00
}
2022-02-03 09:20:45 -05:00
2022-08-18 15:39:28 -04:00
# Remove AutoCAD temp files
2022-02-03 09:20:45 -05:00
If (-not (IsRunning -Name "acad") ) {
2023-01-09 16:01:01 -05:00
$AutoCADTempFiles = Get-ChildItem -Path "${userProfile}\AppData\Local\Temp\*" -File -Include '*.ac$' -ErrorAction SilentlyContinue
2022-02-03 09:20:45 -05:00
If ( $AutoCADTempFiles ) {
2023-10-05 13:11:38 -04:00
Write-Output "Deleting AutoCAD temp files"
2022-11-19 14:37:35 -05:00
ForEach ( $tempfile in $AutoCADTempFiles ) {
Try { Remove-Item $tempfile.FullName -Force -ErrorAction SilentlyContinue }
2023-10-05 13:17:18 -04:00
Catch { Write-Error $_.Exception.Message }
2022-11-19 14:37:35 -05:00
}
2022-02-03 09:20:45 -05:00
}
}
2022-09-08 14:41:54 -04:00
2022-11-19 14:37:35 -05:00
# Apple iTunes data
2022-11-28 14:13:12 -05:00
# If (-not (IsRunning -Name 'itunes') ) {
# # Remove Apple software updates downloaded from iTunes
# $IPSWBasePath = "${userProfile}\AppData\Roaming\Apple Computer\iTunes"
# $IPSW = @()
# # iPhone update files
# ForEach ( $updateFile in $(Get-ChildItem -Path "${IPSWBasePath}\iPhone Software Updates\*" -File -Include '*.ipsw' -ErrorAction SilentlyContinue) ) {
# $IPSW += ,@($updateFile.FullName)
# }
# # iPad update files
# ForEach ( $updateFile in $(Get-ChildItem -Path "${IPSWBasePath}\iPad Software Updates\*" -File -Include '*.ipsw' -ErrorAction SilentlyContinue) ) {
# $IPSW += ,@($updateFile.FullName)
# }
# # iPod update files
# ForEach ( $updateFile in $(Get-ChildItem -Path "${IPSWBasePath}\iPod Software Updates\*" -File -Include '*.ipsw' -ErrorAction SilentlyContinue) ) {
# $IPSW += ,@($updateFile.FullName)
# }
# # Remove Apple mobile applications downloaded from iTunes
# $IPA = @()
# ForEach ( $mobileApp in $(Get-ChildItem -Path "${userProfile}\Music\iTunes\iTunes Media\Mobile Applications\*" -File -Include '*.ipa' -ErrorAction SilentlyContinue) ) {
# $IPA += ,@($updateFile.FullName)
# }
2022-11-19 14:37:35 -05:00
2022-11-28 14:13:12 -05:00
# If ( $IPSW ) {
2023-10-05 13:11:38 -04:00
# Write-Output "Found Apple software update files"
2022-11-28 14:13:12 -05:00
# ForEach ( $path in $IPSW ) {
2023-10-05 13:11:38 -04:00
# Write-Output " - Deleting: ""${path}"""
2022-11-28 14:13:12 -05:00
# Try { Remove-Item -Path $path -Force -ErrorAction SilentlyContinue }
2023-10-05 13:17:18 -04:00
# Catch { Write-Error $_.Exception.Message }
2022-11-28 14:13:12 -05:00
# }
# }
# If ( $IPA ) {
2023-10-05 13:11:38 -04:00
# Write-Output "Found Apple mobile application files"
2022-11-28 14:13:12 -05:00
# ForEach ( $path in $IPA ) {
2023-10-05 13:11:38 -04:00
# Write-Output " - Deleting: ""${path}"""
2022-11-28 14:13:12 -05:00
# Try { Remove-Item -Path $path -Force -ErrorAction SilentlyContinue }
2023-10-05 13:17:18 -04:00
# Catch { Write-Error $_.Exception.Message }
2022-11-28 14:13:12 -05:00
# }
# }
# }
2022-11-19 14:37:35 -05:00
# Remove old downloaded application files
$OldDownloadedApps = (Get-ChildItem -Path "${userProfile}\Downloads\*" -File -Filter '*.exe' -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -lt ((Get-Date) - $TimeDelta) })
If ( $OldDownloadedApps ) {
2023-10-05 13:11:38 -04:00
Write-Output "Deleting old downloaded app files"
2022-11-19 14:37:35 -05:00
ForEach ( $oldDownloadedApp in $OldDownloadedApps ) {
$path = $oldDownloadedApp.FullName
2023-10-05 13:11:38 -04:00
Write-Output " - Deleting: ""${path}"""
Try { Remove-Item -Path $path.FullName -Force -ErrorAction SilentlyContinue }
2023-10-05 13:17:18 -04:00
Catch { Write-Error $_.Exception.Message }
2022-11-19 14:37:35 -05:00
}
}
# Remove duplicate downloads
# Separate the possible duplicates from the rest
$PossibleDuplicates = @()
$NotDuplicates = @()
ForEach ( $file in (Get-ChildItem -Path "${userProfile}\Downloads\*" -File -ErrorAction SilentlyContinue) ) {
If ( $file.BaseName -match '\s\(\d*\)$' ) {
$PossibleDuplicates += ,@($file)
} Else {
$NotDuplicates += ,@($file)
}
}
# Loop through all files
ForEach ( $pd in $PossibleDuplicates ) {
ForEach ( $nd in $NotDuplicates ) {
# Match the first part of $pd to $nd
If ( [regex]::Match($pd.BaseName,'^(.*)(\s\(\d*\))$').Groups[1].Value -eq $nd.BaseName ) {
# Check for equal file size
If ( $(Get-Item -Path $pd.FullName).Length -eq $(Get-Item -Path $nd.FullName).Length ) {
# Make sure the file still exists before writing any log messages
$ToDelete = $pd.FullName
If ( Test-Path $ToDelete ) {
# Delete the duplicate file
2023-10-05 13:11:38 -04:00
Write-Output "Deleting duplicate download: ""${ToDelete}"""
2022-11-19 14:37:35 -05:00
Try { Remove-Item -Path $ToDelete -Force -ErrorAction SilentlyContinue }
2023-10-05 13:17:18 -04:00
Catch { Write-Error $_.Exception.Message }
2022-11-19 14:37:35 -05:00
}
}
}
2022-02-03 09:20:45 -05:00
}
}
2022-09-08 14:41:54 -04:00
2022-11-22 13:20:18 -05:00
# Remove old Outlook backup files
$OldOutlookBackupFiles = Get-ChildItem -Path "${userProfile}\AppData\Local\Microsoft\Outlook\*" -File -Filter '*.bak' -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -lt ((Get-Date) - $TimeDelta) }
If ( $OldOutlookBackupFiles ) {
2023-10-05 13:11:38 -04:00
Write-Output "Found Outlook backup files older than ${OlderThan} days:"
2022-11-22 13:20:18 -05:00
ForEach ( $file in $OldOutlookBackupFiles ) {
$path = $file.FullName
2023-10-05 13:11:38 -04:00
Write-Output "Deleting: ""${path}"""
2022-11-22 13:20:18 -05:00
Try { Remove-Item -Path $path -Force -ErrorAction SilentlyContinue }
2023-10-05 13:17:18 -04:00
Catch { Write-Error $_.Exception.Message }
2022-11-22 13:20:18 -05:00
}
}
2020-09-07 20:47:09 -04:00
}
2022-11-19 14:37:35 -05:00
# Silently run cleanmgr.exe with default settings
# TODO: This does not run silently - commenting out for now!
#Try {
2023-10-05 13:11:38 -04:00
# Write-Output "Running cleanmgr.exe with default settings for very low disk space"
2022-11-19 14:37:35 -05:00
# Start-Process "cleanmgr.exe" -ArgumentList "/VERYLOWDISK"
2023-10-05 13:11:38 -04:00
# Write-Output " - Finished"
2022-11-19 14:37:35 -05:00
#}
2023-10-05 13:17:18 -04:00
#Catch { Write-Error $_.Exception.Message }