-
-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathwor.ps1
More file actions
1965 lines (1632 loc) · 88 KB
/
wor.ps1
File metadata and controls
1965 lines (1632 loc) · 88 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 Optimization Script
# Optimized version with improved structure, error handling, and performance
#Requires -RunAsAdministrator
#Requires -Version 5.1
<#
.SYNOPSIS
Comprehensive Windows system optimization and privacy enhancement script.
.DESCRIPTION
This script modifies Windows settings to optimize performance, enhance privacy,
and improve security. It provides configurable options to customize the changes.
.NOTES
Author: Optimized by Claude AI based on original script
Version: 2.1 (Updated to include DeviceCensus disabling)
Requires: PowerShell 5.1 or higher with Administrator privileges
#>
# Set strict mode and error preferences for better error handling
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
# Force PowerShell to use TLS 1.2 for downloads
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
#region Configuration
# Create a configuration object that can be validated and used throughout the script
$Config = @{
General = @{
# Performance settings
PowerPlan = 'a1841308-3541-4fab-bc81-f71556f20b4a' # Power saver
DisablePrefetcher = $true
DisableMemoryDump = $true
DisableSystemRestore = $true
DisableNtfsEncryption = $true
DisableNtfsCompression = $true
DisableVBS = $true
DisableLastAccess = $true
DoPerformanceStuff = $true
# Power settings (in minutes, 0 = never)
DiskAcTimeout = 0
DiskDcTimeout = 0
MonitorAcTimeout = 10
MonitorDcTimeout = 5
StandbyAcTimeout = 0
StandbyDcTimeout = 25
HibernateAcTimeout = 0
HibernateDcTimeout = 0
# Quality of life improvements
DarkTheme = $true
LegacyRightClicksMenu = $true
DisableWindowsSounds = $true
DisableStartupSound = $true
# Cleanup options
Remove3dObjFolder = $true
UnpinStartMenu = $false
DisablePerformanceMonitor = $true
}
Security = @{
DisableWindowsFirewall = $true
DisableSMBServer = $true
DoSecurityStuff = $true
DoFingerprintPrevention = $true
UseGoogleDNS = $true
}
Privacy = @{
DisableCortana = $true
DisableTelemetry = $true
DisableBloatware = $true
DoPrivacyStuff = $true
}
SafetyToggles = @{
# Switches to prevent breaking functionality
BeWifiSafe = $false
BeMicrophoneSafe = $true
BeAppxSafe = $false
BeXboxSafe = $false
BeBiometricSafe = $false
BeNetworkPrinterSafe = $false
BePrinterSafe = $false
BeNetworkFolderSafe = $false
BeAeroPeekSafe = $true
BeThumbnailSafe = $true
BeCastSafe = $false
BeVpnPppoeSafe = $false
TroubleshootInstalls = $false
}
Uninstall = @{
UninstallWindowsDefender = $true
UninstallOneDrive = $true
# Define bloatware list
BloatwareList = @(
"Microsoft.BingWeather*"
"MicrosoftTeams*"
"Microsoft.DrawboardPDF*"
"E2A4F912-2574-4A75-9BB0-0D023378592B*"
"Microsoft.Appconnector*"
"Microsoft.3dbuilder"
"Microsoft.BingNews"
"Microsoft.GetHelp"
"Microsoft.Getstarted"
"Microsoft.Messaging"
"Microsoft3DViewer*"
"Microsoft.MicrosoftOfficeHub"
"Microsoft.MicrosoftSolitaireCollection"
"Microsoft.NetworkSpeedTest"
"Microsoft.News"
"Microsoft.Office.Lens"
"Microsoft.Office.OneNote"
"Microsoft.Office.Sway"
"Microsoft.OneConnect"
"Microsoft.People"
"Microsoft.Print3D"
"Microsoft.RemoteDesktop"
"Microsoft.SkypeApp"
"Microsoft.StorePurchaseApp"
"Microsoft.Office.Todo.List"
"Microsoft.Whiteboard"
"Microsoft.WindowsAlarms"
"microsoft.windowscommunicationsapps"
"Microsoft.WindowsFeedbackHub*"
"Microsoft.WindowsMaps"
"Microsoft.WindowsSoundRecorder"
"Microsoft.ZuneMusic"
"Microsoft.ZuneVideo"
# Sponsored AppX
"DolbyLaboratories.DolbyAccess*"
"Microsoft.Asphalt8Airborne*"
"46928bounde.EclipseManager*"
"ActiproSoftwareLLC*"
"AdobeSystemsIncorporated.AdobePhotoshopExpress*"
"Duolingo-LearnLanguagesforFree*"
"PandoraMediaInc*"
"CandyCrush*"
"BubbleWitch3Saga*"
"Wunderlist*"
"Flipboard.Flipboard*"
"Twitter*"
"Facebook*"
"Spotify*"
"Minecraft*"
"Royal Revolt*"
"Sway*"
"Speed Test*"
"FarmHeroesSaga*"
"Prime*"
"Clipchamp*"
"Disney*"
"Netflix*"
"Keeper*"
"Instagram*"
"Amazon*"
"Roblox*"
"AdobePhotoshop*"
)
}
Installation = @{
InstallNvidiaControlPanel = $true
InitialPackages = $false
}
Updates = @{
DisableWindowsUpdates = $false
}
}
# Add conditional entries to bloatware list based on configuration
if ($Config.SafetyToggles.BeXboxSafe -eq $false) {
$Config.Uninstall.BloatwareList += @(
"Microsoft.XboxGamingOverlay"
"Microsoft.Xbox.TCUI"
"Microsoft.XboxApp"
"Microsoft.XboxGameOverlay"
"Microsoft.XboxIdentityProvider"
"Microsoft.XboxSpeechToTextOverlay"
)
}
if ($Config.SafetyToggles.BeBiometricSafe -eq $false) {
$Config.Uninstall.BloatwareList += @(
"Microsoft.BioEnrollment*"
"Microsoft.CredDialogHost*"
"Microsoft.ECApp*"
"Microsoft.LockApp*"
)
}
if ($Config.Installation.InstallNvidiaControlPanel -eq $false) {
$Config.Uninstall.BloatwareList += "NVIDIACorp.NVIDIAControlPanel*"
}
if ($Config.SafetyToggles.BeCastSafe -eq $false) {
$Config.Uninstall.BloatwareList += "Microsoft.PPIP*"
}
#endregion Configuration
#region Logging
# Create a log file with timestamp
$LogPath = "$env:TEMP\WindowsOptimizer_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
$script:SuccessCount = 0
$script:WarningCount = 0
$script:ErrorCount = 0
function Write-LogMessage {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$Message,
[Parameter(Mandatory = $false)]
[ValidateSet('Info', 'Success', 'Warning', 'Error')]
[string]$Type = 'Info'
)
$timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
$logMessage = "[$timestamp] [$Type] $Message"
# Write to log file
Add-Content -Path $LogPath -Value $logMessage
# Output to console with appropriate color
switch ($Type) {
'Success' {
Write-Host $logMessage -ForegroundColor Green
$script:SuccessCount++
}
'Warning' {
Write-Host $logMessage -ForegroundColor Yellow
$script:WarningCount++
}
'Error' {
Write-Host $logMessage -ForegroundColor Red
$script:ErrorCount++
}
default { Write-Host $logMessage }
}
}
function Disable-WindowsFirewallService {
[CmdletBinding()]
param ()
try {
Write-LogMessage "Attempting to disable Windows Defender Firewall service..." -Type Info
# First, try using the enhanced service configuration function
$serviceResult = Set-ServiceConfigurationWithScExe -Name "MpsSvc" -State "Stopped" -StartupType "Disabled" -Description "Disabling Windows Defender Firewall Service"
# If that fails, try a more direct approach with netsh
if (-not $serviceResult) {
Write-LogMessage "Service configuration approach failed, trying netsh approach..." -Type Warning
# First try to disable the firewall profiles through netsh
$netshResult = Start-Process -FilePath "netsh" -ArgumentList "advfirewall set allprofiles state off" -Wait -NoNewWindow -PassThru
if ($netshResult.ExitCode -eq 0) {
Write-LogMessage "Successfully disabled Windows Firewall profiles using netsh" -Type Success
}
else {
Write-LogMessage ("Failed to disable Windows Firewall profiles using netsh. Exit code: " + $netshResult.ExitCode) -Type Warning
}
# Try direct registry approach as last resort
try {
# Disable the firewall service via registry
$regPath = "HKLM:\SYSTEM\CurrentControlSet\Services\MpsSvc"
if (Test-Path $regPath) {
Write-LogMessage "Attempting to modify firewall service via registry..." -Type Info
# Try using reg.exe which might have higher privileges
$regExeResult = Start-Process -FilePath "reg.exe" -ArgumentList "add `"HKLM\SYSTEM\CurrentControlSet\Services\MpsSvc`" /v Start /t REG_DWORD /d 4 /f" -Wait -NoNewWindow -PassThru
if ($regExeResult.ExitCode -eq 0) {
Write-LogMessage "Successfully modified firewall service registry key" -Type Success
}
else {
Write-LogMessage ("Failed to modify firewall service registry key. Exit code: " + $regExeResult.ExitCode) -Type Warning
}
}
}
catch {
Write-LogMessage ("Error modifying firewall registry: " + $_.Exception.Message) -Type Error
}
}
Write-LogMessage "Windows Firewall operation completed with available methods" -Type Success
return $true
}
catch {
Write-LogMessage ("Critical error disabling Windows Firewall: " + $_.Exception.Message) -Type Error
return $false
}
}
function Disable-WindowsFirewallProfiles {
[CmdletBinding()]
param ()
try {
Write-LogMessage "Attempting to disable Windows Firewall profiles..." -Type Info
# First try using PowerShell cmdlets
try {
Get-NetFirewallProfile -ErrorAction Stop | Set-NetFirewallProfile -Enabled False -ErrorAction Stop
Write-LogMessage "Successfully disabled Windows Firewall profiles using PowerShell cmdlets" -Type Success
return $true
}
catch {
Write-LogMessage ("PowerShell cmdlets failed to disable firewall profiles: " + $_.Exception.Message) -Type Warning
}
# If PowerShell method fails, try netsh command
try {
$netshResult = Start-Process -FilePath "netsh" -ArgumentList "advfirewall set allprofiles state off" -Wait -NoNewWindow -PassThru
if ($netshResult.ExitCode -eq 0) {
Write-LogMessage "Successfully disabled Windows Firewall profiles using netsh" -Type Success
return $true
}
else {
Write-LogMessage ("Failed to disable Windows Firewall profiles using netsh. Exit code: " + $netshResult.ExitCode) -Type Warning
}
}
catch {
Write-LogMessage ("Error running netsh command: " + $_.Exception.Message) -Type Warning
}
# As a last resort, try registry method
try {
$profilePaths = @(
"HKLM:\SOFTWARE\Policies\Microsoft\WindowsFirewall\DomainProfile",
"HKLM:\SOFTWARE\Policies\Microsoft\WindowsFirewall\PrivateProfile",
"HKLM:\SOFTWARE\Policies\Microsoft\WindowsFirewall\PublicProfile"
)
foreach ($path in $profilePaths) {
if (-not (Test-Path $path)) {
New-Item -Path $path -Force | Out-Null
}
# Use reg.exe for each profile
$regExeResult = Start-Process -FilePath "reg.exe" -ArgumentList "add `"$($path.Replace(':', ''))`" /v EnableFirewall /t REG_DWORD /d 0 /f" -Wait -NoNewWindow -PassThru
if ($regExeResult.ExitCode -eq 0) {
Write-LogMessage ("Successfully disabled firewall profile via registry: " + $path) -Type Success
}
}
return $true
}
catch {
Write-LogMessage ("Registry method failed to disable firewall profiles: " + $_.Exception.Message) -Type Error
return $false
}
}
catch {
Write-LogMessage ("Critical error during firewall profile operation: " + $_.Exception.Message) -Type Error
return $false
}
}
function Set-ServiceConfigurationWithScExe {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$Name,
[Parameter(Mandatory = $true)]
[ValidateSet("Running", "Stopped")]
[string]$State,
[Parameter(Mandatory = $true)]
[ValidateSet("Automatic", "Manual", "Disabled")]
[string]$StartupType,
[Parameter(Mandatory = $false)]
[string]$Description = ""
)
try {
# Map PowerShell startup type to sc.exe format
$scStartupType = switch ($StartupType) {
"Automatic" { "auto" }
"Manual" { "demand" }
"Disabled" { "disabled" }
}
# Try to configure service startup type using sc.exe
Write-LogMessage "Configuring service $Name using sc.exe..." -Type Info
$scConfigResult = Start-Process -FilePath "sc.exe" -ArgumentList "config `"$Name`" start= $scStartupType" -Wait -NoNewWindow -PassThru
if ($scConfigResult.ExitCode -ne 0) {
# Try to take ownership of the service before configuring
Write-LogMessage "Initial configuration failed, attempting alternative approach..." -Type Warning
# Try registry approach directly
try {
$regPath = "HKLM:\SYSTEM\CurrentControlSet\Services\$Name"
$startValue = switch ($StartupType) {
"Automatic" { 2 }
"Manual" { 3 }
"Disabled" { 4 }
}
# Use reg.exe to directly modify the registry
$regResult = Start-Process -FilePath "reg.exe" -ArgumentList "add `"HKLM\SYSTEM\CurrentControlSet\Services\$Name`" /v Start /t REG_DWORD /d $startValue /f" -Wait -NoNewWindow -PassThru
if ($regResult.ExitCode -ne 0) {
Write-LogMessage ("Registry modification for service $Name failed with exit code: " + $regResult.ExitCode) -Type Error
return $false
}
}
catch {
Write-LogMessage ("Failed to modify registry for service " + $Name + ": " + $_.Exception.Message) -Type Error
return $false
}
}
# Handle service state (start/stop) according to desired state
if ($State -eq "Running") {
# Only try to start if not already running and not set to disabled
if ($StartupType -ne "Disabled") {
try {
$currentState = (Get-Service -Name $Name -ErrorAction SilentlyContinue).Status
if ($currentState -ne "Running") {
Write-LogMessage "Starting service $Name..." -Type Info
Start-Process -FilePath "sc.exe" -ArgumentList "start `"$Name`"" -Wait -NoNewWindow
}
}
catch {
Write-LogMessage ("Failed to start service " + $Name + ": " + $_.Exception.Message) -Type Warning
}
}
}
else {
# Try to stop the service
try {
$currentState = (Get-Service -Name $Name -ErrorAction SilentlyContinue).Status
if ($currentState -eq "Running") {
Write-LogMessage "Stopping service $Name..." -Type Info
Start-Process -FilePath "sc.exe" -ArgumentList "stop `"$Name`"" -Wait -NoNewWindow -ErrorAction SilentlyContinue
}
}
catch {
Write-LogMessage ("Failed to stop service " + $Name + ": " + $_.Exception.Message) -Type Warning
}
}
# Verify the service configuration
try {
$serviceAfter = Get-Service -Name $Name -ErrorAction SilentlyContinue
if ($serviceAfter) {
Write-LogMessage ("Service $Name configured successfully: StartType=$StartupType, Status=$($serviceAfter.Status)") -Type Success
return $true
}
else {
Write-LogMessage "Unable to verify service $Name configuration" -Type Warning
return $true # Assume it worked if we can't verify
}
}
catch {
Write-LogMessage ("Error verifying service $Name configuration: " + $_.Exception.Message) -Type Warning
return $true # Assume it worked if we can't verify
}
}
catch {
Write-LogMessage ("Error configuring service " + $Name + ": " + $_.Exception.Message) -Type Error
return $false
}
}
function Set-ProtectedRegistryValue {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$Path,
[Parameter(Mandatory = $true)]
[string]$Name,
[Parameter(Mandatory = $true)]
$Value,
[Parameter(Mandatory = $false)]
[string]$Type = "DWord",
[Parameter(Mandatory = $false)]
[string]$Description = ""
)
try {
# Normalize path to handle both HKLM:\ and HKCU:\ paths
$normalizedPath = $Path -replace '^HKLM:', 'HKLM:\' -replace '^HKCU:', 'HKCU:\'
# Try the standard approach first
if (!(Test-Path $normalizedPath)) {
New-Item -Path $normalizedPath -Force | Out-Null
Write-LogMessage "Created registry path: $normalizedPath" -Type Info
}
# Try to set the value using standard method
Set-ItemProperty -Path $normalizedPath -Name $Name -Value $Value -Type $Type -ErrorAction Stop
Write-LogMessage ("Registry: " + $Description + " - [" + $normalizedPath + "] " + $Name + " = " + $Value) -Type Success
return $true
}
catch {
# If standard approach fails, try the alternative method using reg.exe
Write-LogMessage ("Standard registry write failed: " + $_.Exception.Message) -Type Warning
try {
# Extract the registry path without the provider prefix
$hiveName = if ($normalizedPath -match 'HKLM:\\(.*)') { "HKLM" } elseif ($normalizedPath -match 'HKCU:\\(.*)') { "HKCU" } else { throw "Unsupported registry path" }
$keyPath = if ($normalizedPath -match ':\\(.*)') { $matches[1] } else { throw "Invalid registry path format" }
# Determine the reg.exe type parameter
$regType = switch ($Type) {
"String" { "REG_SZ" }
"ExpandString" { "REG_EXPAND_SZ" }
"Binary" { "REG_BINARY" }
"DWord" { "REG_DWORD" }
"MultiString" { "REG_MULTI_SZ" }
"QWord" { "REG_QWORD" }
default { "REG_SZ" }
}
# For services, try to use sc.exe to configure the service directly
if ($keyPath -match 'SYSTEM\\CurrentControlSet\\services\\(.+)' -and $Name -eq "Start") {
$serviceName = $matches[1]
$startType = switch ($Value) {
2 { "auto" }
3 { "demand" }
4 { "disabled" }
default { $Value } # Pass through for other values
}
$scResult = Start-Process -FilePath "sc.exe" -ArgumentList "config `"$serviceName`" start= $startType" -Wait -NoNewWindow -PassThru
if ($scResult.ExitCode -eq 0) {
Write-LogMessage ("Successfully configured service " + $serviceName + " using sc.exe") -Type Success
return $true
}
else {
Write-LogMessage ("Failed to configure service using sc.exe, trying reg.exe") -Type Warning
}
}
# Use reg.exe to add the value
$regResult = Start-Process -FilePath "reg.exe" -ArgumentList "add `"$hiveName\$keyPath`" /v `"$Name`" /t $regType /d $Value /f" -Wait -NoNewWindow -PassThru
if ($regResult.ExitCode -eq 0) {
Write-LogMessage ("Registry: " + $Description + " - [" + $normalizedPath + "] " + $Name + " = " + $Value + " (using reg.exe)") -Type Success
return $true
}
else {
Write-LogMessage ("Failed to set registry value using reg.exe: " + $normalizedPath + " - Exit code: " + $regResult.ExitCode) -Type Error
# Last resort - try to take ownership of the key
Write-LogMessage "Attempting to take ownership of registry key..." -Type Warning
# Extract components for the takeown commands
$keyComponents = $keyPath.Split('\')
$keyParent = $keyComponents[0..($keyComponents.Count-2)] -join '\'
$keyName = $keyComponents[-1]
# Use PowerShell to take ownership and grant full control
$takeOwnershipScript = @"
param(
[string]`$keyPath = '$hiveName\$keyPath'
)
`$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
`$parts = `$keyPath.Split('\')
`$rootKey = `$parts[0]
`$subKey = `$parts[1..(`$parts.Length-1)] -join '\'
switch (`$rootKey) {
'HKLM' { `$hive = [Microsoft.Win32.Registry]::LocalMachine }
'HKCU' { `$hive = [Microsoft.Win32.Registry]::CurrentUser }
default { throw "Unsupported registry hive" }
}
`$regKey = `$hive.OpenSubKey(`$subKey, [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree, [System.Security.AccessControl.RegistryRights]::TakeOwnership)
if (`$regKey) {
`$acl = `$regKey.GetAccessControl()
`$acl.SetOwner(`$identity.User)
`$regKey.SetAccessControl(`$acl)
`$regKey.Close()
`$regKey = `$hive.OpenSubKey(`$subKey, [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree, [System.Security.AccessControl.RegistryRights]::ChangePermissions)
`$acl = `$regKey.GetAccessControl()
`$rule = New-Object System.Security.AccessControl.RegistryAccessRule(`$identity.User, [System.Security.AccessControl.RegistryRights]::FullControl, [System.Security.AccessControl.InheritanceFlags]::ContainerInherit, [System.Security.AccessControl.PropagationFlags]::None, [System.Security.AccessControl.AccessControlType]::Allow)
`$acl.SetAccessRule(`$rule)
`$regKey.SetAccessControl(`$acl)
`$regKey.Close()
return `$true
}
return `$false
"@
# Execute the ownership script
$ownershipResult = PowerShell -NoProfile -ExecutionPolicy Bypass -Command $takeOwnershipScript
if ($ownershipResult -eq $true) {
# Try again to set the value
$regRetryResult = Start-Process -FilePath "reg.exe" -ArgumentList "add `"$hiveName\$keyPath`" /v `"$Name`" /t $regType /d $Value /f" -Wait -NoNewWindow -PassThru
if ($regRetryResult.ExitCode -eq 0) {
Write-LogMessage ("Registry: " + $Description + " - [" + $normalizedPath + "] " + $Name + " = " + $Value + " (after taking ownership)") -Type Success
return $true
}
}
Write-LogMessage ("Failed to set registry value after all attempts: " + $normalizedPath + "\\" + $Name) -Type Error
return $false
}
}
catch {
Write-LogMessage ("Failed to set registry value using alternative methods: " + $_.Exception.Message) -Type Error
return $false
}
}
}
function Start-Operation {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$Description
)
Write-LogMessage "Starting: $Description" -Type Info
}
function Complete-Operation {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$Description,
[Parameter(Mandatory = $false)]
[bool]$Successful = $true
)
if ($Successful) {
Write-LogMessage "Completed: $Description" -Type Success
}
else {
Write-LogMessage "Failed: $Description" -Type Error
}
}
#endregion Logging
#region Helper Functions
function Test-Administrator {
$currentUser = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
return $currentUser.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
function Restart-ScriptAsAdmin {
if (-not (Test-Administrator)) {
Write-LogMessage "Script must run as administrator. Restarting with elevation..." -Type Warning
Start-Process powershell.exe -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs
Exit
}
}
function Set-RegistryValue {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$Path,
[Parameter(Mandatory = $true)]
[string]$Name,
[Parameter(Mandatory = $true)]
$Value,
[Parameter(Mandatory = $false)]
[string]$Type = "String",
[Parameter(Mandatory = $false)]
[string]$Description = ""
)
try {
# Normalize path to handle both HKLM:\ and HKCU:\ paths
$normalizedPath = $Path -replace '^HKLM:', 'HKLM:\' -replace '^HKCU:', 'HKCU:\'
# Create the path if it doesn't exist
if (!(Test-Path $normalizedPath)) {
New-Item -Path $normalizedPath -Force | Out-Null
Write-LogMessage "Created registry path: $normalizedPath" -Type Info
}
# Set the value
Set-ItemProperty -Path $normalizedPath -Name $Name -Value $Value -Type $Type -ErrorAction Stop
Write-LogMessage "Registry: $Description - [$normalizedPath] $Name = $Value" -Type Success
return $true
}
catch {
Write-LogMessage "Failed to set registry value: $normalizedPath\$Name - $($_.Exception.Message)" -Type Error
return $false
}
}
function Remove-RegistryValue {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$Path,
[Parameter(Mandatory = $false)]
[string]$Name = $null,
[Parameter(Mandatory = $false)]
[string]$Description = ""
)
try {
# Normalize path to handle both HKLM:\ and HKCU:\ paths
$normalizedPath = $Path -replace '^HKLM:', 'HKLM:\' -replace '^HKCU:', 'HKCU:\'
if (Test-Path $normalizedPath) {
if ($Name) {
# Remove specific property
Remove-ItemProperty -Path $normalizedPath -Name $Name -ErrorAction Stop
Write-LogMessage "Removed registry value: $Description - [$normalizedPath] $Name" -Type Success
}
else {
# Remove entire key
Remove-Item -Path $normalizedPath -Recurse -Force -ErrorAction Stop
Write-LogMessage "Removed registry key: $Description - $normalizedPath" -Type Success
}
return $true
}
else {
Write-LogMessage "Registry path does not exist: $normalizedPath" -Type Warning
return $true # Not an error if it doesn't exist
}
}
catch {
Write-LogMessage ("Failed to remove registry value: " + $normalizedPath + " - " + $_.Exception.Message) -Type Error
return $false
}
}
function Set-ServiceConfiguration {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$Name,
[Parameter(Mandatory = $true)]
[ValidateSet("Running", "Stopped")]
[string]$State,
[Parameter(Mandatory = $true)]
[ValidateSet("Automatic", "Manual", "Disabled")]
[string]$StartupType,
[Parameter(Mandatory = $false)]
[string]$Description = "",
[Parameter(Mandatory = $false)]
[bool]$Force = $false
)
try {
$service = Get-Service -Name $Name -ErrorAction SilentlyContinue
if ($null -eq $service) {
Write-LogMessage "Service '$Name' not found" -Type Warning
return $false
}
# Update service startup type
Set-Service -Name $Name -StartupType $StartupType -ErrorAction Stop
# Start or stop the service as needed
if ($State -eq "Running" -and $service.Status -ne "Running") {
Start-Service -Name $Name -ErrorAction Stop
}
elseif ($State -eq "Stopped" -and $service.Status -ne "Stopped") {
if ($Force) {
Stop-Service -Name $Name -Force -ErrorAction Stop
}
else {
Stop-Service -Name $Name -ErrorAction Stop
}
}
# Additional registry setting for services that need it
$regPath = "HKLM:\SYSTEM\CurrentControlSet\Services\$Name"
$startValue = switch ($StartupType) {
"Automatic" { 2 }
"Manual" { 3 }
"Disabled" { 4 }
}
Set-ProtectedRegistryValue -Path $regPath -Name "Start" -Value $startValue -Type "DWord" -Description "$Description (Registry)"
Write-LogMessage "Service: $Description - $Name set to $StartupType/$State" -Type Success
return $true
}
catch {
Write-LogMessage ("Failed to configure service " + $Name + ": " + $_.Exception.Message) -Type Error
return $false
}
}
function Remove-File {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$Path,
[Parameter(Mandatory = $false)]
[string]$Description = ""
)
if (!(Test-Path $Path)) {
Write-LogMessage "File does not exist: $Path" -Type Info
return $true
}
try {
# Take ownership
takeown /F $Path | Out-Null
# Set full permissions
$Acl = Get-Acl $Path
$username = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("everyone", "FullControl", "Allow")
$Acl.SetAccessRule($AccessRule)
Set-Acl $Path $Acl
# Remove read-only attribute
Set-ItemProperty $Path -Name IsReadOnly -Value $false -ErrorAction SilentlyContinue
# Delete the file
Remove-Item -Path $Path -Force -ErrorAction Stop
Write-LogMessage "Removed file: $Description - $Path" -Type Success
return $true
}
catch {
Write-LogMessage ("Failed to remove file " + $Path + ": " + $_.Exception.Message) -Type Error
return $false
}
}
function Remove-Directory {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$Path,
[Parameter(Mandatory = $false)]
[string]$Description = ""
)
if (!(Test-Path $Path)) {
Write-LogMessage "Directory does not exist: $Path" -Type Info
return $true
}
try {
# Take ownership of the directory and contents
takeown /F $Path /R /D Y | Out-Null
# Set full permissions
$Acl = Get-Acl $Path
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("everyone", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
$Acl.AddAccessRule($AccessRule)
Set-Acl $Path $Acl
# Delete the directory
Remove-Item -Path $Path -Recurse -Force -ErrorAction Stop
Write-LogMessage "Removed directory: $Description - $Path" -Type Success
return $true
}
catch {
Write-LogMessage ("Failed to remove directory " + $Path + ": " + $_.Exception.Message) -Type Error
return $false
}
}
function Stop-ProcessSafely {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$Name,
[Parameter(Mandatory = $false)]
[int]$MaxAttempts = 3
)
try {
$process = Get-Process -Name $Name -ErrorAction SilentlyContinue
if ($null -eq $process) {
Write-LogMessage "Process '$Name' is not running" -Type Info
return $true
}
for ($attempt = 1; $attempt -le $MaxAttempts; $attempt++) {
Write-LogMessage "Stopping process '$Name' - Attempt $attempt of $MaxAttempts" -Type Info
Stop-Process -Name $Name -Force -ErrorAction SilentlyContinue
# Wait and check if it's gone
Start-Sleep -Seconds 2
$process = Get-Process -Name $Name -ErrorAction SilentlyContinue
if ($null -eq $process) {
Write-LogMessage "Successfully stopped process '$Name'" -Type Success
return $true
}
}
Write-LogMessage "Failed to stop process '$Name' after $MaxAttempts attempts" -Type Warning
return $false
}
catch {
Write-LogMessage ("Error stopping process '" + $Name + "': " + $_.Exception.Message) -Type Error
return $false
}
}
function Clear-AllCaches {
Start-Operation "Clearing system caches"
# Clear network profiles
Remove-RegistryValue -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\Profiles" -Description "Clearing network profiles"
Remove-RegistryValue -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\Signatures\Managed" -Description "Clearing managed network profiles"
Remove-RegistryValue -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\Signatures\Unmanaged" -Description "Clearing unmanaged network profiles"
# Clear USB history
Remove-RegistryValue -Path "HKLM:\SYSTEM\CurrentControlSet\Enum\USBSTOR" -Description "Clearing USB history"
Remove-RegistryValue -Path "HKLM:\SYSTEM\CurrentControlSet\Control\usbflags" -Description "Clearing USB flags"
# Clear intranet history
Remove-RegistryValue -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\Nla\Cache\Intranet" -Description "Clearing intranet history"
# Clear command history
Remove-RegistryValue -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU" -Description "Clearing command history"
Remove-RegistryValue -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\TypedPaths" -Description "Clearing typed paths"
Remove-RegistryValue -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs" -Description "Clearing recent docs"
# Clear other caches
Remove-RegistryValue -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\AppCompatCache" -Description "Clearing app compat cache"
Remove-RegistryValue -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2" -Description "Clearing mapped drives cache"
# Clear file system caches
try {
Stop-Process -Name explorer -Force -ErrorAction SilentlyContinue
# Clear temp files
Get-ChildItem -Path $env:TEMP -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
Get-ChildItem -Path "$env:WINDIR\Prefetch" -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
Get-ChildItem -Path "$env:WINDIR\*.dmp" -ErrorAction SilentlyContinue | Remove-Item -Force -ErrorAction SilentlyContinue
# Clear explorer caches
Remove-Directory -Path "$env:LocalAppData\Microsoft\Windows\Explorer" -Description "Clearing explorer cache"
Remove-Directory -Path "$env:LocalAppData\Microsoft\Windows\Recent" -Description "Clearing recent items"
Remove-Directory -Path "$env:LocalAppData\Microsoft\Windows\Recent\AutomaticDestinations" -Description "Clearing automatic destinations"
Remove-Directory -Path "$env:LocalAppData\Microsoft\Windows\Recent\CustomDestinations" -Description "Clearing custom destinations"
# Restart explorer
Start-Process explorer.exe
Write-LogMessage "Restarted Explorer" -Type Success
}
catch {
Write-LogMessage ("Error clearing file system caches: " + $_.Exception.Message) -Type Error
}
Complete-Operation "Clearing system caches"
}
function Test-SafeMode {
$mySafeMode = Get-WmiObject win32_computersystem | Select-Object BootupState
return ($mySafeMode -notlike '*Normal boot*')
}
function Get-GPUVendor {
try {