-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmTTCleaner.ps1
More file actions
2187 lines (1909 loc) · 78.6 KB
/
Copy pathmTTCleaner.ps1
File metadata and controls
2187 lines (1909 loc) · 78.6 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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
.TITLE
mTTCleaner - Browser Cache and Database Cleanup Tool
.SYNOPSIS
Cross-platform browser cache and database cleanup tool for myTech.Today
.DESCRIPTION
mTTCleaner is a comprehensive cross-platform browser maintenance tool that:
- Supports 28 browsers (Chrome, Edge, Firefox, Brave, Opera, Vivaldi, Safari, and more)
- Works on Windows, macOS, and Linux (PowerShell 7+)
- Cleans browser caches to free up disk space
- Compacts SQLite databases to reclaim space
- Removes metrics and telemetry files
- Modern TUI with browser selection (using Spectre.Console)
- Active browser detection via registry/mdfind/which
- Windows Event Log integration for enterprise monitoring
- Creates platform-specific shortcuts (Windows .lnk, macOS symlinks, Linux .desktop)
- Sets up automated monthly maintenance (Task Scheduler/launchd/cron)
- Self-deploys to platform-appropriate locations
- Optional parallel processing for improved performance
.PARAMETER Automated
Run in automated mode (skip user confirmation and browser selection)
.PARAMETER SkipConfirmation
Skip the user confirmation prompt
.PARAMETER NoParallel
Disable parallel processing (use sequential mode)
.PARAMETER Browser
Target specific browser or 'All' for all installed browsers
Supported: Chrome, Edge, Firefox, Brave, Opera, Vivaldi, LibreWolf, Waterfox,
TorBrowser, Chromium, PaleMoon, UngoogledChromium, Midori, Min, OperaGX,
Safari, DuckDuckGo, SRWareIron, Maxthon, SeaMonkey, Slimjet, Falkon, Orion,
Arc, SigmaOS, iCab, Epiphany, Konqueror
.PARAMETER SkipDatabaseCompaction
Skip database compaction operations
.PARAMETER CreateShortcuts
Create desktop and start menu shortcuts (cross-platform)
.PARAMETER CreateScheduledTask
Create monthly scheduled task (cross-platform)
.EXAMPLE
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted
Set the execution policy to allow running scripts (run once before first use)
.EXAMPLE
.\mTTCleaner.ps1
Run interactive cleanup with browser selection menu
.EXAMPLE
.\mTTCleaner.ps1 -Browser Chrome -SkipConfirmation
Clean only Chrome without confirmation
.EXAMPLE
.\mTTCleaner.ps1 -Automated
Run automated cleanup for all detected browsers
.EXAMPLE
.\mTTCleaner.ps1 -CreateShortcuts -CreateScheduledTask
Set up shortcuts and scheduled task for monthly maintenance
.EXAMPLE
.\mTTCleaner.ps1 -NoParallel
Run cleanup in sequential mode (disable parallel processing)
.NOTES
File Name : mTTCleaner.ps1
Author : Kyle C. Rode / myTech.Today
Version : 2.2.1
DateCreated : 2025-01-23
LastModified : 2026-03-18
Copyright : (c) 2025 myTech.Today. All rights reserved.
Requires : PowerShell 7.0 or later for full cross-platform support
Platform : Windows, macOS, Linux
#>
#Requires -Version 7.0
[CmdletBinding(SupportsShouldProcess = $true)]
param(
[Parameter(Mandatory = $false)]
[switch]$Automated,
[Parameter(Mandatory = $false)]
[switch]$SkipConfirmation,
[Parameter(Mandatory = $false)]
[switch]$NoParallel,
[Parameter(Mandatory = $false)]
[ValidateSet('All', 'Chrome', 'Edge', 'Firefox', 'Brave', 'Opera', 'Vivaldi', 'LibreWolf', 'Waterfox', 'TorBrowser', 'Chromium', 'PaleMoon', 'UngoogledChromium', 'Midori', 'Min', 'OperaGX', 'Safari', 'DuckDuckGo', 'SRWareIron', 'Maxthon', 'SeaMonkey', 'Slimjet', 'Falkon', 'Orion', 'Arc', 'SigmaOS', 'iCab', 'Epiphany', 'Konqueror')]
[string]$Browser = 'All',
[Parameter(Mandatory = $false)]
[switch]$SkipDatabaseCompaction,
[Parameter(Mandatory = $false)]
[switch]$CreateShortcuts,
[Parameter(Mandatory = $false)]
[switch]$CreateScheduledTask
)
#region Platform Detection and Configuration
# Detect current platform
$script:CurrentPlatform = if ($IsWindows) { 'Windows' }
elseif ($IsMacOS) { 'macOS' }
elseif ($IsLinux) { 'Linux' }
else { 'Unknown' }
Write-Verbose "Detected platform: $script:CurrentPlatform"
# Platform-specific path resolution
function Get-PlatformPath {
<#
.SYNOPSIS
Resolves platform-specific paths for cross-platform compatibility
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateSet('InstallDir', 'DataRoot', 'ConfigDir', 'LogDir', 'CacheDir', 'TempDir')]
[string]$PathType,
[Parameter(Mandatory = $false)]
[string]$SubPath = ''
)
$basePath = switch ($PathType) {
'InstallDir' {
if ($IsWindows) {
Join-Path $env:LOCALAPPDATA 'myTech.Today\mTTCleaner'
}
elseif ($IsMacOS) {
Join-Path $HOME 'Library/Application Support/myTech.Today/mTTCleaner'
}
elseif ($IsLinux) {
Join-Path $HOME '.local/share/myTech.Today/mTTCleaner'
}
}
'DataRoot' {
if ($IsWindows) {
Join-Path $env:LOCALAPPDATA 'myTech.Today\mTTCleaner'
}
elseif ($IsMacOS) {
Join-Path $HOME 'Library/Preferences/myTech.Today/mTTCleaner'
}
elseif ($IsLinux) {
$xdgConfig = if ($env:XDG_CONFIG_HOME) { $env:XDG_CONFIG_HOME } else { Join-Path $HOME '.config' }
Join-Path $xdgConfig 'myTech.Today/mTTCleaner'
}
}
'ConfigDir' {
Join-Path (Get-PlatformPath -PathType DataRoot) 'config'
}
'LogDir' {
if ($IsWindows) {
Join-Path (Get-PlatformPath -PathType DataRoot) 'logs'
}
elseif ($IsMacOS) {
Join-Path $HOME 'Library/Logs/myTech.Today/mTTCleaner'
}
elseif ($IsLinux) {
Join-Path $HOME '.local/share/myTech.Today/mTTCleaner/logs'
}
}
'CacheDir' {
if ($IsWindows) {
Join-Path $env:LOCALAPPDATA 'myTech.Today\mTTCleaner\cache'
}
elseif ($IsMacOS) {
Join-Path $HOME 'Library/Caches/myTech.Today/mTTCleaner'
}
elseif ($IsLinux) {
$xdgCache = if ($env:XDG_CACHE_HOME) { $env:XDG_CACHE_HOME } else { Join-Path $HOME '.cache' }
Join-Path $xdgCache 'myTech.Today/mTTCleaner'
}
}
'TempDir' {
if ($IsWindows) {
$env:TEMP
}
elseif ($IsMacOS -or $IsLinux) {
'/tmp'
}
}
}
if ($SubPath) {
return Join-Path $basePath $SubPath
}
return $basePath
}
# Check if running with elevated privileges (optional, not required)
function Test-IsElevated {
<#
.SYNOPSIS
Checks if the current session has elevated privileges
#>
[CmdletBinding()]
[OutputType([bool])]
param()
if ($IsWindows) {
$principal = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
elseif ($IsMacOS -or $IsLinux) {
return (id -u) -eq 0
}
return $false
}
$script:IsElevated = Test-IsElevated
if ($script:IsElevated) {
Write-Verbose "Running with elevated privileges"
}
else {
Write-Verbose "Running without elevated privileges (some operations may be limited)"
}
function Install-SQLite3 {
<#
.SYNOPSIS
Automatically downloads and installs SQLite3 tools for Windows
.DESCRIPTION
Downloads the latest SQLite3 precompiled binaries from sqlite.org
and extracts them to the script's install directory
#>
[CmdletBinding()]
[OutputType([string])]
param()
if (-not $IsWindows) {
# On macOS/Linux, SQLite3 should be installed via package manager
return $null
}
# Check if sqlite3.exe already exists in install directory
$sqliteDir = Join-Path $script:InstallPath 'sqlite3'
$sqliteExe = Join-Path $sqliteDir 'sqlite3.exe'
if (Test-Path $sqliteExe) {
Write-Verbose "SQLite3 already installed at: $sqliteExe"
# Add to PATH for current session
if ($env:PATH -notlike "*$sqliteDir*") {
$env:PATH = "$sqliteDir;$env:PATH"
}
return $sqliteExe
}
try {
Write-Log "SQLite3 not found. Downloading and installing..." -Level INFO
# Create sqlite3 directory
if (-not (Test-Path $sqliteDir)) {
New-Item -ItemType Directory -Path $sqliteDir -Force | Out-Null
}
# Download SQLite3 tools (using a stable version URL)
# Note: This URL points to the latest version. Update the version number as needed.
$sqliteUrl = 'https://www.sqlite.org/2024/sqlite-tools-win-x64-3460100.zip'
$zipPath = Join-Path $env:TEMP 'sqlite-tools.zip'
Write-Log "Downloading SQLite3 from: $sqliteUrl" -Level INFO
Invoke-WebRequest -Uri $sqliteUrl -OutFile $zipPath -UseBasicParsing -ErrorAction Stop
# Extract zip file directly to a temp directory
Write-Log "Extracting SQLite3 tools..." -Level INFO
$extractPath = Join-Path $env:TEMP "sqlite-extract-$(Get-Random)"
Expand-Archive -Path $zipPath -DestinationPath $extractPath -Force
# The files are extracted directly to the destination, not in a subdirectory
$sourceSqlite = Join-Path $extractPath 'sqlite3.exe'
if (Test-Path $sourceSqlite) {
# Copy sqlite3.exe to our install directory
Copy-Item -Path $sourceSqlite -Destination $sqliteExe -Force
Write-Log "SQLite3 installed successfully to: $sqliteExe" -Level SUCCESS
# Clean up
Remove-Item -Path $zipPath -Force -ErrorAction SilentlyContinue
Remove-Item -Path $extractPath -Recurse -Force -ErrorAction SilentlyContinue
# Add to PATH for current session
$env:PATH = "$sqliteDir;$env:PATH"
return $sqliteExe
}
else {
Write-Log "Failed to find sqlite3.exe in extracted archive" -Level WARNING
Remove-Item -Path $zipPath -Force -ErrorAction SilentlyContinue
Remove-Item -Path $extractPath -Recurse -Force -ErrorAction SilentlyContinue
return $null
}
}
catch {
Write-Log "Failed to download/install SQLite3: $_" -Level WARNING
Write-Log "You can manually download SQLite3 from: https://www.sqlite.org/download.html" -Level INFO
return $null
}
}
#endregion
# Suppress progress bars to prevent spinner graphics in logs
$script:OriginalProgressPreference = $ProgressPreference
$ProgressPreference = 'SilentlyContinue'
# Script constants
$script:ScriptVersion = '2.2.1' # Auto-configure UTF-8 encoding in PowerShell profile during install
$script:ScriptName = 'mTTCleaner'
$script:InstallPath = Get-PlatformPath -PathType InstallDir
$script:LogPath = Get-PlatformPath -PathType LogDir
$script:IconUrl = 'https://raw.githubusercontent.com/mytech-today-now/scripts/refs/heads/main/mytech.ico'
$script:IconPath = Join-Path $script:InstallPath 'mytech.ico'
# Statistics tracking
$script:Stats = @{
TotalCacheCleared = 0
TotalDatabaseSpaceSaved = 0
TotalMetricsFilesRemoved = 0
BrowsersProcessed = 0
StartTime = Get-Date
}
#region Logging Functions
# Download and integrate myTech.Today logging module
# This provides Windows Event Log integration and enhanced logging features
try {
# Save script constants before downloading logging module (it may overwrite them)
$savedScriptName = $script:ScriptName
$savedScriptVersion = $script:ScriptVersion
$loggingUrl = 'https://raw.githubusercontent.com/mytech-today-now/scripts/refs/heads/main/logging.ps1'
Write-Verbose "Downloading logging module from $loggingUrl"
Invoke-Expression (Invoke-WebRequest -Uri $loggingUrl -UseBasicParsing -ErrorAction Stop).Content
$script:LoggingModuleLoaded = $true
# Restore script constants after downloading logging module
$script:ScriptName = $savedScriptName
$script:ScriptVersion = $savedScriptVersion
}
catch {
Write-Warning "Failed to download logging module: $_"
Write-Warning "Falling back to basic logging"
$script:LoggingModuleLoaded = $false
# Fallback basic logging implementation
$script:LogFile = Join-Path $script:LogPath "$script:ScriptName.log"
function Initialize-Log {
param(
[string]$ScriptName,
[string]$ScriptVersion = "1.0.0"
)
try {
if (-not (Test-Path $script:LogPath)) {
New-Item -ItemType Directory -Path $script:LogPath -Force | Out-Null
}
if (-not (Test-Path $script:LogFile)) {
New-Item -ItemType File -Path $script:LogFile -Force | Out-Null
}
return $script:LogFile
}
catch {
Write-Warning "Failed to initialize logging: $_"
return $null
}
}
function Write-Log {
param(
[Parameter(Mandatory = $true)]
[string]$Message,
[Parameter(Mandatory = $false)]
[ValidateSet('INFO', 'SUCCESS', 'WARNING', 'ERROR')]
[string]$Level = 'INFO',
[Parameter(Mandatory = $false)]
[string]$Solution,
[Parameter(Mandatory = $false)]
[string]$Context,
[Parameter(Mandatory = $false)]
[string]$Component
)
$timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
$logMessage = "[$timestamp] [$Level] $Message"
try {
Add-Content -Path $script:LogFile -Value $logMessage -ErrorAction SilentlyContinue
}
catch {
# Silently continue
}
$color = switch ($Level) {
'SUCCESS' { 'Green' }
'WARNING' { 'Yellow' }
'ERROR' { 'Red' }
default { 'Cyan' }
}
Write-Host $logMessage -ForegroundColor $color
}
function Get-LogPath {
return $script:LogFile
}
}
#endregion
#region TUI Functions
function Initialize-SpectreConsole {
<#
.SYNOPSIS
Initialize Spectre.Console module for TUI
#>
[CmdletBinding()]
param()
try {
# Check if PwshSpectreConsole is available
if (-not (Get-Module -ListAvailable -Name PwshSpectreConsole)) {
Write-Verbose "PwshSpectreConsole module not found, attempting to install..."
# Try to install the module
try {
Install-Module -Name PwshSpectreConsole -Scope CurrentUser -Force -AllowClobber -ErrorAction Stop
Write-Verbose "PwshSpectreConsole module installed successfully"
}
catch {
Write-Warning "Failed to install PwshSpectreConsole module: $_"
Write-Warning "Falling back to basic console output"
return $false
}
}
# Import the module
Import-Module PwshSpectreConsole -ErrorAction Stop
return $true
}
catch {
Write-Warning "Failed to initialize Spectre.Console: $_"
Write-Warning "Falling back to basic console output"
return $false
}
}
function Show-WelcomeBanner {
<#
.SYNOPSIS
Display welcome banner with script information
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $false)]
[bool]$UseSpectre = $false
)
if ($UseSpectre) {
try {
Format-SpectrePanel -Title "mTTCleaner - Browser Cleanup Tool" -Data @(
"Cross-Platform Edition v$script:ScriptVersion"
""
"Platform: $script:CurrentPlatform"
"Elevated: $(if ($script:IsElevated) { 'Yes' } else { 'No' })"
"PowerShell: $($PSVersionTable.PSVersion)"
) -Color Green
}
catch {
# Fallback to basic output
$UseSpectre = $false
}
}
if (-not $UseSpectre) {
Write-Host "`n========================================" -ForegroundColor Cyan
Write-Host " mTTCleaner - Browser Cleanup Tool" -ForegroundColor Cyan
Write-Host " Cross-Platform Edition v$script:ScriptVersion" -ForegroundColor Cyan
Write-Host "========================================`n" -ForegroundColor Cyan
Write-Host "Platform: $script:CurrentPlatform" -ForegroundColor Green
Write-Host "Elevated: $script:IsElevated" -ForegroundColor $(if ($script:IsElevated) { 'Green' } else { 'Yellow' })
Write-Host "PowerShell: $($PSVersionTable.PSVersion)`n" -ForegroundColor Gray
}
}
function Show-BrowserSelection {
<#
.SYNOPSIS
Display browser selection menu
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[hashtable]$BrowserDefinitions,
[Parameter(Mandatory = $false)]
[bool]$UseSpectre = $false
)
# Detect installed browsers
$installedBrowsers = @()
foreach ($browserKey in $BrowserDefinitions.Keys) {
$browser = $BrowserDefinitions[$browserKey]
$isInstalled = Test-BrowserInstalled -BrowserName $browserKey -ProfilePath $browser.ProfileRoot
if ($isInstalled) {
$installedBrowsers += [PSCustomObject]@{
Key = $browserKey
Name = $browser.Name
Type = $browser.Type
Installed = $true
}
}
}
if ($installedBrowsers.Count -eq 0) {
Write-Host "[INFO] No supported browsers detected on this system" -ForegroundColor Yellow
return @()
}
if ($UseSpectre) {
try {
Write-Host "`nDetected Browsers:" -ForegroundColor Cyan
$choices = $installedBrowsers | ForEach-Object { $_.Name }
$selected = Read-SpectreMultiSelection -Title "Select browsers to clean" -Choices $choices -Color Green
# Map selected names back to keys
$selectedKeys = @()
foreach ($selection in $selected) {
$browser = $installedBrowsers | Where-Object { $_.Name -eq $selection }
if ($browser) {
$selectedKeys += $browser.Key
}
}
return $selectedKeys
}
catch {
# Fallback to basic selection
$UseSpectre = $false
}
}
if (-not $UseSpectre) {
Write-Host "`nDetected Browsers:" -ForegroundColor Cyan
for ($i = 0; $i -lt $installedBrowsers.Count; $i++) {
Write-Host " [$($i + 1)] $($installedBrowsers[$i].Name)" -ForegroundColor White
}
Write-Host " [A] All browsers" -ForegroundColor Green
Write-Host " [Q] Quit`n" -ForegroundColor Red
$selection = Read-Host "Enter your choice"
if ($selection -eq 'Q' -or $selection -eq 'q') {
return @()
}
elseif ($selection -eq 'A' -or $selection -eq 'a') {
return $installedBrowsers.Key
}
else {
try {
$index = [int]$selection - 1
if ($index -ge 0 -and $index -lt $installedBrowsers.Count) {
return @($installedBrowsers[$index].Key)
}
}
catch {
Write-Host "[ERROR] Invalid selection" -ForegroundColor Red
return @()
}
}
}
}
function Show-OperationOptions {
<#
.SYNOPSIS
Display operation options menu
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $false)]
[bool]$UseSpectre = $false
)
if ($UseSpectre) {
try {
$options = @('Full Clean (Cache + Database + Metrics)', 'Cache Only', 'Database Vacuum Only', 'Metrics Only')
$selected = Read-SpectreSelection -Title "Select operation type" -Choices $options -Color Cyan
$result = switch ($selected) {
'Full Clean (Cache + Database + Metrics)' { 'Full' }
'Cache Only' { 'Cache' }
'Database Vacuum Only' { 'Database' }
'Metrics Only' { 'Metrics' }
default { 'Full' }
}
return $result
}
catch {
$UseSpectre = $false
}
}
if (-not $UseSpectre) {
Write-Host "`nOperation Options:" -ForegroundColor Cyan
Write-Host " [1] Full Clean (Cache + Database + Metrics)" -ForegroundColor Green
Write-Host " [2] Cache Only" -ForegroundColor White
Write-Host " [3] Database Vacuum Only" -ForegroundColor White
Write-Host " [4] Metrics Only`n" -ForegroundColor White
$selection = Read-Host "Enter your choice (default: 1)"
$result = switch ($selection) {
'2' { 'Cache' }
'3' { 'Database' }
'4' { 'Metrics' }
default { 'Full' }
}
return $result
}
}
#endregion
# Initialize logging with enhanced Windows Event Log support
Initialize-Log -ScriptName $script:ScriptName -ScriptVersion $script:ScriptVersion | Out-Null
# Log startup information
Write-Log "$script:ScriptName v$script:ScriptVersion started on $script:CurrentPlatform" -Level INFO
$currentUser = if ($IsWindows) { "$env:USERDOMAIN\$env:USERNAME" } else { $env:USER }
Write-Log "Running as: $currentUser" -Level INFO
Write-Log "Elevated privileges: $script:IsElevated" -Level INFO
Write-Log "Log file: $script:LogFile" -Level INFO
# Check if running from install location
$currentPath = $PSCommandPath
$isInstalled = $currentPath -like "$script:InstallPath*"
if (-not $isInstalled) {
Write-Log "Script not running from install location. Deploying..." -Level INFO
# Create install directory
if (-not (Test-Path $script:InstallPath)) {
New-Item -ItemType Directory -Path $script:InstallPath -Force | Out-Null
Write-Log "Created install directory: $script:InstallPath" -Level INFO
}
# Copy script files
$scriptDir = Split-Path -Parent $PSCommandPath
$filesToCopy = @('mTTCleaner.ps1', 'README.md', 'README.html')
foreach ($file in $filesToCopy) {
$sourcePath = Join-Path $scriptDir $file
$destPath = Join-Path $script:InstallPath $file
if (Test-Path $sourcePath) {
Copy-Item -Path $sourcePath -Destination $destPath -Force
Write-Log "Copied $file to install location" -Level INFO
}
}
# Ensure UTF-8 encoding is configured in PowerShell profile (prevents Spectre Console warning)
$utf8Line = '$OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding = [System.Text.UTF8Encoding]::new()'
$profilePath = $PROFILE.CurrentUserAllHosts
try {
$profileDir = Split-Path -Parent $profilePath
if (-not (Test-Path $profileDir)) {
New-Item -ItemType Directory -Path $profileDir -Force | Out-Null
Write-Log "Created PowerShell profile directory: $profileDir" -Level INFO
}
if (-not (Test-Path $profilePath)) {
# Profile doesn't exist - create it with the UTF-8 line
Set-Content -Path $profilePath -Value $utf8Line -Force
Write-Log "Created PowerShell profile with UTF-8 encoding: $profilePath" -Level INFO
}
else {
$profileContent = Get-Content -Path $profilePath -Raw -ErrorAction SilentlyContinue
if ($profileContent -notmatch 'OutputEncoding.*UTF8Encoding') {
# Prepend the UTF-8 line to existing profile
$newContent = $utf8Line + [Environment]::NewLine + $profileContent
Set-Content -Path $profilePath -Value $newContent -Force
Write-Log "Added UTF-8 encoding to PowerShell profile: $profilePath" -Level INFO
}
else {
Write-Log "UTF-8 encoding already configured in PowerShell profile" -Level INFO
}
}
# Apply UTF-8 encoding to current session so the re-launched script benefits immediately
$OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding = [System.Text.UTF8Encoding]::new()
}
catch {
Write-Log "Could not configure UTF-8 encoding in profile: $_" -Level WARN
}
# Re-launch from install location (only if not in WhatIf mode)
$installedScript = Join-Path $script:InstallPath 'mTTCleaner.ps1'
if ($WhatIfPreference) {
Write-Log "WhatIf mode: Would launch from install location: $installedScript" -Level INFO
exit 0
}
if (Test-Path $installedScript) {
Write-Log "Launching from install location: $installedScript" -Level INFO
$params = $PSBoundParameters
& $installedScript @params
exit $LASTEXITCODE
}
else {
Write-Log "Failed to copy script to install location" -Level ERROR
exit 1
}
}
# Initialize Spectre Console if available
$script:UseSpectre = Initialize-SpectreConsole
# User confirmation check
if (-not $Automated -and -not $SkipConfirmation) {
# Show welcome banner
Show-WelcomeBanner -UseSpectre $script:UseSpectre
Write-Host "This script will:" -ForegroundColor Yellow
Write-Host " - Close all browser processes" -ForegroundColor White
Write-Host " - Delete browser caches" -ForegroundColor White
Write-Host " - Compact browser databases (requires sqlite3)" -ForegroundColor White
Write-Host " - Remove metrics/telemetry files`n" -ForegroundColor White
$confirmation = Read-Host "Type 'Yes' to continue"
if ($confirmation -ne 'Yes') {
Write-Log "User cancelled operation" -Level WARNING
Write-Host "`n[CANCELLED] Operation cancelled by user" -ForegroundColor Yellow
exit 0
}
Write-Log "User confirmed operation" -Level INFO
}
#region Browser Configuration
function Test-BrowserInstalled {
<#
.SYNOPSIS
Detect if a browser is actually installed on the system
.DESCRIPTION
Uses platform-specific detection methods:
- Windows: Registry queries and executable paths
- macOS: Application bundle detection and mdfind
- Linux: which, flatpak, snap, and common binary locations
#>
[CmdletBinding()]
[OutputType([bool])]
param(
[Parameter(Mandatory = $true)]
[string]$BrowserName,
[Parameter(Mandatory = $false)]
[string]$ProfilePath
)
# First check if profile path exists (quick check)
if ($ProfilePath -and (Test-Path $ProfilePath)) {
return $true
}
# Platform-specific detection
if ($IsWindows) {
# Check registry for installed applications
$registryPaths = @(
'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'
'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'
'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'
)
$browserNames = @{
'Chrome' = @('Google Chrome', 'Chrome')
'Edge' = @('Microsoft Edge', 'Edge')
'Firefox' = @('Mozilla Firefox', 'Firefox')
'Brave' = @('Brave', 'Brave Browser')
'Opera' = @('Opera Stable', 'Opera')
'OperaGX' = @('Opera GX', 'OperaGX')
'Vivaldi' = @('Vivaldi')
'Chromium' = @('Chromium')
'LibreWolf' = @('LibreWolf')
'Waterfox' = @('Waterfox')
'TorBrowser' = @('Tor Browser')
'PaleMoon' = @('Pale Moon')
'DuckDuckGo' = @('DuckDuckGo', 'DuckDuckGo Privacy Browser')
'SRWareIron' = @('SRWare Iron', 'Iron')
'Maxthon' = @('Maxthon', 'Maxthon Cloud Browser')
'SeaMonkey' = @('SeaMonkey')
'Slimjet' = @('Slimjet')
'Falkon' = @('Falkon')
'Orion' = @('Orion', 'Orion Browser')
'Arc' = @('Arc', 'Arc Browser')
'SigmaOS' = @('SigmaOS')
'iCab' = @('iCab')
'Epiphany' = @('Epiphany', 'GNOME Web')
'Konqueror' = @('Konqueror')
}
if ($browserNames.ContainsKey($BrowserName)) {
foreach ($regPath in $registryPaths) {
try {
$apps = Get-ItemProperty $regPath -ErrorAction SilentlyContinue
foreach ($app in $apps) {
foreach ($name in $browserNames[$BrowserName]) {
if ($app.DisplayName -like "*$name*") {
return $true
}
}
}
}
catch {
# Continue to next registry path
}
}
}
}
elseif ($IsMacOS) {
# Check /Applications and ~/Applications for .app bundles
$appPaths = @('/Applications', "$HOME/Applications")
$appNames = @{
'Chrome' = 'Google Chrome.app'
'Edge' = 'Microsoft Edge.app'
'Firefox' = 'Firefox.app'
'Brave' = 'Brave Browser.app'
'Opera' = 'Opera.app'
'OperaGX' = 'Opera GX.app'
'Vivaldi' = 'Vivaldi.app'
'Chromium' = 'Chromium.app'
'LibreWolf' = 'LibreWolf.app'
'Waterfox' = 'Waterfox.app'
'TorBrowser' = 'Tor Browser.app'
'Safari' = 'Safari.app'
'DuckDuckGo' = 'DuckDuckGo.app'
'Slimjet' = 'Slimjet.app'
'Orion' = 'Orion.app'
'Arc' = 'Arc.app'
'SigmaOS' = 'SigmaOS.app'
'iCab' = 'iCab.app'
}
if ($appNames.ContainsKey($BrowserName)) {
foreach ($appPath in $appPaths) {
$fullPath = Join-Path $appPath $appNames[$BrowserName]
if (Test-Path $fullPath) {
return $true
}
}
}
}
elseif ($IsLinux) {
# Check using which, flatpak, and snap
$binaryNames = @{
'Chrome' = @('google-chrome', 'google-chrome-stable')
'Edge' = @('microsoft-edge', 'microsoft-edge-stable')
'Firefox' = @('firefox')
'Brave' = @('brave', 'brave-browser')
'Opera' = @('opera')
'Vivaldi' = @('vivaldi')
'Chromium' = @('chromium', 'chromium-browser')
'LibreWolf' = @('librewolf')
'Waterfox' = @('waterfox')
'TorBrowser' = @('tor-browser', 'torbrowser-launcher')
'PaleMoon' = @('palemoon')
'Midori' = @('midori')
'DuckDuckGo' = @('duckduckgo')
'Falkon' = @('falkon')
'SeaMonkey' = @('seamonkey')
'Slimjet' = @('slimjet')
'Epiphany' = @('epiphany', 'epiphany-browser')
'Konqueror' = @('konqueror')
}
if ($binaryNames.ContainsKey($BrowserName)) {
foreach ($binary in $binaryNames[$BrowserName]) {
# Check using which
$whichResult = Get-Command $binary -ErrorAction SilentlyContinue
if ($whichResult) {
return $true
}
# Check flatpak
try {
$flatpakResult = & flatpak list 2>$null | Select-String -Pattern $binary -Quiet
if ($flatpakResult) {
return $true
}
}
catch {
# flatpak not available
}
# Check snap
try {
$snapResult = & snap list 2>$null | Select-String -Pattern $binary -Quiet
if ($snapResult) {
return $true
}
}
catch {
# snap not available
}
}
}
}
return $false
}
function Get-BrowserPath {
<#
.SYNOPSIS
Get platform-specific browser profile paths
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$BrowserName
)
$paths = @{
Windows = @{
Chrome = Join-Path $env:LOCALAPPDATA 'Google\Chrome\User Data'
Edge = Join-Path $env:LOCALAPPDATA 'Microsoft\Edge\User Data'
Firefox = Join-Path $env:APPDATA 'Mozilla\Firefox\Profiles'
Brave = Join-Path $env:LOCALAPPDATA 'BraveSoftware\Brave-Browser\User Data'
Opera = Join-Path $env:APPDATA 'Opera Software\Opera Stable'
OperaGX = Join-Path $env:APPDATA 'Opera Software\Opera GX Stable'
Vivaldi = Join-Path $env:LOCALAPPDATA 'Vivaldi\User Data'
Chromium = Join-Path $env:LOCALAPPDATA 'Chromium\User Data'
UngoogledChromium = Join-Path $env:LOCALAPPDATA 'Chromium\User Data'
LibreWolf = Join-Path $env:APPDATA 'LibreWolf\Profiles'
Waterfox = Join-Path $env:APPDATA 'Waterfox\Profiles'
TorBrowser = Join-Path $env:APPDATA 'Tor Browser\Browser\TorBrowser\Data\Browser'
PaleMoon = Join-Path $env:APPDATA 'Moonchild Productions\Pale Moon\Profiles'
Midori = Join-Path $env:LOCALAPPDATA 'Midori\User Data'
Min = Join-Path $env:APPDATA 'Min\User Data'
DuckDuckGo = Join-Path $env:LOCALAPPDATA 'DuckDuckGo\User Data'
SRWareIron = Join-Path $env:LOCALAPPDATA 'Chromium\User Data'
Maxthon = Join-Path $env:LOCALAPPDATA 'Maxthon\User Data'
SeaMonkey = Join-Path $env:APPDATA 'Mozilla\SeaMonkey\Profiles'
Slimjet = Join-Path $env:LOCALAPPDATA 'Slimjet\User Data'
Falkon = Join-Path $env:LOCALAPPDATA 'falkon\profiles'
}
macOS = @{
Chrome = Join-Path $HOME 'Library/Application Support/Google/Chrome'
Edge = Join-Path $HOME 'Library/Application Support/Microsoft Edge'
Firefox = Join-Path $HOME 'Library/Application Support/Firefox/Profiles'
Brave = Join-Path $HOME 'Library/Application Support/BraveSoftware/Brave-Browser'
Opera = Join-Path $HOME 'Library/Application Support/com.operasoftware.Opera'
OperaGX = Join-Path $HOME 'Library/Application Support/com.operasoftware.OperaGX'
Vivaldi = Join-Path $HOME 'Library/Application Support/Vivaldi'
Chromium = Join-Path $HOME 'Library/Application Support/Chromium'
UngoogledChromium = Join-Path $HOME 'Library/Application Support/Chromium'
LibreWolf = Join-Path $HOME 'Library/Application Support/librewolf/Profiles'
Waterfox = Join-Path $HOME 'Library/Application Support/Waterfox/Profiles'
TorBrowser = Join-Path $HOME 'Library/Application Support/TorBrowser-Data/Browser'
PaleMoon = Join-Path $HOME 'Library/Application Support/Pale Moon/Profiles'
Midori = Join-Path $HOME 'Library/Application Support/Midori'
Min = Join-Path $HOME 'Library/Application Support/Min'
Safari = Join-Path $HOME 'Library/Safari'
DuckDuckGo = Join-Path $HOME 'Library/Application Support/DuckDuckGo'
SRWareIron = Join-Path $HOME 'Library/Application Support/Chromium'
Maxthon = Join-Path $HOME 'Library/Application Support/Maxthon'
SeaMonkey = Join-Path $HOME 'Library/Application Support/SeaMonkey/Profiles'
Slimjet = Join-Path $HOME 'Library/Application Support/Slimjet'
Falkon = Join-Path $HOME 'Library/Application Support/falkon'
Orion = Join-Path $HOME 'Library/Application Support/Orion'
Arc = Join-Path $HOME 'Library/Application Support/Arc'
SigmaOS = Join-Path $HOME 'Library/Application Support/SigmaOS'
iCab = Join-Path $HOME 'Library/Application Support/iCab'
}
Linux = @{
Chrome = Join-Path $HOME '.config/google-chrome'
Edge = Join-Path $HOME '.config/microsoft-edge'