-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathset.psm1
More file actions
1898 lines (1666 loc) · 81.7 KB
/
Copy pathset.psm1
File metadata and controls
1898 lines (1666 loc) · 81.7 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
#requires -Version 5.1
if ($null -ne $ExecutionContext.SessionState.Module) {
Set-StrictMode -Version 2.0
# Preload read-only Windows management modules with WhatIf temporarily disabled.
# Windows PowerShell 5.1 otherwise prints unrelated import-time alias previews.
$moduleImportWhatIfPreference = $WhatIfPreference
try {
$WhatIfPreference = $false
foreach ($dependencyModule in @('CimCmdlets', 'Appx', 'Dism')) {
Import-Module $dependencyModule -ErrorAction Stop
}
Import-Module PrintManagement -ErrorAction SilentlyContinue
}
finally {
$WhatIfPreference = $moduleImportWhatIfPreference
}
}
$script:DefaultAppxNames = @(
'Clipchamp.Clipchamp'
'Microsoft.549981C3F5F10'
'Microsoft.BingFinance'
'Microsoft.BingFoodAndDrink'
'Microsoft.BingHealthAndFitness'
'Microsoft.BingNews'
'Microsoft.BingSports'
'Microsoft.BingTravel'
'Microsoft.BingWeather'
'Microsoft.GamingApp'
'Microsoft.GetHelp'
'Microsoft.Getstarted'
'Microsoft.Microsoft3DViewer'
'Microsoft.MicrosoftOfficeHub'
'Microsoft.MicrosoftSolitaireCollection'
'Microsoft.MixedReality.Portal'
'Microsoft.OneConnect'
'Microsoft.OutlookForWindows'
'Microsoft.People'
'Microsoft.PowerAutomateDesktop'
'Microsoft.SkypeApp'
'Microsoft.Todos'
'Microsoft.Wallet'
'Microsoft.WindowsAlarms'
'Microsoft.WindowsFeedbackHub'
'Microsoft.WindowsMaps'
'Microsoft.WindowsSoundRecorder'
'Microsoft.Xbox.TCUI'
'Microsoft.XboxApp'
'Microsoft.XboxGameOverlay'
'Microsoft.XboxGamingOverlay'
'Microsoft.XboxIdentityProvider'
'Microsoft.XboxSpeechToTextOverlay'
'Microsoft.ZuneMusic'
'Microsoft.ZuneVideo'
'MicrosoftCorporationII.QuickAssist'
'microsoft.windowscommunicationsapps'
)
function Test-CleanMsAdministrator {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal($identity)
return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
function Add-CleanMsResult {
param(
[Parameter(Mandatory = $true)]
[System.Collections.IList]$ResultList,
[Parameter(Mandatory = $true)]
[string]$Step,
[Parameter(Mandatory = $true)]
[string]$Target,
[Parameter(Mandatory = $true)]
[ValidateSet('Changed', 'Planned', 'Skipped', 'RestartRequired', 'Failed')]
[string]$Status,
[string]$Detail = ''
)
[void]$ResultList.Add([pscustomobject]@{
Step = $Step
Target = $Target
Status = $Status
Detail = $Detail
})
}
$script:CleanMsStepActive = $false
$script:CleanMsStepHadWarning = $false
function Complete-CleanMsStep {
if (-not $script:CleanMsStepActive) {
return
}
if (-not $script:CleanMsStepHadWarning) {
Write-Host '[DONE]' -ForegroundColor Green -BackgroundColor Black
}
$script:CleanMsStepActive = $false
$script:CleanMsStepHadWarning = $false
}
function Write-CleanMsStep {
param([Parameter(Mandatory = $true)][string]$Message)
Complete-CleanMsStep
Write-Host $Message -NoNewline
$script:CleanMsStepActive = $true
$script:CleanMsStepHadWarning = $false
}
function Write-CleanMsWarning {
param([Parameter(Mandatory = $true)][string]$Message)
if ($script:CleanMsStepActive) {
$script:CleanMsStepHadWarning = $true
}
Write-Host "[WARNING] $Message" -ForegroundColor Red -BackgroundColor Black
}
function Test-CleanMsNameMatch {
param(
[Parameter(Mandatory = $true)][string]$Name,
[AllowEmptyCollection()][string[]]$Pattern = @()
)
foreach ($candidate in $Pattern) {
if ($Name -like $candidate) {
return $true
}
}
return $false
}
function Get-CleanMsPropertyValue {
param(
[Parameter(Mandatory = $true)]$InputObject,
[Parameter(Mandatory = $true)][string]$Name
)
$property = $InputObject.PSObject.Properties[$Name]
if ($null -eq $property) {
return $null
}
return $property.Value
}
function Set-CleanMsRegistryDword {
param(
[Parameter(Mandatory = $true)]$Context,
[Parameter(Mandatory = $true)][System.Collections.IList]$ResultList,
[Parameter(Mandatory = $true)][string]$Step,
[Parameter(Mandatory = $true)][string]$Path,
[Parameter(Mandatory = $true)][string]$Name,
[Parameter(Mandatory = $true)][int]$Value,
[Parameter(Mandatory = $true)][bool]$DryRun
)
$target = "$Path\$Name"
$currentValue = $null
$currentValueKind = $null
try {
if (Test-Path -Path $Path) {
$property = Get-ItemProperty -Path $Path -Name $Name -ErrorAction SilentlyContinue
if ($null -ne $property) {
$currentValue = Get-CleanMsPropertyValue -InputObject $property -Name $Name
try {
$registryKey = Get-Item -Path $Path -ErrorAction Stop
$currentValueKind = $registryKey.GetValueKind($Name)
}
catch {
# Unknown or wrong value kinds are rewritten as DWORD below.
$currentValueKind = $null
}
}
}
}
catch {
Write-CleanMsWarning "Could not read $target. $($_.Exception.Message)"
Add-CleanMsResult -ResultList $ResultList -Step $Step -Target $target -Status Failed -Detail $_.Exception.Message
return 'Failed'
}
$currentDword = 0
if ($currentValueKind -eq [Microsoft.Win32.RegistryValueKind]::DWord -and
$null -ne $currentValue -and
[int]::TryParse([string]$currentValue, [ref]$currentDword) -and
$currentDword -eq $Value) {
Add-CleanMsResult -ResultList $ResultList -Step $Step -Target $target -Status Skipped -Detail 'Already configured.'
return 'Unchanged'
}
if (-not $Context.ShouldProcess($target, "Set DWORD value to $Value")) {
$status = if ($DryRun) { 'Planned' } else { 'Skipped' }
Add-CleanMsResult -ResultList $ResultList -Step $Step -Target $target -Status $status
return $(if ($DryRun) { 'Planned' } else { 'Declined' })
}
try {
if (-not (Test-Path -Path $Path)) {
New-Item -Path $Path -Force -ErrorAction Stop | Out-Null
}
New-ItemProperty -Path $Path -Name $Name -Value $Value -PropertyType DWord -Force -ErrorAction Stop | Out-Null
Add-CleanMsResult -ResultList $ResultList -Step $Step -Target $target -Status Changed
return 'Changed'
}
catch {
Write-CleanMsWarning "Could not configure $target. $($_.Exception.Message)"
Add-CleanMsResult -ResultList $ResultList -Step $Step -Target $target -Status Failed -Detail $_.Exception.Message
return 'Failed'
}
}
function Remove-CleanMsAppxPackages {
param(
[Parameter(Mandatory = $true)]$Context,
[Parameter(Mandatory = $true)][System.Collections.IList]$ResultList,
[Parameter(Mandatory = $true)][string]$Step,
[Parameter(Mandatory = $true)][string[]]$Name,
[string[]]$KeepName = @(),
[Parameter(Mandatory = $true)][bool]$DryRun
)
$patterns = @($Name | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | Select-Object -Unique)
if ($patterns.Count -eq 0) {
return
}
try {
$matchedPackages = @(Get-AppxPackage -AllUsers -PackageTypeFilter Main, Bundle, Framework, Resource -ErrorAction Stop | Where-Object {
(Test-CleanMsNameMatch -Name $_.Name -Pattern $patterns) -and
-not (Test-CleanMsNameMatch -Name $_.Name -Pattern $KeepName)
})
$protectedNames = @($matchedPackages | Where-Object {
$_.IsFramework -or $_.IsResourcePackage -or $_.NonRemovable
} | Select-Object -ExpandProperty Name -Unique)
$bundleNames = @($matchedPackages | Where-Object { $_.IsBundle } | Select-Object -ExpandProperty Name -Unique)
$installedPackages = @($matchedPackages | Where-Object {
$_.IsFramework -or $_.IsResourcePackage -or $_.NonRemovable -or
$_.IsBundle -or $bundleNames -notcontains $_.Name
})
}
catch {
Write-CleanMsWarning "Could not enumerate installed AppX packages. $($_.Exception.Message)"
Add-CleanMsResult -ResultList $ResultList -Step $Step -Target 'Installed AppX inventory' -Status Failed -Detail $_.Exception.Message
return
}
foreach ($package in $installedPackages) {
$isFramework = $package.PSObject.Properties.Name -contains 'IsFramework' -and $package.IsFramework
$isResource = $package.PSObject.Properties.Name -contains 'IsResourcePackage' -and $package.IsResourcePackage
$isNonRemovable = $package.PSObject.Properties.Name -contains 'NonRemovable' -and $package.NonRemovable
if ($isFramework -or $isResource -or $isNonRemovable) {
Add-CleanMsResult -ResultList $ResultList -Step $Step -Target $package.PackageFullName -Status Skipped -Detail 'Framework, resource, or non-removable package.'
continue
}
if (-not $Context.ShouldProcess($package.PackageFullName, 'Remove installed AppX package for all users')) {
$status = if ($DryRun) { 'Planned' } else { 'Skipped' }
Add-CleanMsResult -ResultList $ResultList -Step $Step -Target $package.PackageFullName -Status $status
continue
}
try {
Remove-AppxPackage -Package $package.PackageFullName -AllUsers -ErrorAction Stop
Add-CleanMsResult -ResultList $ResultList -Step $Step -Target $package.PackageFullName -Status Changed -Detail 'Removed from existing user profiles.'
}
catch {
Write-CleanMsWarning "Could not remove AppX package $($package.Name). $($_.Exception.Message)"
Add-CleanMsResult -ResultList $ResultList -Step $Step -Target $package.PackageFullName -Status Failed -Detail $_.Exception.Message
}
}
try {
$provisionedPackages = @(Get-AppxProvisionedPackage -Online -ErrorAction Stop | Where-Object {
(Test-CleanMsNameMatch -Name $_.DisplayName -Pattern $patterns) -and
-not (Test-CleanMsNameMatch -Name $_.DisplayName -Pattern $KeepName) -and
$protectedNames -notcontains $_.DisplayName
})
}
catch {
Write-CleanMsWarning "Could not enumerate provisioned AppX packages. $($_.Exception.Message)"
Add-CleanMsResult -ResultList $ResultList -Step $Step -Target 'Provisioned AppX inventory' -Status Failed -Detail $_.Exception.Message
$provisionedPackages = @()
}
foreach ($package in $provisionedPackages) {
if (-not $Context.ShouldProcess($package.PackageName, 'Remove AppX provisioning for current and future users')) {
$status = if ($DryRun) { 'Planned' } else { 'Skipped' }
Add-CleanMsResult -ResultList $ResultList -Step $Step -Target $package.PackageName -Status $status
continue
}
try {
Remove-AppxProvisionedPackage -Online -PackageName $package.PackageName -AllUsers -ErrorAction Stop | Out-Null
Add-CleanMsResult -ResultList $ResultList -Step $Step -Target $package.PackageName -Status Changed -Detail 'Removed from the provisioning layer.'
}
catch {
Write-CleanMsWarning "Could not deprovision AppX package $($package.DisplayName). $($_.Exception.Message)"
Add-CleanMsResult -ResultList $ResultList -Step $Step -Target $package.PackageName -Status Failed -Detail $_.Exception.Message
}
}
}
function Remove-CleanMsOptionalFeatures {
param(
[Parameter(Mandatory = $true)]$Context,
[Parameter(Mandatory = $true)][System.Collections.IList]$ResultList,
[Parameter(Mandatory = $true)][bool]$DryRun
)
Write-CleanMsStep 'Removing optional Windows features and printers...'
$step = 'Optional features'
$featureNames = @(
'WindowsMediaPlayer'
'WorkFolders-Client'
'Printing-XPSServices-Features'
'FaxServicesClientPackage'
)
try {
$features = @(Get-WindowsOptionalFeature -Online -ErrorAction Stop)
}
catch {
Write-CleanMsWarning "Could not enumerate optional Windows features. $($_.Exception.Message)"
Add-CleanMsResult -ResultList $ResultList -Step $step -Target 'Windows optional feature inventory' -Status Failed -Detail $_.Exception.Message
$features = @()
}
foreach ($featureName in $featureNames) {
$feature = $features | Where-Object { $_.FeatureName -eq $featureName } | Select-Object -First 1
if ($null -eq $feature -or $feature.State -eq 'Disabled' -or $feature.State -eq 'DisabledWithPayloadRemoved') {
Add-CleanMsResult -ResultList $ResultList -Step $step -Target $featureName -Status Skipped -Detail 'Not present or already disabled.'
continue
}
if (-not $Context.ShouldProcess($featureName, 'Disable Windows optional feature')) {
$status = if ($DryRun) { 'Planned' } else { 'Skipped' }
Add-CleanMsResult -ResultList $ResultList -Step $step -Target $featureName -Status $status
continue
}
try {
$result = Disable-WindowsOptionalFeature -Online -FeatureName $featureName -NoRestart -ErrorAction Stop
Add-CleanMsResult -ResultList $ResultList -Step $step -Target $featureName -Status Changed -Detail "RestartNeeded=$($result.RestartNeeded)"
}
catch {
Write-CleanMsWarning "Could not disable optional feature $featureName. $($_.Exception.Message)"
Add-CleanMsResult -ResultList $ResultList -Step $step -Target $featureName -Status Failed -Detail $_.Exception.Message
}
}
$capabilityPatterns = @('Media.WindowsMediaPlayer*', 'Print.Fax.Scan*')
try {
$capabilities = @(Get-WindowsCapability -Online -ErrorAction Stop | Where-Object {
$_.State -eq 'Installed' -and (Test-CleanMsNameMatch -Name $_.Name -Pattern $capabilityPatterns)
})
}
catch {
Write-CleanMsWarning "Could not enumerate Windows capabilities. $($_.Exception.Message)"
Add-CleanMsResult -ResultList $ResultList -Step $step -Target 'Windows capability inventory' -Status Failed -Detail $_.Exception.Message
$capabilities = @()
}
foreach ($capability in $capabilities) {
if (-not $Context.ShouldProcess($capability.Name, 'Remove Windows capability')) {
$status = if ($DryRun) { 'Planned' } else { 'Skipped' }
Add-CleanMsResult -ResultList $ResultList -Step $step -Target $capability.Name -Status $status
continue
}
try {
$result = Remove-WindowsCapability -Online -Name $capability.Name -ErrorAction Stop
Add-CleanMsResult -ResultList $ResultList -Step $step -Target $capability.Name -Status Changed -Detail "RestartNeeded=$($result.RestartNeeded)"
}
catch {
Write-CleanMsWarning "Could not remove capability $($capability.Name). $($_.Exception.Message)"
Add-CleanMsResult -ResultList $ResultList -Step $step -Target $capability.Name -Status Failed -Detail $_.Exception.Message
}
}
if ($null -eq (Get-Command Get-Printer -ErrorAction SilentlyContinue)) {
Add-CleanMsResult -ResultList $ResultList -Step $step -Target 'Fax and XPS printer queues' -Status Skipped -Detail 'PrintManagement cmdlets are unavailable.'
return
}
try {
$printers = @(Get-Printer -ErrorAction Stop | Where-Object {
$_.Name -eq 'Fax' -or
$_.Name -eq 'Microsoft XPS Document Writer' -or
$_.DriverName -like '*Microsoft*XPS*' -or
$_.DriverName -like '*Shared Fax*'
})
}
catch {
Write-CleanMsWarning "Could not enumerate printers. $($_.Exception.Message)"
Add-CleanMsResult -ResultList $ResultList -Step $step -Target 'Printer inventory' -Status Failed -Detail $_.Exception.Message
$printers = @()
}
foreach ($printer in $printers) {
if (-not $Context.ShouldProcess($printer.Name, 'Remove printer queue')) {
$status = if ($DryRun) { 'Planned' } else { 'Skipped' }
Add-CleanMsResult -ResultList $ResultList -Step $step -Target $printer.Name -Status $status
continue
}
try {
Remove-Printer -Name $printer.Name -ErrorAction Stop
Add-CleanMsResult -ResultList $ResultList -Step $step -Target $printer.Name -Status Changed
}
catch {
Write-CleanMsWarning "Could not remove printer $($printer.Name). $($_.Exception.Message)"
Add-CleanMsResult -ResultList $ResultList -Step $step -Target $printer.Name -Status Failed -Detail $_.Exception.Message
}
}
}
function Set-CleanMsPrivacyPolicies {
param(
[Parameter(Mandatory = $true)]$Context,
[Parameter(Mandatory = $true)][System.Collections.IList]$ResultList,
[Parameter(Mandatory = $true)][bool]$DryRun
)
Write-CleanMsStep 'Configuring documented Microsoft Edge and Office privacy policies...'
$edgePath = 'HKLM:\SOFTWARE\Policies\Microsoft\Edge'
$edgeValues = [ordered]@{
DiagnosticData = 0
UrlDiagnosticDataEnabled = 0
Edge3PSerpTelemetryEnabled = 0
PersonalizationReportingEnabled = 0
UserFeedbackAllowed = 0
PaymentMethodQueryEnabled = 0
AutofillCreditCardEnabled = 0
AutofillAddressEnabled = 0
SearchSuggestEnabled = 0
EdgeShoppingAssistantEnabled = 0
ConfigureDoNotTrack = 1
HubsSidebarEnabled = 0
Microsoft365CopilotChatIconEnabled = 0
EdgeEntraCopilotPageContext = 0
}
foreach ($entry in $edgeValues.GetEnumerator()) {
$null = Set-CleanMsRegistryDword -Context $Context -ResultList $ResultList -Step 'Edge privacy' -Path $edgePath -Name $entry.Key -Value $entry.Value -DryRun $DryRun
}
$officeTelemetryPath = 'HKCU:\Software\Policies\Microsoft\Office\Common\ClientTelemetry'
$null = Set-CleanMsRegistryDword -Context $Context -ResultList $ResultList -Step 'Office privacy' -Path $officeTelemetryPath -Name 'SendTelemetry' -Value 3 -DryRun $DryRun
}
function Set-CleanMsWindowsSyncPolicy {
param(
[Parameter(Mandatory = $true)]$Context,
[Parameter(Mandatory = $true)][System.Collections.IList]$ResultList,
[Parameter(Mandatory = $true)][bool]$DryRun
)
Write-CleanMsStep 'Disabling Windows settings synchronization...'
$path = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\SettingSync'
$null = Set-CleanMsRegistryDword -Context $Context -ResultList $ResultList -Step 'Windows sync' -Path $path -Name 'DisableSettingSync' -Value 2 -DryRun $DryRun
$null = Set-CleanMsRegistryDword -Context $Context -ResultList $ResultList -Step 'Windows sync' -Path $path -Name 'DisableSettingSyncUserOverride' -Value 1 -DryRun $DryRun
}
function Set-CleanMsWidgetsPolicy {
param(
[Parameter(Mandatory = $true)]$Context,
[Parameter(Mandatory = $true)][System.Collections.IList]$ResultList,
[Parameter(Mandatory = $true)][bool]$DryRun
)
$os = Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction SilentlyContinue
if ($null -eq $os) {
Add-CleanMsResult -ResultList $ResultList -Step 'Widgets' -Target 'Windows version' -Status Failed -Detail 'Could not determine the Windows build.'
return
}
if ([int]$os.BuildNumber -ge 22000) {
Write-CleanMsStep 'Disabling Windows 11 Widgets by policy...'
$null = Set-CleanMsRegistryDword -Context $Context -ResultList $ResultList -Step 'Widgets' -Path 'HKLM:\SOFTWARE\Policies\Microsoft\Dsh' -Name 'AllowNewsAndInterests' -Value 0 -DryRun $DryRun
}
else {
Write-CleanMsStep 'Disabling Windows 10 News and interests by policy...'
$null = Set-CleanMsRegistryDword -Context $Context -ResultList $ResultList -Step 'News and interests' -Path 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\Windows Feeds' -Name 'EnableFeeds' -Value 0 -DryRun $DryRun
}
}
function Disable-CleanMsCopilot {
param(
[Parameter(Mandatory = $true)]$Context,
[Parameter(Mandatory = $true)][System.Collections.IList]$ResultList,
[string[]]$KeepName = @(),
[switch]$SkipAppRemoval,
[Parameter(Mandatory = $true)][bool]$DryRun
)
Write-CleanMsStep 'Applying the supported Copilot cleanup and compatibility policy...'
if (-not $SkipAppRemoval) {
Remove-CleanMsAppxPackages -Context $Context -ResultList $ResultList -Step 'Copilot app' -Name @('Microsoft.Copilot') -KeepName $KeepName -DryRun $DryRun
}
$null = Set-CleanMsRegistryDword -Context $Context -ResultList $ResultList -Step 'Copilot legacy policy' -Path 'HKCU:\Software\Policies\Microsoft\Windows\WindowsCopilot' -Name 'TurnOffWindowsCopilot' -Value 1 -DryRun $DryRun
}
function Get-CleanMsUninstallEntries {
$registryRoots = @(
'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'
'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall'
)
foreach ($root in $registryRoots) {
if (-not (Test-Path -Path $root)) {
continue
}
foreach ($key in Get-ChildItem -Path $root -ErrorAction SilentlyContinue) {
$entry = Get-ItemProperty -Path $key.PSPath -ErrorAction SilentlyContinue
if ($null -eq $entry) {
continue
}
$displayName = Get-CleanMsPropertyValue -InputObject $entry -Name 'DisplayName'
if ([string]::IsNullOrWhiteSpace($displayName)) {
continue
}
[pscustomobject]@{
DisplayName = $displayName
DisplayVersion = Get-CleanMsPropertyValue -InputObject $entry -Name 'DisplayVersion'
UninstallString = Get-CleanMsPropertyValue -InputObject $entry -Name 'UninstallString'
QuietUninstallString = Get-CleanMsPropertyValue -InputObject $entry -Name 'QuietUninstallString'
NoRemove = Get-CleanMsPropertyValue -InputObject $entry -Name 'NoRemove'
SystemComponent = Get-CleanMsPropertyValue -InputObject $entry -Name 'SystemComponent'
ProductCode = $key.PSChildName
RegistryPath = $key.PSPath
}
}
}
}
function Split-CleanMsCommandLine {
param([Parameter(Mandatory = $true)][string]$CommandLine)
$expanded = [Environment]::ExpandEnvironmentVariables($CommandLine.Trim())
if ($expanded -match '^\s*"([^"]+\.exe)"\s*(.*)$') {
return [pscustomobject]@{ FilePath = $matches[1].Trim(); Arguments = $matches[2].Trim() }
}
if ($expanded -match '^\s*(.+?\.exe)\s*(.*)$') {
return [pscustomobject]@{ FilePath = $matches[1].Trim(); Arguments = $matches[2].Trim() }
}
throw "Could not parse uninstall command: $CommandLine"
}
function Assert-CleanMsMicrosoftSignature {
param([Parameter(Mandatory = $true)][string]$LiteralPath)
$signature = Get-AuthenticodeSignature -LiteralPath $LiteralPath -ErrorAction Stop
$subject = if ($null -ne $signature.SignerCertificate) { $signature.SignerCertificate.Subject } else { '' }
if ($signature.Status -ne 'Valid' -or $subject -notmatch '(?i)(^|,\s*)O=Microsoft Corporation(,|$)') {
throw "Executable does not have a valid Microsoft signature: $LiteralPath"
}
}
function Invoke-CleanMsUninstallCommand {
param(
[Parameter(Mandatory = $true)][string]$CommandLine,
[Parameter(Mandatory = $true)][string]$DisplayName,
[string]$ExpectedFileName,
[string[]]$AllowedRootPath = @(),
[switch]$RequireMicrosoftSignature
)
$command = Split-CleanMsCommandLine -CommandLine $CommandLine
if (-not [IO.Path]::IsPathRooted($command.FilePath)) {
throw "Uninstaller must use an absolute path: $($command.FilePath)"
}
$command.FilePath = [IO.Path]::GetFullPath($command.FilePath)
if ($AllowedRootPath.Count -gt 0) {
$isAllowedPath = $false
foreach ($rootPath in $AllowedRootPath) {
if ([string]::IsNullOrWhiteSpace($rootPath)) {
continue
}
$normalizedRoot = [IO.Path]::GetFullPath($rootPath).TrimEnd('\') + '\'
if ($command.FilePath.StartsWith($normalizedRoot, [StringComparison]::OrdinalIgnoreCase)) {
$isAllowedPath = $true
break
}
}
if (-not $isAllowedPath) {
throw "Uninstaller is outside the trusted Windows or Program Files roots: $($command.FilePath)"
}
}
if (-not (Test-Path -LiteralPath $command.FilePath -PathType Leaf)) {
throw "Uninstaller executable was not found: $($command.FilePath)"
}
if (-not [string]::IsNullOrWhiteSpace($ExpectedFileName) -and [IO.Path]::GetFileName($command.FilePath) -ne $ExpectedFileName) {
throw "Unexpected uninstaller executable: $($command.FilePath)"
}
if ($RequireMicrosoftSignature) {
Assert-CleanMsMicrosoftSignature -LiteralPath $command.FilePath
}
$startParameters = @{
FilePath = $command.FilePath
Wait = $true
PassThru = $true
WindowStyle = 'Hidden'
ErrorAction = 'Stop'
}
if (-not [string]::IsNullOrWhiteSpace($command.Arguments)) {
$startParameters['ArgumentList'] = $command.Arguments
}
$process = Start-Process @startParameters
if ($process.ExitCode -notin @(0, 1605, 1614, 3010)) {
throw "$DisplayName uninstaller exited with code $($process.ExitCode)."
}
return $process.ExitCode
}
function Remove-CleanMsTeams {
param(
[Parameter(Mandatory = $true)]$Context,
[Parameter(Mandatory = $true)][System.Collections.IList]$ResultList,
[string[]]$KeepName = @(),
[Parameter(Mandatory = $true)][bool]$DryRun
)
Write-CleanMsStep 'Removing Microsoft Teams and the Teams Meeting Add-in...'
Remove-CleanMsAppxPackages -Context $Context -ResultList $ResultList -Step 'Teams app' -Name @('MSTeams', 'MicrosoftTeams') -KeepName $KeepName -DryRun $DryRun
$entries = @(Get-CleanMsUninstallEntries | Where-Object {
$_.DisplayName -like '*Teams Meeting Add-in*' -or
$_.DisplayName -like '*Teams Meeting Addin*'
})
foreach ($entry in $entries) {
$target = "$($entry.DisplayName) $($entry.DisplayVersion)".Trim()
if ($entry.ProductCode -notmatch '^\{[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\}$') {
Add-CleanMsResult -ResultList $ResultList -Step 'Teams add-in' -Target $target -Status Skipped -Detail 'Only machine-wide MSI product-code entries are trusted for elevated removal.'
continue
}
if (-not $Context.ShouldProcess($target, 'Uninstall Teams Meeting Add-in')) {
$status = if ($DryRun) { 'Planned' } else { 'Skipped' }
Add-CleanMsResult -ResultList $ResultList -Step 'Teams add-in' -Target $target -Status $status
continue
}
try {
$systemDirectory = [Environment]::SystemDirectory
$msiExecPath = Join-Path $systemDirectory 'msiexec.exe'
$msiCommand = '"{0}" /x {1} /qn /norestart' -f $msiExecPath, $entry.ProductCode
$exitCode = Invoke-CleanMsUninstallCommand -CommandLine $msiCommand -DisplayName $entry.DisplayName -ExpectedFileName 'msiexec.exe' -AllowedRootPath @($systemDirectory) -RequireMicrosoftSignature
Add-CleanMsResult -ResultList $ResultList -Step 'Teams add-in' -Target $target -Status Changed -Detail "ExitCode=$exitCode"
}
catch {
Write-CleanMsWarning "Could not uninstall $target. $($_.Exception.Message)"
Add-CleanMsResult -ResultList $ResultList -Step 'Teams add-in' -Target $target -Status Failed -Detail $_.Exception.Message
}
}
}
function Remove-CleanMsOneDrive {
param(
[Parameter(Mandatory = $true)]$Context,
[Parameter(Mandatory = $true)][System.Collections.IList]$ResultList,
[Parameter(Mandatory = $true)][bool]$DryRun
)
Write-CleanMsStep 'Uninstalling Microsoft OneDrive without deleting OneDrive folder contents...'
$step = 'OneDrive'
$systemDirectory = [Environment]::SystemDirectory
$windowsDirectory = [IO.Directory]::GetParent($systemDirectory).FullName
$localAppData = [Environment]::GetFolderPath([Environment+SpecialFolder]::LocalApplicationData)
$programFiles = [Environment]::GetFolderPath([Environment+SpecialFolder]::ProgramFiles)
$programFilesX86 = [Environment]::GetFolderPath([Environment+SpecialFolder]::ProgramFilesX86)
$entries = @(Get-CleanMsUninstallEntries | Where-Object { $_.DisplayName -eq 'Microsoft OneDrive' })
$uninstallCommands = New-Object System.Collections.ArrayList
foreach ($entry in $entries) {
if (-not [string]::IsNullOrWhiteSpace($entry.QuietUninstallString)) {
[void]$uninstallCommands.Add($entry.QuietUninstallString)
}
if (-not [string]::IsNullOrWhiteSpace($entry.UninstallString)) {
[void]$uninstallCommands.Add($entry.UninstallString)
}
}
$installMarkers = New-Object System.Collections.ArrayList
if (-not [string]::IsNullOrWhiteSpace($localAppData)) {
[void]$installMarkers.Add((Join-Path $localAppData 'Microsoft\OneDrive\OneDrive.exe'))
}
foreach ($basePath in @($programFiles, $programFilesX86)) {
if (-not [string]::IsNullOrWhiteSpace($basePath)) {
[void]$installMarkers.Add((Join-Path $basePath 'Microsoft OneDrive\OneDrive.exe'))
}
}
$hasInstallMarker = @($installMarkers | Where-Object { Test-Path -LiteralPath $_ -PathType Leaf }).Count -gt 0
$hasRunningProcess = $null -ne (Get-Process -Name OneDrive -ErrorAction SilentlyContinue | Select-Object -First 1)
$installationDetected = $entries.Count -gt 0 -or $hasInstallMarker -or $hasRunningProcess
if ($installationDetected) {
$trustedOneDriveRoots = @($windowsDirectory, $programFiles, $programFilesX86) | Where-Object {
-not [string]::IsNullOrWhiteSpace($_)
}
foreach ($programFilesRoot in @($programFiles, $programFilesX86)) {
if ([string]::IsNullOrWhiteSpace($programFilesRoot)) {
continue
}
$oneDriveMachineRoot = Join-Path $programFilesRoot 'Microsoft OneDrive'
foreach ($machineSetup in Get-ChildItem -Path $oneDriveMachineRoot -Filter OneDriveSetup.exe -File -Recurse -ErrorAction SilentlyContinue) {
[void]$uninstallCommands.Add(('"{0}" /allusers /uninstall' -f $machineSetup.FullName))
}
}
foreach ($setupPath in @(
(Join-Path $systemDirectory 'OneDriveSetup.exe')
(Join-Path $windowsDirectory 'SysWOW64\OneDriveSetup.exe')
)) {
if (Test-Path -LiteralPath $setupPath -PathType Leaf) {
[void]$uninstallCommands.Add(('"{0}" /uninstall' -f $setupPath))
}
}
$uninstallCommands = @($uninstallCommands | Select-Object -Unique)
if ($uninstallCommands.Count -eq 0) {
Add-CleanMsResult -ResultList $ResultList -Step $step -Target 'Microsoft OneDrive' -Status Failed -Detail 'OneDrive appears installed, but no trusted uninstaller was found.'
}
elseif ($Context.ShouldProcess('Microsoft OneDrive', 'Stop the sync client and run a Microsoft-signed OneDriveSetup.exe uninstaller')) {
try {
Stop-Process -Name OneDrive -Force -ErrorAction SilentlyContinue
$attemptErrors = New-Object System.Collections.ArrayList
$exitCode = $null
foreach ($uninstallCommand in $uninstallCommands) {
try {
$exitCode = Invoke-CleanMsUninstallCommand -CommandLine $uninstallCommand -DisplayName 'Microsoft OneDrive' -ExpectedFileName 'OneDriveSetup.exe' -AllowedRootPath $trustedOneDriveRoots -RequireMicrosoftSignature
break
}
catch {
[void]$attemptErrors.Add($_.Exception.Message)
}
}
if ($null -eq $exitCode) {
throw ($attemptErrors -join ' | ')
}
Add-CleanMsResult -ResultList $ResultList -Step $step -Target 'Microsoft OneDrive' -Status Changed -Detail "ExitCode=$exitCode; OneDrive folder contents were not explicitly deleted."
}
catch {
Write-CleanMsWarning "Could not uninstall Microsoft OneDrive. $($_.Exception.Message)"
Add-CleanMsResult -ResultList $ResultList -Step $step -Target 'Microsoft OneDrive' -Status Failed -Detail $_.Exception.Message
}
}
else {
$status = if ($DryRun) { 'Planned' } else { 'Skipped' }
Add-CleanMsResult -ResultList $ResultList -Step $step -Target 'Microsoft OneDrive' -Status $status -Detail 'The script will not explicitly delete OneDrive folder contents.'
}
}
else {
Add-CleanMsResult -ResultList $ResultList -Step $step -Target 'Microsoft OneDrive' -Status Skipped -Detail 'No installed OneDrive client was detected.'
}
$null = Set-CleanMsRegistryDword -Context $Context -ResultList $ResultList -Step $step -Path 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\OneDrive' -Name 'DisableFileSyncNGSC' -Value 1 -DryRun $DryRun
$shortcutPaths = @(
(Join-Path ([Environment]::GetFolderPath('Desktop')) 'OneDrive.lnk')
(Join-Path ([Environment]::GetFolderPath('StartMenu')) 'Programs\OneDrive.lnk')
)
foreach ($shortcut in $shortcutPaths) {
if (-not (Test-Path -LiteralPath $shortcut)) {
continue
}
if (-not $Context.ShouldProcess($shortcut, 'Remove OneDrive shortcut')) {
$status = if ($DryRun) { 'Planned' } else { 'Skipped' }
Add-CleanMsResult -ResultList $ResultList -Step $step -Target $shortcut -Status $status
continue
}
try {
Remove-Item -LiteralPath $shortcut -Force -ErrorAction Stop
Add-CleanMsResult -ResultList $ResultList -Step $step -Target $shortcut -Status Changed
}
catch {
Write-CleanMsWarning "Could not remove shortcut $shortcut. $($_.Exception.Message)"
Add-CleanMsResult -ResultList $ResultList -Step $step -Target $shortcut -Status Failed -Detail $_.Exception.Message
}
}
}
function Get-CleanMsProcessEnvironmentValue {
param([Parameter(Mandatory = $true)][string]$Name)
return [Environment]::GetEnvironmentVariable($Name, [EnvironmentVariableTarget]::Process)
}
function Invoke-CleanMsWithGlobalMutex {
param(
[Parameter(Mandatory = $true)][string]$Name,
[Parameter(Mandatory = $true)][scriptblock]$Action
)
$mutex = $null
$acquired = $false
try {
$mutex = New-Object Threading.Mutex($false, $Name)
try {
$acquired = $mutex.WaitOne(0)
}
catch [Threading.AbandonedMutexException] {
$acquired = $true
throw 'A previous deep Edge-removal process ended unexpectedly. Inspect WINDIR, Geo, and recovery backups before retrying.'
}
if (-not $acquired) {
throw 'Another deep Edge-removal process is already running.'
}
return & $Action
}
finally {
if ($acquired -and $null -ne $mutex) {
try {
$mutex.ReleaseMutex()
}
catch {
Write-CleanMsWarning "Could not release the deep Edge-removal mutex. $($_.Exception.Message)"
}
}
if ($null -ne $mutex) {
$mutex.Dispose()
}
}
}
function Set-CleanMsProcessEnvironmentValue {
param(
[Parameter(Mandatory = $true)][string]$Name,
[AllowNull()][string]$Value
)
[Environment]::SetEnvironmentVariable($Name, $Value, [EnvironmentVariableTarget]::Process)
}
function Invoke-CleanMsWithTemporaryRegistryValues {
param(
[Parameter(Mandatory = $true)][string]$Path,
[Parameter(Mandatory = $true)][object[]]$ValueEntry,
[Parameter(Mandatory = $true)][scriptblock]$Action
)
$registryKey = Get-Item -Path $Path -ErrorAction Stop
$originalValues = New-Object System.Collections.ArrayList
try {
$existingNames = @($registryKey.GetValueNames())
foreach ($entry in $ValueEntry) {
$existed = $existingNames -contains $entry.Name
$originalValue = $null
$originalKind = $null
if ($existed) {
$originalValue = $registryKey.GetValue(
$entry.Name,
$null,
[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames
)
$originalKind = $registryKey.GetValueKind($entry.Name)
}
[void]$originalValues.Add([pscustomobject]@{
Name = $entry.Name
Existed = $existed
Value = $originalValue
Kind = $originalKind
})
}
try {
foreach ($entry in $ValueEntry) {
$registryKey.SetValue($entry.Name, $entry.Value, $entry.Kind)
}
return & $Action
}
finally {
$restoreErrors = New-Object System.Collections.ArrayList
foreach ($original in $originalValues) {
try {
if ($original.Existed) {
$registryKey.SetValue($original.Name, $original.Value, $original.Kind)
}
else {
$registryKey.DeleteValue($original.Name, $false)
}
}
catch {
[void]$restoreErrors.Add("$($original.Name): $($_.Exception.Message)")
}
}
if ($restoreErrors.Count -gt 0) {
$rollbackException = [System.InvalidOperationException]::new("Could not restore temporary registry values at $Path. $($restoreErrors -join ' | ')")
$rollbackException.Data['CleanMsRollbackFailure'] = $true
throw $rollbackException
}
}
}
finally {
if ($null -ne $registryKey) {
$registryKey.Close()
}
}
}
function Invoke-CleanMsEdgeWithTemporaryWindir {
param([Parameter(Mandatory = $true)][scriptblock]$Action)
$environmentPath = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
$originalProcessWindir = Get-CleanMsProcessEnvironmentValue -Name 'windir'
try {
Set-CleanMsProcessEnvironmentValue -Name 'windir' -Value ''
return Invoke-CleanMsWithTemporaryRegistryValues -Path $environmentPath -ValueEntry @(
[pscustomobject]@{
Name = 'windir'
Value = ''
Kind = [Microsoft.Win32.RegistryValueKind]::ExpandString
}
) -Action $Action
}
finally {
try {
Set-CleanMsProcessEnvironmentValue -Name 'windir' -Value $originalProcessWindir
}
catch {
$rollbackException = [System.InvalidOperationException]::new("Could not restore the process WINDIR value. $($_.Exception.Message)")
$rollbackException.Data['CleanMsRollbackFailure'] = $true
throw $rollbackException
}
}
}
function Invoke-CleanMsEdgeWithTemporaryEuRegion {
param([Parameter(Mandatory = $true)][scriptblock]$Action)
return Invoke-CleanMsWithTemporaryRegistryValues -Path 'Registry::HKEY_USERS\.DEFAULT\Control Panel\International\Geo' -ValueEntry @(
[pscustomobject]@{
Name = 'Name'
Value = 'FR'
Kind = [Microsoft.Win32.RegistryValueKind]::String
}
[pscustomobject]@{
Name = 'Nation'
Value = '84'
Kind = [Microsoft.Win32.RegistryValueKind]::String
}
) -Action $Action
}
function Invoke-CleanMsEdgeWithTemporaryAllowUninstall {
param([Parameter(Mandatory = $true)][scriptblock]$Action)
$edgeUpdateDevPath = 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\EdgeUpdateDev'
$keyExisted = Test-Path -Path $edgeUpdateDevPath
if (-not $keyExisted) {
New-Item -Path $edgeUpdateDevPath -Force -ErrorAction Stop | Out-Null
}
try {
return Invoke-CleanMsWithTemporaryRegistryValues -Path $edgeUpdateDevPath -ValueEntry @(
[pscustomobject]@{