-
-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathWMT-GUI.ps1
More file actions
8113 lines (7193 loc) · 415 KB
/
WMT-GUI.ps1
File metadata and controls
8113 lines (7193 loc) · 415 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
<#
Windows Maintenance Tool - GUI Edition
CLI: Lil_Batti (author) with contributions from Chaython
Feature Integration & Updates: Lil_Batti & Chaython
GUI thanks to https://github.com/Chaython
Imported and integrated from Lil_Batti (author) with contributions from Chaython
#>
# ==========================================
# 1. SETUP
# ==========================================
$AppVersion = "5.1"
$ErrorActionPreference = "SilentlyContinue"
[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)
$OutputEncoding = [System.Text.UTF8Encoding]::new($false)
# HIDE CONSOLE (Safe Check)
# This prevents crashes if you run the script twice in the same session
if (-not ([System.Management.Automation.PSTypeName]'Win32Functions.Win32ShowWindow').Type) {
$t = '[DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr handle, int state);'
Add-Type -MemberDefinition $t -Name "Win32ShowWindow" -Namespace Win32Functions
}
try {
$hwnd = ([System.Diagnostics.Process]::GetCurrentProcess() | Get-Process).MainWindowHandle
if ($hwnd -ne [IntPtr]::Zero) {
[Win32Functions.Win32ShowWindow]::ShowWindow($hwnd, 0) | Out-Null
}
} catch {}
# ADMIN CHECK
$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object System.Security.Principal.WindowsPrincipal($identity)
if (-not $principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)) {
Start-Process powershell.exe "-File `"$PSCommandPath`"" -Verb RunAs
exit
}
# ENABLE HIGH-DPI AWARENESS (Safe Check)
if ([Environment]::OSVersion.Version.Major -ge 6) {
if (-not ([System.Management.Automation.PSTypeName]'Win32Dpi').Type) {
$code = @'
[DllImport("user32.dll")]
public static extern bool SetProcessDPIAware();
'@
Add-Type -MemberDefinition $code -Name "Win32Dpi"
}
try { [Win32Dpi]::SetProcessDPIAware() | Out-Null } catch {}
}
Add-Type -AssemblyName PresentationFramework, System.Windows.Forms, System.Drawing, Microsoft.VisualBasic
[System.Windows.Forms.Application]::EnableVisualStyles()
# OPTIMIZATION: Define Token Manipulator globally once (Prevents "Type already exists" errors)
if (-not ([System.Management.Automation.PSTypeName]'Win32.TokenManipulator').Type) {
$tokenCode = @'
using System;
using System.Runtime.InteropServices;
public class Win32 {
public class TokenManipulator {
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
[DllImport("kernel32.dll", ExactSpelling = true)]
internal static extern IntPtr GetCurrentProcess();
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);
[DllImport("advapi32.dll", SetLastError = true)]
internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct TokPriv1Luid { public int Count; public long Luid; public int Attr; }
internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
internal const int TOKEN_QUERY = 0x00000008;
public static bool EnablePrivilege(string privilege) {
try {
IntPtr htok = IntPtr.Zero;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok)) return false;
TokPriv1Luid tp; tp.Count = 1; tp.Attr = SE_PRIVILEGE_ENABLED; tp.Luid = 0;
if (!LookupPrivilegeValue(null, privilege, ref tp.Luid)) return false;
if (!AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero)) return false;
return true;
} catch { return false; }
}
}
}
'@
Add-Type -TypeDefinition $tokenCode
}
# ==========================================
# 2. HELPER FUNCTIONS
# ==========================================
function Get-Ctrl { param($Name) return $window.FindName($Name) }
function Write-GuiLog {
param($Msg)
$lb = Get-Ctrl "LogBox"
if ($lb) {
$lb.AppendText("[$((Get-Date).ToString('HH:mm'))] $Msg`n")
$lb.ScrollToEnd()
}
}
function Invoke-UiCommand {
param(
[scriptblock]$Sb,
$Msg="Processing...",
[object[]]$ArgumentList = @()
)
[System.Windows.Forms.Cursor]::Current = [System.Windows.Forms.Cursors]::WaitCursor
Write-GuiLog $Msg
try {
# Pass arguments to the scriptblock using splatting
$res = & $Sb @ArgumentList | Out-String
if ($res){ Write-GuiLog $res.Trim() }
else { Write-GuiLog "Done." }
} catch {
Write-GuiLog "ERROR: $($_.Exception.Message)"
}
[System.Windows.Forms.Cursor]::Current = [System.Windows.Forms.Cursors]::Default
}
# Centralized data path for exports (in repo folder)
function Get-DataPath {
$root = Split-Path -Parent $PSCommandPath
$dataPath = Join-Path $root "data"
if (-not (Test-Path $dataPath)) {
New-Item -ItemType Directory -Path $dataPath -Force | Out-Null
}
return $dataPath
}
$script:DataDir = Get-DataPath
# Simple modal text viewer (read-only)
function Show-TextDialog {
param(
[string]$Title = "Output",
[string]$Text = ""
)
$f = New-Object System.Windows.Forms.Form
$f.Text = $Title
$f.Size = "800,600"
$f.StartPosition = "CenterScreen"
$f.BackColor = [System.Drawing.Color]::FromArgb(30,30,30)
$f.ForeColor = [System.Drawing.Color]::White
$tb = New-Object System.Windows.Forms.RichTextBox
$tb.Dock = "Fill"
$tb.ReadOnly = $true
$tb.BackColor = [System.Drawing.Color]::FromArgb(20,20,20)
$tb.ForeColor = [System.Drawing.Color]::White
$tb.Font = New-Object System.Drawing.Font("Consolas", 10)
$tb.Text = $Text
$tb.WordWrap = $false
$f.Controls.Add($tb)
$btn = New-Object System.Windows.Forms.Button
$btn.Text = "Close"
$btn.Dock = "Bottom"
$btn.Height = 35
$btn.BackColor = "DimGray"
$btn.ForeColor = "White"
$btn.Add_Click({ $f.Close() })
$f.Controls.Add($btn)
$f.ShowDialog() | Out-Null
}
# --- SETTINGS MANAGER ---
# Initialize cache variable
$script:WmtSettingsCache = $null
function Save-WmtSettings {
param($Settings)
$path = Join-Path (Get-DataPath) "settings.json"
try {
# Update the memory cache immediately
$script:WmtSettingsCache = $Settings
# Convert Hashtable/OrderedDictionary to generic Object for cleaner JSON
$saveObj = [PSCustomObject]@{
TempCleanup = $Settings.TempCleanup
RegistryScan = $Settings.RegistryScan
WingetIgnore = $Settings.WingetIgnore
LoadWinapp2 = [bool]$Settings.LoadWinapp2
EnabledProviders = $Settings.EnabledProviders
Theme = if ($Settings.Theme) { [string]$Settings.Theme } else { "dark" }
WindowState = if ($Settings.WindowState) { [string]$Settings.WindowState } else { "Normal" }
WindowBounds = if ($Settings.WindowBounds) { $Settings.WindowBounds } else { $null }
}
$saveObj | ConvertTo-Json -Depth 5 | Set-Content $path -Force
} catch {
Write-Warning "Failed to save settings: $_"
}
}
function Get-WmtSettings {
# OPTIMIZATION: Return cached settings if available to avoid disk I/O
if ($script:WmtSettingsCache) { return $script:WmtSettingsCache }
$path = Join-Path (Get-DataPath) "settings.json"
# Default Structure
$defaults = @{
TempCleanup = @{}
RegistryScan = @{}
WingetIgnore = @()
LoadWinapp2 = $false
EnabledProviders = @("winget", "msstore", "pip", "npm", "chocolatey")
Theme = "dark"
WindowState = "Normal"
WindowBounds = @{
Top = 0
Left = 0
Width = 1280
Height = 820
}
}
if (Test-Path $path) {
try {
$json = Get-Content $path -Raw | ConvertFrom-Json
if ($json.TempCleanup) {
foreach ($p in $json.TempCleanup.PSObject.Properties) { $defaults.TempCleanup[$p.Name] = $p.Value }
}
if ($json.RegistryScan) {
foreach ($p in $json.RegistryScan.PSObject.Properties) { $defaults.RegistryScan[$p.Name] = $p.Value }
}
if ($json.PSObject.Properties["WingetIgnore"]) {
$raw = $json.WingetIgnore
$clean = New-Object System.Collections.ArrayList
if ($raw) { foreach ($item in $raw) { [void]$clean.Add("$item".Trim()) } }
$defaults.WingetIgnore = $clean.ToArray()
}
if ($json.PSObject.Properties["LoadWinapp2"]) { $defaults.LoadWinapp2 = [bool]$json.LoadWinapp2 }
if ($json.PSObject.Properties["EnabledProviders"]) { $defaults.EnabledProviders = $json.EnabledProviders }
if ($json.PSObject.Properties["Theme"] -and $json.Theme) { $defaults.Theme = [string]$json.Theme }
if ($json.PSObject.Properties["WindowState"] -and $json.WindowState) { $defaults.WindowState = [string]$json.WindowState }
if ($json.PSObject.Properties["WindowBounds"] -and $json.WindowBounds) {
$defaults.WindowBounds = @{
Top = [double]$json.WindowBounds.Top
Left = [double]$json.WindowBounds.Left
Width = [double]$json.WindowBounds.Width
Height = [double]$json.WindowBounds.Height
}
}
} catch {
Write-GuiLog "Error loading settings: $($_.Exception.Message)"
}
}
# Cache the result
$script:WmtSettingsCache = $defaults
return $defaults
}
function Show-DownloadStats {
Invoke-UiCommand {
try {
$repo = "ios12checker/Windows-Maintenance-Tool"
$rel = Invoke-RestMethod -Uri "https://api.github.com/repos/$repo/releases/latest" -UseBasicParsing
if (-not $rel -or -not $rel.assets) { throw "No release data returned." }
$total = ($rel.assets | Measure-Object download_count -Sum).Sum
$lines = @()
$lines += "Release: $($rel.name)"
$lines += "Total downloads: $total"
$lines += ""
foreach ($a in $rel.assets) {
$lines += ("{0} : {1}" -f $a.name, $a.download_count)
}
$msg = $lines -join "`r`n"
Write-Output $msg
[System.Windows.MessageBox]::Show($msg, "Latest Release Downloads", [System.Windows.MessageBoxButton]::OK, [System.Windows.MessageBoxImage]::Information) | Out-Null
} catch {
$err = "Failed to fetch download stats: $($_.Exception.Message)"
Write-Output $err
[System.Windows.MessageBox]::Show($err, "Latest Release Downloads", [System.Windows.MessageBoxButton]::OK, [System.Windows.MessageBoxImage]::Error) | Out-Null
}
} "Fetching latest release download counts..."
}
# --- UPDATE CHECKER ---
function Start-UpdateCheckBackground {
# 1. Access LogBox
$lbStart = Get-Ctrl "LogBox"
if ($lbStart) {
$lbStart.AppendText("`n[UPDATE] Checking for updates...`n")
$lbStart.ScrollToEnd()
}
$localVersionStr = $script:AppVersion
$scriptPathForUpdate = if ($PSCommandPath) { $PSCommandPath } else { $MyInvocation.MyCommand.Path }
$localScriptHash = ""
$localScriptLastWriteUtc = $null
try {
if ($scriptPathForUpdate -and (Test-Path $scriptPathForUpdate)) {
$localScriptHash = (Get-FileHash -Path $scriptPathForUpdate -Algorithm SHA256).Hash
$localScriptLastWriteUtc = (Get-Item -Path $scriptPathForUpdate).LastWriteTimeUtc
}
} catch {}
# 2. Start Background Thread (Runspace)
$script:UpdateRunspace = [PowerShell]::Create().AddScript({
param($CurrentVer)
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$jobRes = @{ Status = "Failed"; RemoteVersion = "0.0"; RemoteHash = ""; RemoteLastModifiedUtc = ""; Content = ""; Error = "" }
try {
$time = Get-Date -Format "yyyyMMddHHmmss"
$url = "https://raw.githubusercontent.com/ios12checker/Windows-Maintenance-Tool/main/WMT-GUI.ps1?t=$time"
# Shorter timeout for UI responsiveness
$req = Invoke-WebRequest -Uri $url -UseBasicParsing -TimeoutSec 10
$content = $req.Content
$jobRes.Content = $content
try {
$lm = $req.Headers["Last-Modified"]
if ($lm) {
$jobRes.RemoteLastModifiedUtc = ([DateTime]::Parse($lm)).ToUniversalTime().ToString("o")
}
} catch {}
$sha = [System.Security.Cryptography.SHA256]::Create()
try {
$bytes = [System.Text.Encoding]::UTF8.GetBytes([string]$content)
$hashBytes = $sha.ComputeHash($bytes)
$jobRes.RemoteHash = ([System.BitConverter]::ToString($hashBytes)).Replace("-", "")
} finally {
$sha.Dispose()
}
if ($content -match '\$AppVersion\s*=\s*"(\d+(\.\d+)+)"') {
$jobRes.RemoteVersion = $matches[1]
$jobRes.Status = "Success"
}
elseif ($content -match "Windows Maintenance Tool.*v(\d+(\.\d+)+)") {
$jobRes.RemoteVersion = $matches[1]
$jobRes.Status = "Success"
} else {
$jobRes.Error = "Version string not found."
}
} catch {
$jobRes.Error = $_.Exception.Message
}
return $jobRes
}).AddArgument($localVersionStr)
$script:UpdateAsyncResult = $script:UpdateRunspace.BeginInvoke()
# 3. Setup Timer
$script:UpdateTimer = New-Object System.Windows.Threading.DispatcherTimer
$script:UpdateTimer.Interval = [TimeSpan]::FromMilliseconds(500)
$script:UpdateTicks = 0
$script:UpdateTimer.Add_Tick({
$lb = Get-Ctrl "LogBox"
$script:UpdateTicks++
# A. Timeout Check (20s)
if ($script:UpdateTicks -gt 40) {
$script:UpdateTimer.Stop()
if ($script:UpdateRunspace) { $script:UpdateRunspace.Dispose() }
if ($lb) { $lb.AppendText("[UPDATE] Error: Request timed out.`n"); $lb.ScrollToEnd() }
return
}
# B. Check Job Status
if ($script:UpdateAsyncResult.IsCompleted) {
$script:UpdateTimer.Stop()
try {
$jobResult = $script:UpdateRunspace.EndInvoke($script:UpdateAsyncResult)
$script:UpdateRunspace.Dispose()
# Retrieve the actual object (EndInvoke returns a collection)
if ($jobResult -is [System.Collections.ObjectModel.Collection[PSObject]]) {
$jobResult = $jobResult[0]
}
if ($jobResult.Status -eq "Success") {
$localVer = [Version]$script:AppVersion
$remoteVer = [Version]$jobResult.RemoteVersion
$remoteSeemsNewer = $true
try {
if ($jobResult.RemoteLastModifiedUtc -and $localScriptLastWriteUtc) {
$remoteLastUtc = [DateTime]::Parse([string]$jobResult.RemoteLastModifiedUtc).ToUniversalTime()
if ($remoteLastUtc -le $localScriptLastWriteUtc) { $remoteSeemsNewer = $false }
}
} catch {}
$isContentPatch = ($remoteVer -eq $localVer -and $localScriptHash -and $jobResult.RemoteHash -and ($localScriptHash -ne $jobResult.RemoteHash) -and $remoteSeemsNewer)
if ($lb) {
$lb.AppendText("[UPDATE] Local: v$localVer | Remote: v$remoteVer`n")
if ($isContentPatch) { $lb.AppendText("[UPDATE] Same version but newer script content detected.`n") }
elseif ($remoteVer -eq $localVer -and $localScriptHash -and $jobResult.RemoteHash -and ($localScriptHash -ne $jobResult.RemoteHash) -and -not $remoteSeemsNewer) {
$lb.AppendText("[UPDATE] Local script appears newer than remote; skipping patch prompt.`n")
}
$lb.ScrollToEnd()
}
if ($remoteVer -gt $localVer -or $isContentPatch) {
if ($lb) {
if ($remoteVer -gt $localVer) { $lb.AppendText(" -> Update Available!`n") }
else { $lb.AppendText(" -> Patch Update Available (same version).`n") }
$lb.ScrollToEnd()
}
# Use Dispatcher to show dialog on UI thread
$window.Dispatcher.Invoke([Action]{
$msg = if ($remoteVer -gt $localVer) {
"A new version is available!`n`nLocal Version: v$localVer`nRemote Version: v$remoteVer`n`nDo you want to update now?"
} else {
"A script patch is available for your current version (v$localVer).`n`nThis updates fixes without changing the version number.`n`nDo you want to update now?"
}
$mbRes = [System.Windows.MessageBox]::Show($msg, "Update Available", [System.Windows.MessageBoxButton]::YesNo, [System.Windows.MessageBoxImage]::Information)
if ($mbRes -eq [System.Windows.MessageBoxResult]::Yes) {
try {
$remoteContent = [string]$jobResult.Content
if ([string]::IsNullOrWhiteSpace($remoteContent) -or $remoteContent.Length -lt 200) {
throw "Downloaded update content was empty or invalid."
}
$scriptPath = if ($scriptPathForUpdate) { $scriptPathForUpdate } else { if ($PSCommandPath) { $PSCommandPath } else { $MyInvocation.MyCommand.Path } }
if ([string]::IsNullOrWhiteSpace($scriptPath) -or -not (Test-Path $scriptPath)) {
throw "Could not resolve script path for self-update."
}
$backupName = "$(Split-Path $scriptPath -Leaf).bak"
$backupPath = Join-Path (Get-DataPath) $backupName
Copy-Item -Path $scriptPath -Destination $backupPath -Force
Set-Content -Path $scriptPath -Value $remoteContent -Encoding UTF8 -Force
[System.Windows.MessageBox]::Show("Update complete! Restarting...", "Updated", [System.Windows.MessageBoxButton]::OK, [System.Windows.MessageBoxImage]::Information) | Out-Null
Start-Process powershell.exe -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File `"$scriptPath`"" -WorkingDirectory (Split-Path -Parent $scriptPath)
$window.Close()
} catch {
$errMsg = "Auto-update failed: $($_.Exception.Message)"
try { Write-GuiLog "[UPDATE] $errMsg" } catch {}
$fallback = [System.Windows.MessageBox]::Show(
"$errMsg`n`nOpen Releases page and update manually?",
"Update Failed",
[System.Windows.MessageBoxButton]::YesNo,
[System.Windows.MessageBoxImage]::Warning
)
if ($fallback -eq [System.Windows.MessageBoxResult]::Yes) {
Start-Process "https://github.com/ios12checker/Windows-Maintenance-Tool/releases"
}
}
}
})
} else {
if ($lb) { $lb.AppendText(" -> System is up to date.`n"); $lb.ScrollToEnd() }
}
} else {
if ($lb) { $lb.AppendText("[UPDATE] Failed: $($jobResult.Error)`n"); $lb.ScrollToEnd() }
}
} catch {
if ($lb) { $lb.AppendText("[UPDATE] Processing Error: $($_.Exception.Message)`n"); $lb.ScrollToEnd() }
}
}
})
$script:UpdateTimer.Start()
}
# --- RESTORED LOGIC ---
function Start-UpdateRepair {
Invoke-UiCommand {
Stop-Service -Name wuauserv, bits, cryptsvc, msiserver -Force -ErrorAction SilentlyContinue
$rnd = Get-Random
if(Test-Path "$env:windir\SoftwareDistribution"){ Rename-Item "$env:windir\SoftwareDistribution" "$env:windir\SoftwareDistribution.bak_$rnd" -ErrorAction SilentlyContinue }
if(Test-Path "$env:windir\System32\catroot2"){ Rename-Item "$env:windir\System32\catroot2" "$env:windir\System32\catroot2.bak_$rnd" -ErrorAction SilentlyContinue }
netsh winsock reset | Out-Null
Start-Service -Name wuauserv, bits, cryptsvc, msiserver -ErrorAction SilentlyContinue
} "Repairing Windows Update..."
}
function Start-NetRepair {
Invoke-UiCommand {
ipconfig /release | Out-Null
ipconfig /renew | Out-Null
ipconfig /flushdns | Out-Null
netsh winsock reset | Out-Null
netsh int ip reset | Out-Null
} "Running Full Network Repair..."
}
function Start-RegClean {
Invoke-UiCommand {
$bkDir = Join-Path (Get-DataPath) "RegistryBackups"
if(!(Test-Path $bkDir)){ New-Item -Path $bkDir -ItemType Directory | Out-Null }
$bkFile = "$bkDir\Backup_$(Get-Date -F 'yyyyMMdd_HHmm').reg"
reg export "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" $bkFile /y | Out-Null
$keys = Get-ChildItem HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall | Where-Object { $_.PSChildName -match 'IE40|IE4Data|DirectDrawEx|DXM_Runtime|SchedulingAgent' }
if ($keys) { foreach ($k in $keys) { Remove-Item $k.PSPath -Recurse -Force; Write-Output "Removed: $($k.PSChildName)" } } else { Write-Output "No obsolete keys found." }
Write-Output "Backup saved to: $bkFile"
} "Cleaning Registry..."
}
function Start-XboxClean {
Invoke-UiCommand {
Write-Output "Stopping Xbox Auth Manager..."
Stop-Service -Name "XblAuthManager" -Force -ErrorAction SilentlyContinue
$allCreds = (cmdkey /list) -split "`r?`n"
$targets = @()
foreach ($line in $allCreds) {
if ($line -match "(?i)^\\s*Target:.*(Xbl.*)$") { $targets += $matches[1] }
}
if ($targets.Count -eq 0) {
Write-Output "No Xbox Live credentials found."
} else {
foreach ($t in $targets) {
Write-Output "Deleting credential: $t"
cmdkey /delete:$t 2>$null
}
Write-Output "Deleted $($targets.Count) credential(s)."
}
Start-Service -Name "XblAuthManager" -ErrorAction SilentlyContinue
} "Cleaning Xbox Credentials..."
}
function Start-GpeditInstall {
# Check for User Confirmation
$msg = "Install Local Group Policy Editor?`n`nThis enables the Group Policy Editor (gpedit.msc) on Windows Home editions by installing the built-in system packages.`n`nContinue?"
$res = [System.Windows.Forms.MessageBox]::Show($msg, "Confirm Install", [System.Windows.Forms.MessageBoxButtons]::YesNo, [System.Windows.Forms.MessageBoxImage]::Question)
if ($res -eq "No") { return }
Invoke-UiCommand {
$packageRoot = Join-Path $env:SystemRoot "servicing\\Packages"
if (-not (Test-Path $packageRoot)) {
throw "Package directory not found: $packageRoot"
}
Write-Output "Searching packages in $packageRoot..."
$clientTools = Get-ChildItem -Path $packageRoot -Filter "Microsoft-Windows-GroupPolicy-ClientTools-Package~*.mum" -ErrorAction SilentlyContinue
$clientExtensions = Get-ChildItem -Path $packageRoot -Filter "Microsoft-Windows-GroupPolicy-ClientExtensions-Package~*.mum" -ErrorAction SilentlyContinue
if (-not $clientTools -or -not $clientExtensions) {
Write-Output "WARNING: Required GroupPolicy packages were not found."
Write-Output "Ensure you are on a compatible Windows 10/11 version."
return
}
$packages = @($clientTools + $clientExtensions) | Sort-Object Name -Unique
foreach ($pkg in $packages) {
Write-Output "Installing: $($pkg.Name)..."
# Using DISM to add package
$proc = Start-Process dism.exe -ArgumentList "/online","/norestart","/add-package:`"$($pkg.FullName)`"" -NoNewWindow -Wait -PassThru
if ($proc.ExitCode -ne 0) {
Write-Output " -> Failed (Exit Code: $($proc.ExitCode))"
}
}
Write-Output "`nInstallation Complete. Try running 'gpedit.msc'. (A reboot may be required)."
} "Installing Group Policy Editor..."
}
# --- NETWORK / DNS HELPERS (from CLI) ---
function Get-ActiveAdapters {
Get-NetAdapter | Where-Object { $_.Status -eq 'Up' -and $_.InterfaceDescription -notlike '*Virtual*' -and $_.Name -notlike '*vEthernet*' }
}
function Set-DnsAddresses {
param(
[string[]]$Addresses,
[string]$Label = "Custom DNS"
)
if (-not $Addresses -or $Addresses.Count -eq 0) { return }
$addrList = $Addresses
$labelText = $Label
Invoke-UiCommand {
param($addrList, $labelText)
$adapters = Get-ActiveAdapters | Select-Object -ExpandProperty Name
if (-not $adapters) { Write-Output "No active adapters found."; return }
foreach ($adapter in $adapters) {
try {
Set-DnsClientServerAddress -InterfaceAlias $adapter -ServerAddresses $addrList -ErrorAction Stop
Write-Output "[$labelText] Applied to $adapter : $($addrList -join ', ')"
} catch {
Write-Output "[$labelText] Failed on $adapter : $($_.Exception.Message)"
}
}
} "Applying $labelText..." -ArgumentList (,$addrList), $labelText
}
# --- SHARED DNS CONFIGURATION ---
$script:DohTargets = @(
@{ Server = "1.1.1.1"; Template = "https://cloudflare-dns.com/dns-query" }
@{ Server = "1.0.0.1"; Template = "https://cloudflare-dns.com/dns-query" }
@{ Server = "2606:4700:4700::1111"; Template = "https://cloudflare-dns.com/dns-query" }
@{ Server = "2606:4700:4700::1001"; Template = "https://cloudflare-dns.com/dns-query" }
@{ Server = "8.8.8.8"; Template = "https://dns.google/dns-query" }
@{ Server = "8.8.4.4"; Template = "https://dns.google/dns-query" }
@{ Server = "2001:4860:4860::8888"; Template = "https://dns.google/dns-query" }
@{ Server = "2001:4860:4860::8844"; Template = "https://dns.google/dns-query" }
@{ Server = "9.9.9.9"; Template = "https://dns.quad9.net/dns-query" }
@{ Server = "149.112.112.112"; Template = "https://dns.quad9.net/dns-query" }
@{ Server = "2620:fe::fe"; Template = "https://dns.quad9.net/dns-query" }
@{ Server = "2620:fe::fe:9"; Template = "https://dns.quad9.net/dns-query" }
@{ Server = "94.140.14.14"; Template = "https://dns.adguard.com/dns-query" }
@{ Server = "94.140.15.15"; Template = "https://dns.adguard.com/dns-query" }
@{ Server = "2a10:50c0::ad1:ff"; Template = "https://dns.adguard.com/dns-query" }
@{ Server = "2a10:50c0::ad2:ff"; Template = "https://dns.adguard.com/dns-query" }
)
function Start-DohJob {
param($List, $IsEnable)
# 1. UI Feedback
# Attempt to find buttons. If not found, variables will be null.
$btnEnable = Get-Ctrl "btnDohAuto"
$btnDisable = Get-Ctrl "btnDohDisable"
# Safely disable if found
if ($btnEnable) { $btnEnable.IsEnabled = $false }
if ($btnDisable) { $btnDisable.IsEnabled = $false }
$actionStr = if ($IsEnable) { "Enabling" } else { "Disabling" }
Write-GuiLog "$actionStr DoH... (Batch Processing)"
# 2. Start Background Job
$script:DohJob = Start-Job -ScriptBlock {
param($List, $IsEnable)
# Create a temp file for the batch commands
$tmpFile = [System.IO.Path]::GetTempFileName()
$cnt = 0
# Build the batch file content
$lines = @()
foreach ($dns in $List) {
if ($IsEnable) {
$lines += "dns add encryption server=$($dns.Server) dohtemplate=$($dns.Template) autoupgrade=yes udpfallback=no"
} else {
$lines += "dns delete encryption server=$($dns.Server)"
}
$cnt++
}
# Write to file
$lines | Set-Content -Path $tmpFile -Encoding Ascii
# Run netsh in batch mode (-f)
$p = Start-Process -FilePath "netsh.exe" -ArgumentList "-f", $tmpFile -NoNewWindow -PassThru -Wait
# Cleanup
if (Test-Path $tmpFile) { Remove-Item $tmpFile }
# Helper tasks
ipconfig /flushdns | Out-Null
if ($IsEnable) {
try { Restart-Service Dnscache -Force -ErrorAction SilentlyContinue } catch {}
}
# Return the result object
if ($p.ExitCode -eq 0) {
Write-Output ([PSCustomObject]@{ Count = $cnt; Success = $true })
} else {
Write-Output ([PSCustomObject]@{ Count = 0; Success = $false })
}
} -ArgumentList $List, $IsEnable
# 3. Monitor Job
if ($script:DohTimer) { $script:DohTimer.Stop() }
$script:DohTimer = New-Object System.Windows.Threading.DispatcherTimer
$script:DohTimer.Interval = [TimeSpan]::FromMilliseconds(500)
$script:DohTimer.Add_Tick({
if ($script:DohJob.State -ne 'Running') {
$script:DohTimer.Stop()
# Re-fetch buttons in this scope to be safe
$btnEnable = Get-Ctrl "btnDohAuto"
$btnDisable = Get-Ctrl "btnDohDisable"
try {
$rawResults = Receive-Job -Job $script:DohJob
$res = $rawResults | Where-Object { $_ -is [PSCustomObject] -and $_.Psobject.Properties.Match('Count') } | Select-Object -Last 1
if ($res -and $res.Success) {
$c = $res.Count
$finMsg = if ($IsEnable) { "Successfully applied $c DoH rules." } else { "Successfully removed $c DoH rules." }
Write-GuiLog "Done. $finMsg"
if ($c -gt 0) {
# FIXED: Use [System.Windows.MessageBox] (WPF) to match the Enum types
[System.Windows.MessageBox]::Show($finMsg, "DoH Manager", [System.Windows.MessageBoxButton]::OK, [System.Windows.MessageBoxImage]::Information) | Out-Null
}
} else {
Write-GuiLog "Operation failed or no changes were made."
}
} catch {
Write-GuiLog "Job Error: $($_.Exception.Message)"
}
# Cleanup
Remove-Job -Job $script:DohJob
$script:DohJob = $null
# Unlock Buttons (Safe Check)
if ($btnEnable) { $btnEnable.IsEnabled = $true }
if ($btnDisable) { $btnDisable.IsEnabled = $true }
}
})
$script:DohTimer.Start()
}
# Redirect existing function calls to the new Async handler
function Enable-AllDoh { Start-DohJob -List $script:DohTargets -IsEnable $true }
function Disable-AllDoh { Start-DohJob -List $script:DohTargets -IsEnable $false }
# --- Hosts Adblock ---
function Invoke-HostsUpdate {
Invoke-UiCommand {
# 1. Find PATHS
$hostsPath = "$env:windir\System32\drivers\etc\hosts"
$backupDir = Join-Path (Get-DataPath) "hosts_backups"
if (-not (Test-Path $backupDir)) { New-Item -ItemType Directory -Path $backupDir -Force | Out-Null }
# Capture original ACL to preserve permissions (e.g., Users read access)
$origAcl = $null
if (Test-Path $hostsPath) {
try { $origAcl = Get-Acl -Path $hostsPath } catch {}
}
# 2. DOWNLOAD HOSTS FILE
$mirrors = @(
"https://o0.pages.dev/Lite/hosts.win",
"https://raw.githubusercontent.com/badmojr/1Hosts/master/Lite/hosts.win"
)
$adBlockContent = $null
foreach ($mirror in $mirrors) {
try {
$wc = New-Object System.Net.WebClient
# CRITICAL SPEED FIX: Bypasses auto-proxy detection delay (saves 1-5s)
$wc.Proxy = $null
$wc.Encoding = [System.Text.Encoding]::UTF8
Write-GuiLog "Downloading from $mirror..."
$tempContent = $wc.DownloadString($mirror)
# SAFETY CHECK: Ensure file is valid (> 1KB)
if ($tempContent.Length -gt 1024) {
$adBlockContent = $tempContent
Write-Output "Download complete ($([math]::Round($adBlockContent.Length / 1KB, 2)) KB)"
break
}
} catch {
Write-Output "Mirror failed: $mirror"
} finally {
if ($wc) {$wc.Dispose()}
}
}
if (-not $adBlockContent) {
Write-GuiLog "ERROR: Download failed or file was empty. Aborting."
return
}
# 3. BACKUP EXISTING
if (Test-Path $hostsPath) {
$bkName = "hosts_$(Get-Date -F yyyyMMdd_HHmmss).bak"
Copy-Item $hostsPath (Join-Path $backupDir $bkName) -Force
Write-Output "Backup created: $bkName"
}
# 4. PRESERVE CUSTOM ENTRIES
$customStart = "# === BEGIN USER CUSTOM ENTRIES ==="
$customEnd = "# === END USER CUSTOM ENTRIES ==="
$userEntries = "$customStart`r`n# Add custom entries here`r`n127.0.0.1 localhost`r`n::1 localhost`r`n$customEnd"
if (Test-Path $hostsPath) {
try {
$raw = Get-Content $hostsPath -Raw
if ($raw -match "(?s)$([regex]::Escape($customStart))(.*?)$([regex]::Escape($customEnd))") {
$userEntries = $matches[0]
}
} catch {}
}
# 5. CONSTRUCT & WRITE
$finalContent = "$userEntries`r`n`r`n# UPDATED: $(Get-Date)`r`n$adBlockContent"
try {
Set-Content -Path $hostsPath -Value $finalContent -Encoding UTF8 -Force
# Re-apply original ACL or ensure Users has read access
try {
if ($origAcl) {
Set-Acl -Path $hostsPath -AclObject $origAcl
Write-Output "Restored original permissions on hosts file."
} else {
$fs = Get-Acl -Path $hostsPath
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("Users","ReadAndExecute","Allow")
$fs.SetAccessRule($rule)
Set-Acl -Path $hostsPath -AclObject $fs
Write-Output "Applied Users read permission to hosts file."
}
} catch {
Write-Output "Warning: Could not reapply permissions: $($_.Exception.Message)"
}
# Validation
if ((Get-Item $hostsPath).Length -lt 100) { throw "Write verification failed (File empty)." }
ipconfig /flushdns | Out-Null
Write-Output "Hosts file updated successfully."
} catch {
Write-GuiLog "CRITICAL ERROR: $($_.Exception.Message)"
# Restore backup if write failed
$latestBackup = Get-ChildItem $backupDir | Sort-Object CreationTime -Descending | Select-Object -First 1
if ($latestBackup) {
Copy-Item $latestBackup.FullName $hostsPath -Force
Write-GuiLog "Restored backup due to failure."
}
}
} "Updating hosts file..."
}
# --- HOSTS EDITOR ---
function Show-HostsEditor {
# 1. SETUP FORM
$hForm = New-Object System.Windows.Forms.Form
$hForm.Text = "Hosts File Editor"
$hForm.Size = "900, 700"
$hForm.StartPosition = "CenterScreen"
$hForm.BackColor = [System.Drawing.Color]::FromArgb(30,30,30)
$hForm.KeyPreview = $true
# Initialize Dirty Flag (False)
$hForm.Tag = $false
# 2. CONTROLS
$txtHosts = New-Object System.Windows.Forms.RichTextBox
$txtHosts.Dock = "Fill"
$txtHosts.BackColor = [System.Drawing.Color]::FromArgb(45,45,48)
$txtHosts.ForeColor = "White"
$txtHosts.Font = "Consolas, 11"
$txtHosts.AcceptsTab = $true
$txtHosts.DetectUrls = $false
$hForm.Controls.Add($txtHosts)
$pnl = New-Object System.Windows.Forms.Panel
$pnl.Dock = "Bottom"
$pnl.Height = 50
$hForm.Controls.Add($pnl)
$btn = New-Object System.Windows.Forms.Button
$btn.Text = "Save"
$btn.BackColor = "SeaGreen"
$btn.ForeColor = "White"
$btn.FlatStyle = "Flat"
$btn.Top = 10
$btn.Left = 20
$btn.Width = 100
$pnl.Controls.Add($btn)
$lblInfo = New-Object System.Windows.Forms.Label
$lblInfo.Text = "Ctrl+S to Save"
$lblInfo.ForeColor = "Gray"
$lblInfo.AutoSize = $true
$lblInfo.Top = 15
$lblInfo.Left = 140
$pnl.Controls.Add($lblInfo)
$hostsPath = "$env:windir\System32\drivers\etc\hosts"
# 3. LOAD FILE
if (Test-Path $hostsPath) {
$diskSize = (Get-Item $hostsPath).Length
$content = Get-Content $hostsPath -Raw -ErrorAction SilentlyContinue
# Safety Check
if ($diskSize -gt 0 -and [string]::IsNullOrWhiteSpace($content)) {
[System.Windows.Forms.MessageBox]::Show("Could not read Hosts file. Aborting.", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error)
return
}
$txtHosts.Text = $content
}
# 4. HIGHLIGHTING HELPER
$Highlight = {
$sel = $txtHosts.SelectionStart
$len = $txtHosts.SelectionLength
$txtHosts.SelectAll()
$txtHosts.SelectionColor = "White"
$s = $txtHosts.Text.IndexOf("# === BEGIN USER CUSTOM ENTRIES ===")
$e = $txtHosts.Text.IndexOf("# === END USER CUSTOM ENTRIES ===")
if ($s -ge 0 -and $e -gt $s) {
$txtHosts.Select($s, ($e + 33) - $s)
$txtHosts.SelectionColor = "Cyan"
}
$txtHosts.Select($sel, $len)
}
& $Highlight
# 5. CHANGE TRACKING
$txtHosts.Add_TextChanged({
$hForm.Tag = $true
if ($hForm.Text -notmatch "\*$") {
$hForm.Text = "Hosts File Editor *"
}
})
# 6. SAVE LOGIC (Modified to use local variables)
$SaveAction = {
param($FormObj, $TextBox, $FilePath, $HighlightScript)
try {
if ([string]::IsNullOrWhiteSpace($TextBox.Text)) {
$check = [System.Windows.Forms.MessageBox]::Show(
"Save EMPTY file?",
"Warning",
[System.Windows.Forms.MessageBoxButtons]::YesNo,
[System.Windows.Forms.MessageBoxIcon]::Warning
)
if ($check -eq "No") { return $false }
}
Set-Content -Path $FilePath -Value $TextBox.Text -Encoding UTF8 -Force
Start-Process icacls.exe -ArgumentList "`"$FilePath`" /reset" -NoNewWindow -Wait -ErrorAction SilentlyContinue
if ((Get-Item $FilePath).Length -eq 0 -and $TextBox.Text.Length -gt 0) {
throw "Write failed (0 bytes)."
}
# Reset State
if ($FormObj) {
$FormObj.Tag = $false
$FormObj.Text = "Hosts File Editor"
}
[System.Windows.Forms.MessageBox]::Show("Saved successfully!", "Success", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information)
# Re-apply highlighting
& $HighlightScript
return $true
} catch {
[System.Windows.Forms.MessageBox]::Show("Error saving: $_", "Error", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error)
return $false
}
}
# 7. EVENTS
$btn.Add_Click({
$null = & $SaveAction -FormObj $hForm -TextBox $txtHosts -FilePath $hostsPath -HighlightScript $Highlight
})
$hForm.Add_KeyDown({
param($src, $e)
if ($e.Control -and $e.KeyCode -eq 'S') {
$e.SuppressKeyPress = $true
$null = & $SaveAction -FormObj $src -TextBox $txtHosts -FilePath $hostsPath -HighlightScript $Highlight
}
})
# 8. CLOSE PROMPT (FIXED - Pass all required parameters)
$hForm.Add_FormClosing({
param($src, $e)
if ($src.Tag -eq $true) {
$res = [System.Windows.Forms.MessageBox]::Show(
"You have unsaved changes. Save now?",
"Confirm",
[System.Windows.Forms.MessageBoxButtons]::YesNoCancel,
[System.Windows.Forms.MessageBoxIcon]::Warning
)
if ($res -eq "Yes") {
# Pass all required parameters to SaveAction
$success = & $SaveAction -FormObj $src -TextBox $txtHosts -FilePath $hostsPath -HighlightScript $Highlight
if (-not $success) {
$e.Cancel = $true
}
} elseif ($res -eq "Cancel") {
$e.Cancel = $true
}
# If "No", just close without saving
}
})
$hForm.ShowDialog()
}
# --- STORAGE / SYSTEM ---
function Invoke-ChkdskAll {
$confirm = [System.Windows.MessageBox]::Show("Run CHKDSK /f /r on all file-system drives in a live console window?`n`nThis can take a long time. System drive repairs may be scheduled for next reboot.", "Confirm CHKDSK", [System.Windows.MessageBoxButton]::YesNo, [System.Windows.MessageBoxImage]::Warning)
if ($confirm -ne "Yes") { return }