-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathc盘清理助手.ps1
More file actions
454 lines (396 loc) · 16.2 KB
/
Copy pathc盘清理助手.ps1
File metadata and controls
454 lines (396 loc) · 16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
param(
[switch]$Execute,
[int]$MinimumAgeDays = 3,
[switch]$IncludeBrowserCaches,
[switch]$IncludeDevCaches,
[switch]$IncludeTencentCaches,
[switch]$IncludeLarkCaches,
[switch]$IncludeWpsCaches,
[switch]$SkipCoreCaches,
[switch]$IncludeVirtualMemoryReport,
[switch]$OnlyExtraTargets,
[string[]]$ExtraCachePath = @(),
[string]$ReportPath = ""
)
$ErrorActionPreference = "Continue"
$script:CleanerBackendMarker = "CDriveCacheHelperBackend"
function Format-Size {
param([double]$Bytes)
if ($Bytes -ge 1GB) { return ("{0:N2} GB" -f ($Bytes / 1GB)) }
if ($Bytes -ge 1MB) { return ("{0:N2} MB" -f ($Bytes / 1MB)) }
if ($Bytes -ge 1KB) { return ("{0:N2} KB" -f ($Bytes / 1KB)) }
return ("{0:N0} B" -f $Bytes)
}
function Get-FolderBytes {
param([string]$Path)
if (-not (Test-Path -LiteralPath $Path)) { return 0 }
$measure = Get-ChildItem -LiteralPath $Path -Recurse -Force -File -ErrorAction SilentlyContinue |
Measure-Object -Property Length -Sum
if ($null -eq $measure.Sum) { return 0 }
return [double]$measure.Sum
}
function Test-ProtectedPath {
param([string]$Path)
try {
$full = [System.IO.Path]::GetFullPath($Path).TrimEnd('\')
} catch {
return $true
}
$protectedRoots = @(
"C:\Program Files",
"C:\Program Files (x86)",
"C:\Windows\WinSxS",
"C:\Windows\System32\DriverStore",
"C:\Windows\Installer",
"$env:USERPROFILE\Desktop",
"$env:USERPROFILE\Documents",
"$env:USERPROFILE\Downloads",
"$env:USERPROFILE\Pictures",
"$env:USERPROFILE\Videos",
"$env:USERPROFILE\.codex"
)
$protectedPatterns = @(
"\\WeChat Files(\\|$)",
"\\FileStorage(\\|$)",
"\\FileRecv(\\|$)",
"\\Msg(\\|$)",
"\\Message(\\|$)",
"\\Database(\\|$)",
"\\DB(\\|$)",
"\\Image(\\|$)",
"\\Images(\\|$)",
"\\Video(\\|$)",
"\\Videos(\\|$)",
"\\Audio(\\|$)",
"\\Voice(\\|$)",
"\\Attachment(\\|$)",
"\\Documents(\\|$)",
"\\Download(\\|$)"
)
if (-not $full.StartsWith("C:\", [System.StringComparison]::OrdinalIgnoreCase)) {
return $true
}
foreach ($root in $protectedRoots) {
if (-not $root) { continue }
try {
$p = [System.IO.Path]::GetFullPath($root).TrimEnd('\')
if ($full.Equals($p, [System.StringComparison]::OrdinalIgnoreCase)) { return $true }
if ($full.StartsWith($p + "\", [System.StringComparison]::OrdinalIgnoreCase)) { return $true }
} catch {
}
}
foreach ($pattern in $protectedPatterns) {
if ($full -match $pattern) { return $true }
}
return $false
}
function New-Target {
param(
[string]$Name,
[string]$Path,
[string]$Reason,
[string]$Group
)
[PSCustomObject]@{
Name = $Name
Path = $Path
Reason = $Reason
Group = $Group
}
}
function Add-ExistingTarget {
param(
[System.Collections.ArrayList]$List,
[string]$Name,
[string]$Path,
[string]$Reason,
[string]$Group
)
if ([string]::IsNullOrWhiteSpace($Path)) { return }
if (Test-Path -LiteralPath $Path) {
[void]$List.Add((New-Target $Name $Path $Reason $Group))
}
}
function Find-CacheDirectories {
param(
[string[]]$Roots,
[string]$Group,
[string]$Reason
)
$safeNames = @(
"cache",
"code cache",
"gpucache",
"dawncache",
"shadercache"
)
$found = New-Object System.Collections.ArrayList
foreach ($root in $Roots) {
if (-not (Test-Path -LiteralPath $root)) { continue }
$dirs = Get-ChildItem -LiteralPath $root -Recurse -Force -Directory -ErrorAction SilentlyContinue |
Where-Object {
$leaf = $_.Name.ToLowerInvariant()
$safeNames -contains $leaf -and -not (Test-ProtectedPath $_.FullName)
}
foreach ($dir in $dirs) {
[void]$found.Add((New-Target $dir.Name $dir.FullName $Reason $Group))
}
}
return $found
}
function Clear-CacheTarget {
param(
[string]$Path,
[datetime]$Cutoff
)
$removedBytes = 0
$removedFiles = 0
$failed = 0
if (-not (Test-Path -LiteralPath $Path)) {
return [PSCustomObject]@{ RemovedBytes = 0; RemovedFiles = 0; Failed = 0 }
}
$files = Get-ChildItem -LiteralPath $Path -Recurse -Force -File -ErrorAction SilentlyContinue |
Where-Object { $_.LastWriteTime -lt $Cutoff }
foreach ($file in $files) {
try {
$length = [double]$file.Length
Remove-Item -LiteralPath $file.FullName -Force -ErrorAction Stop
$removedBytes += $length
$removedFiles += 1
} catch {
$failed += 1
}
}
$dirs = Get-ChildItem -LiteralPath $Path -Recurse -Force -Directory -ErrorAction SilentlyContinue |
Sort-Object FullName -Descending
foreach ($dir in $dirs) {
try {
$hasChildren = Get-ChildItem -LiteralPath $dir.FullName -Force -ErrorAction SilentlyContinue | Select-Object -First 1
if ($null -eq $hasChildren) {
Remove-Item -LiteralPath $dir.FullName -Force -ErrorAction Stop
}
} catch {
}
}
return [PSCustomObject]@{
RemovedBytes = $removedBytes
RemovedFiles = $removedFiles
Failed = $failed
}
}
function Show-VirtualMemoryReport {
Write-Host ""
Write-Host "Virtual memory report (report only; no settings are changed)"
$files = @("C:\pagefile.sys", "C:\swapfile.sys", "C:\hiberfil.sys")
foreach ($file in $files) {
if (Test-Path -LiteralPath $file) {
$item = Get-Item -LiteralPath $file -Force -ErrorAction SilentlyContinue
if ($null -ne $item) {
Write-Host ("- {0}: {1}" -f $file, (Format-Size $item.Length))
}
} else {
Write-Host ("- {0}: not found or not visible" -f $file)
}
}
try {
$pagefiles = Get-CimInstance Win32_PageFileUsage -ErrorAction Stop
foreach ($pf in $pagefiles) {
Write-Host ("- Pagefile {0}: allocated {1} MB, current usage {2} MB, peak {3} MB" -f $pf.Name, $pf.AllocatedBaseSize, $pf.CurrentUsage, $pf.PeakUsage)
}
} catch {
Write-Host "- Pagefile WMI data unavailable."
}
}
function Get-DefaultReportPath {
param([bool]$IsExecuteMode)
$reportDir = Join-Path $PSScriptRoot "reports"
New-Item -ItemType Directory -Force -Path $reportDir | Out-Null
$kind = if ($IsExecuteMode) { "clean" } else { "scan" }
$stamp = Get-Date -Format "yyyyMMdd-HHmmss"
return (Join-Path $reportDir ("{0}-{1}.txt" -f $kind, $stamp))
}
function Save-RunReport {
param(
[object[]]$Rows,
[string]$Path,
[string]$Mode,
[int]$MinimumAgeDays,
[datetime]$Cutoff,
[double]$TotalScannable,
[double]$TotalRemoved,
[int]$TotalFailed,
[bool]$IncludeVirtualMemoryReport
)
try {
$parent = Split-Path -Parent $Path
if (-not [string]::IsNullOrWhiteSpace($parent)) {
New-Item -ItemType Directory -Force -Path $parent | Out-Null
}
$lines = @()
$lines += "C drive cache helper report"
$lines += ("Created: {0}" -f (Get-Date))
$lines += ("Mode: {0}" -f $Mode)
$lines += ("Minimum age: {0} day(s)" -f $MinimumAgeDays)
$lines += ("Cutoff: {0}" -f $Cutoff)
$lines += ""
$lines += "Safety boundary:"
$lines += "- Cache only."
$lines += "- No software uninstall."
$lines += "- No Program Files, Windows component folders, user documents, projects, chat records, received files, or Codex memory."
$lines += "- Virtual memory is report-only."
$lines += ""
$lines += "Targets:"
$lines += (($Rows | Sort-Object Group, Name, Path | Format-Table -AutoSize | Out-String).TrimEnd())
$lines += ""
$lines += ("Scannable cache total: {0}" -f (Format-Size $TotalScannable))
if ($Mode -eq "EXECUTE") {
$lines += ("Removed: {0}" -f (Format-Size $TotalRemoved))
$lines += ("Failed file removals, usually locked files: {0}" -f $TotalFailed)
} else {
$lines += "No files were deleted."
}
if ($IncludeVirtualMemoryReport) {
$lines += "Virtual memory: shown in console output only; no settings changed."
}
Set-Content -LiteralPath $Path -Value $lines -Encoding UTF8
return $true
} catch {
Write-Host ("Report save failed: {0}" -f $_.Exception.Message)
return $false
}
}
$targets = New-Object System.Collections.ArrayList
if (-not $OnlyExtraTargets) {
if (-not $SkipCoreCaches) {
Add-ExistingTarget $targets "User temp" "$env:LOCALAPPDATA\Temp" "User temporary cache" "Core"
Add-ExistingTarget $targets "Windows temp" "C:\Windows\Temp" "Windows temporary cache" "Core"
Add-ExistingTarget $targets "Crash dumps" "$env:LOCALAPPDATA\CrashDumps" "Application crash dump cache" "Core"
Add-ExistingTarget $targets "D3D shader cache" "$env:LOCALAPPDATA\D3DSCache" "DirectX shader cache" "Core"
Add-ExistingTarget $targets "NVIDIA DX cache" "$env:LOCALAPPDATA\NVIDIA\DXCache" "NVIDIA DirectX cache" "Core"
Add-ExistingTarget $targets "NVIDIA GL cache" "$env:LOCALAPPDATA\NVIDIA\GLCache" "NVIDIA OpenGL cache" "Core"
Add-ExistingTarget $targets "NVIDIA downloader" "$env:PROGRAMDATA\NVIDIA Corporation\Downloader" "NVIDIA driver download cache" "Core"
Add-ExistingTarget $targets "NVIDIA package cache" "$env:PROGRAMDATA\NVIDIA Corporation\NetService" "NVIDIA network service cache" "Core"
}
if ($IncludeTencentCaches) {
$tencentTargets = Find-CacheDirectories -Roots @("$env:APPDATA\Tencent", "$env:LOCALAPPDATA\Tencent") -Group "Tencent" -Reason "Conservative Tencent cache directory; chat records and received files are excluded"
foreach ($target in $tencentTargets) { [void]$targets.Add($target) }
}
if ($IncludeLarkCaches) {
$larkTargets = Find-CacheDirectories -Roots @("$env:APPDATA\LarkShell", "$env:LOCALAPPDATA\LarkShell", "$env:APPDATA\Feishu", "$env:LOCALAPPDATA\Feishu") -Group "Lark" -Reason "Conservative Lark cache directory; chat records and received files are excluded"
foreach ($target in $larkTargets) { [void]$targets.Add($target) }
}
if ($IncludeWpsCaches) {
Add-ExistingTarget $targets "WPS office cache" "$env:APPDATA\kingsoft\office6\cache" "WPS rebuildable cache" "WPS"
Add-ExistingTarget $targets "WPS PDF temp" "$env:APPDATA\kingsoft\office6\pdf\temp" "WPS PDF temporary files" "WPS"
Add-ExistingTarget $targets "WPS font cache" "$env:APPDATA\kingsoft\office6\docerFonts\fontsdk\cache" "WPS downloadable font cache" "WPS"
$wpsTargets = Find-CacheDirectories -Roots @("$env:APPDATA\kingsoft\wps\addons\data") -Group "WPS" -Reason "WPS rebuildable web cache; addon pool, templates and backups are excluded"
foreach ($target in $wpsTargets) { [void]$targets.Add($target) }
}
if ($IncludeBrowserCaches) {
Add-ExistingTarget $targets "Edge cache" "$env:LOCALAPPDATA\Microsoft\Edge\User Data\Default\Cache" "Edge browser cache" "Browser"
Add-ExistingTarget $targets "Edge code cache" "$env:LOCALAPPDATA\Microsoft\Edge\User Data\Default\Code Cache" "Edge script cache" "Browser"
Add-ExistingTarget $targets "Chrome cache" "$env:LOCALAPPDATA\Google\Chrome\User Data\Default\Cache" "Chrome browser cache" "Browser"
Add-ExistingTarget $targets "Chrome code cache" "$env:LOCALAPPDATA\Google\Chrome\User Data\Default\Code Cache" "Chrome script cache" "Browser"
}
if ($IncludeDevCaches) {
Add-ExistingTarget $targets "VS Code cache" "$env:APPDATA\Code\Cache" "VS Code cache" "Developer"
Add-ExistingTarget $targets "VS Code cached data" "$env:APPDATA\Code\CachedData" "VS Code extension runtime cache" "Developer"
Add-ExistingTarget $targets "VS Code extension installer cache" "$env:APPDATA\Code\CachedExtensionVSIXs" "Downloaded VS Code extension installer packages; installed extensions are kept" "Developer"
Add-ExistingTarget $targets "Cursor cache" "$env:APPDATA\Cursor\Cache" "Cursor cache" "Developer"
Add-ExistingTarget $targets "Cursor cached data" "$env:APPDATA\Cursor\CachedData" "Cursor extension runtime cache" "Developer"
Add-ExistingTarget $targets "npm cache" "$env:LOCALAPPDATA\npm-cache" "npm download cache" "Developer"
}
}
foreach ($extra in $ExtraCachePath) {
Add-ExistingTarget $targets "Extra cache" $extra "User-provided cache path" "Extra"
}
$cutoff = (Get-Date).AddDays(-1 * $MinimumAgeDays)
$mode = if ($Execute) { "EXECUTE" } else { "SCAN ONLY" }
Write-Host "C drive cache helper"
Write-Host "Mode: $mode"
Write-Host "Minimum age: $MinimumAgeDays day(s)"
Write-Host "Cutoff: $cutoff"
Write-Host ""
Write-Host "This script never uninstalls software and never cleans Program Files, user documents, projects, chat records, or Codex memory."
Write-Host "WeChat, QQ, and Lark handling is cache-only; received files and message data are protected."
Write-Host ""
$report = @()
$totalScannable = 0
$totalRemoved = 0
$totalFailed = 0
$seen = @{}
$coveredRoots = New-Object System.Collections.ArrayList
$groupBytes = @{}
foreach ($target in ($targets | Sort-Object @{ Expression = { $_.Path.Length } }, Path)) {
if ([string]::IsNullOrWhiteSpace($target.Path)) { continue }
if (-not (Test-Path -LiteralPath $target.Path)) { continue }
$key = $target.Path.ToLowerInvariant()
if ($seen.ContainsKey($key)) { continue }
$seen[$key] = $true
$covered = $false
foreach ($root in $coveredRoots) {
if ($target.Path.StartsWith($root + "\", [System.StringComparison]::OrdinalIgnoreCase)) {
$covered = $true
break
}
}
if ($covered) { continue }
if (Test-ProtectedPath $target.Path) {
$report += [PSCustomObject]@{
Group = $target.Group
Name = $target.Name
Path = $target.Path
Size = "PROTECTED"
Removed = "-"
Failed = "-"
Reason = "Skipped protected path"
}
continue
}
[void]$coveredRoots.Add($target.Path.TrimEnd('\'))
$before = Get-FolderBytes $target.Path
$totalScannable += $before
if (-not $groupBytes.ContainsKey($target.Group)) { $groupBytes[$target.Group] = 0.0 }
$groupBytes[$target.Group] += $before
$removedText = "-"
$failedText = "-"
if ($Execute) {
$result = Clear-CacheTarget -Path $target.Path -Cutoff $cutoff
$totalRemoved += $result.RemovedBytes
$totalFailed += $result.Failed
$removedText = Format-Size $result.RemovedBytes
$failedText = [string]$result.Failed
}
$report += [PSCustomObject]@{
Group = $target.Group
Name = $target.Name
Path = $target.Path
Size = Format-Size $before
Removed = $removedText
Failed = $failedText
Reason = $target.Reason
}
}
$sortedReport = $report | Sort-Object Group, Name, Path
$sortedReport | Format-Table -AutoSize
Write-Host ""
Write-Host "Selected category totals:"
$groupBytes.GetEnumerator() | Sort-Object Name | ForEach-Object {
Write-Host ("- {0}: {1}" -f $_.Name, (Format-Size $_.Value))
}
Write-Host ("Scannable cache total: {0}" -f (Format-Size $totalScannable))
if ($Execute) {
Write-Host ("Removed: {0}" -f (Format-Size $totalRemoved))
Write-Host ("Failed file removals, usually locked files: {0}" -f $totalFailed)
} else {
Write-Host "No files were deleted. Add -Execute to clean cache files older than the selected age."
}
if ($IncludeVirtualMemoryReport) {
Show-VirtualMemoryReport
}
if ([string]::IsNullOrWhiteSpace($ReportPath)) {
$ReportPath = Get-DefaultReportPath -IsExecuteMode ([bool]$Execute)
}
if (Save-RunReport -Rows $sortedReport -Path $ReportPath -Mode $mode -MinimumAgeDays $MinimumAgeDays -Cutoff $cutoff -TotalScannable $totalScannable -TotalRemoved $totalRemoved -TotalFailed $totalFailed -IncludeVirtualMemoryReport ([bool]$IncludeVirtualMemoryReport)) {
Write-Host ("Report saved: {0}" -f $ReportPath)
}