forked from DrEmpiricism/Optimize-Offline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Optimize-Offline.psm1
1997 lines (1950 loc) · 104 KB
/
Optimize-Offline.psm1
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
Using module .\Src\Offline-Resources.psm1
#Requires -RunAsAdministrator
#Requires -Version 5.1
#Requires -Module Dism
<#
===========================================================================
Created with: SAPIEN Technologies, Inc., PowerShell Studio 2019 v5.7.182
Created on: 11/20/2019 11:53 AM
Created by: BenTheGreat
Filename: Optimize-Offline.psm1
Version: 4.0.1.7
Last updated: 12/11/2020
-------------------------------------------------------------------------
Module Name: Optimize-Offline
===========================================================================
#>
Function Optimize-Offline
{
<#
.EXTERNALHELP Optimize-Offline-help.xml
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
HelpMessage = 'The full path to a Windows 10 Installation Media ISO, or a Windows 10 WIM, SWM or ESD file.')]
[ValidateScript( {
If ($PSItem.Exists -and $PSItem.Extension -eq '.ISO' -or $PSItem.Extension -eq '.WIM' -or $PSItem.Extension -eq '.SWM' -or $PSItem.Extension -eq '.ESD') { $true }
Else { Throw ('Invalid source path: "{0}"' -f $PSItem.FullName) }
})]
[IO.FileInfo]$SourcePath,
[Parameter(HelpMessage = 'Selectively or automatically deprovisions Windows Apps and removes their associated provisioning packages (.appx or .appxbundle).')]
[ValidateSet('Select', 'Whitelist', 'All')]
[String]$WindowsApps,
[Parameter(HelpMessage = 'Populates and outputs a Gridview list of System Apps for selective removal.')]
[Switch]$SystemApps,
[Parameter(HelpMessage = 'Populates and outputs a Gridview list of Capability Packages for selective removal.')]
[Switch]$Capabilities,
[Parameter(HelpMessage = 'Populates and outputs a Gridview list of Windows Cabinet File Packages for selective removal.')]
[Switch]$Packages,
[Parameter(HelpMessage = 'Populates and outputs a Gridview list of Windows Optional Features for selective disabling and enabling.')]
[Switch]$Features,
[Parameter(HelpMessage = 'Integrates the Developer Mode Feature into the image.')]
[Switch]$DeveloperMode,
[Parameter(HelpMessage = 'Integrates the Microsoft Windows Store and its required dependencies into the image.')]
[Switch]$WindowsStore,
[Parameter(HelpMessage = 'Integrates the Microsoft Edge HTML or Chromium Browser into the image.')]
[Switch]$MicrosoftEdge,
[Parameter(HelpMessage = 'Integrates the traditional Win32 Calculator into the image.')]
[Switch]$Win32Calc,
[Parameter(HelpMessage = 'Integrates the Windows Server Data Deduplication Feature into the image.')]
[Switch]$Dedup,
[Parameter(HelpMessage = 'Integrates the Microsoft Diagnostic and Recovery Toolset (DaRT 10) and Windows 10 Debugging Tools into Windows Setup and Windows Recovery.')]
[ValidateSet('Setup', 'Recovery')]
[String[]]$DaRT,
[Parameter(HelpMessage = 'Applies optimized settings to the image registry hives.')]
[Switch]$Registry,
[Parameter(HelpMessage = 'Integrates user-specific content added to the "Content/Additional" directory into the image when enabled within the hashtable.')]
[Hashtable]$Additional = @{ Setup = $false; Wallpaper = $false; SystemLogo = $false; LockScreen = $false; RegistryTemplates = $false; LayoutModification = $false; Unattend = $false; Drivers = $false; NetFx3 = $false },
[Parameter(HelpMessage = 'Creates a new bootable Windows Installation Media ISO.')]
[ValidateSet('Prompt', 'No-Prompt')]
[String]$ISO
)
Begin
{
#region Pre-Processing Block
$LocalScope | Add-Member -MemberType NoteProperty -Name Variables -Value (Get-Variable).Name -PassThru | Add-Member -MemberType NoteProperty -Name ErrorActionPreference -Value $ErrorActionPreference -PassThru | Add-Member -MemberType NoteProperty -Name ProgressPreference -Value $ProgressPreference
$ErrorActionPreference = 'SilentlyContinue'
$Global:ProgressPreference = 'SilentlyContinue'
$Host.UI.RawUI.BackgroundColor = 'Black'
Clear-Host
Test-Requirements
If (Get-WindowsImage -Mounted) { Dismount-Images; Clear-Host }
[Void](Clear-WindowsCorruptMountPoint)
$Global:Error.Clear()
#endregion Pre-Processing Block
}
Process
{
#region Create the Working File Structure
Set-Location -Path $OptimizeOffline.Directory
[Environment]::CurrentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath
@(Get-ChildItem -Path $OptimizeOffline.Directory -Filter OfflineTemp_* -Directory), (GetPath -Path $Env:SystemRoot -Child 'Logs\DISM\dism.log') | Purge -ErrorAction Ignore
Try
{
@($TempDirectory, $ImageFolder, $WorkFolder, $ScratchFolder, $LogFolder) | Create -ErrorAction Stop
}
Catch
{
$PSCmdlet.WriteWarning($OptimizeData.FailedToCreateWorkingFileStructure)
Get-ChildItem -Path $OptimizeOffline.Directory -Filter OfflineTemp_* -Directory | Purge -ErrorAction Ignore
Break
}
#endregion Create the Working File Structure
#region Media Export
Switch ($SourcePath.Extension)
{
'.ISO'
{
$ISOMount = (Mount-DiskImage -ImagePath $SourcePath.FullName -StorageType ISO -PassThru | Get-Volume).DriveLetter + ':'
[Void](Get-PSDrive)
If (!(Get-ChildItem -Path (GetPath -Path $ISOMount -Child sources) -Filter install* -File))
{
$PSCmdlet.WriteWarning($OptimizeData.InvalidWindowsInstallMedia -f $SourcePath.Name)
Do
{
[Void](Dismount-DiskImage -ImagePath $SourcePath.FullName)
}
While ((Get-DiskImage -ImagePath $SourcePath.FullName).Attached -eq $true)
$TempDirectory | Purge
Break
}
$Host.UI.RawUI.WindowTitle = ($OptimizeData.ExportingMedia -f $SourcePath.Name)
Write-Host ($OptimizeData.ExportingMedia -f $SourcePath.Name) -ForegroundColor Cyan
$ISOMedia = Create -Path (GetPath -Path $TempDirectory -Child $SourcePath.BaseName) -PassThru
$ISOMedia | Export-DataFile -File ISOMedia
ForEach ($Item In Get-ChildItem -Path $ISOMount -Recurse)
{
$ISOExport = $ISOMedia.FullName + $Item.FullName.Replace($ISOMount, $null)
Copy-Item -Path $Item.FullName -Destination $ISOExport
}
Do
{
[Void](Dismount-DiskImage -ImagePath $SourcePath.FullName)
}
While ((Get-DiskImage -ImagePath $SourcePath.FullName).Attached -eq $true)
If ((Get-ChildItem -Path (GetPath -Path $ISOMedia.FullName -Child sources) -Filter install* -File | Measure-Object).Count -gt 1 -and (Get-ChildItem -Path (GetPath -Path $ISOMedia.FullName -Child sources) -Filter install* -File | Select-Object -First 1).Extension -eq '.SWM')
{
Try
{
$InstallWim = Get-ChildItem -Path (GetPath -Path $ISOMedia.FullName -Child sources) -Filter install* -File | Select-Object -First 1 | Move-Item -Destination $ImageFolder -PassThru -ErrorAction Stop | Set-ItemProperty -Name IsReadOnly -Value $false -PassThru | Get-Item | Select-Object -ExpandProperty FullName
$SwmFiles = Get-ChildItem -Path (GetPath -Path $ISOMedia.FullName -Child sources) -Filter install* -File | Move-Item -Destination $ImageFolder -PassThru -ErrorAction Stop | Set-ItemProperty -Name IsReadOnly -Value $false -PassThru | Get-Item | Select-Object -ExpandProperty FullName
}
Catch [Management.Automation.ItemNotFoundException] { Break }
}
Else
{
Try { $InstallWim = Get-ChildItem -Path (GetPath -Path $ISOMedia.FullName -Child sources) -Filter install.* -File | Move-Item -Destination $ImageFolder -PassThru -ErrorAction Stop | Set-ItemProperty -Name IsReadOnly -Value $false -PassThru | Get-Item | Select-Object -ExpandProperty FullName }
Catch [Management.Automation.ItemNotFoundException] { Break }
}
If ($DaRT -or $Additional.ContainsValue($true))
{
If ($DaRT -and $DaRT.Contains('Setup') -or ($Additional.Drivers -and (Get-ChildItem -Path $OptimizeOffline.BootDrivers -Include *.inf -Recurse -Force)))
{
Try { $BootWim = Get-ChildItem -Path (GetPath -Path $ISOMedia.FullName -Child sources) -Filter boot.* -File | Move-Item -Destination $ImageFolder -PassThru -ErrorAction Stop | Set-ItemProperty -Name IsReadOnly -Value $false -PassThru | Get-Item | Select-Object -ExpandProperty FullName }
Catch [Management.Automation.ItemNotFoundException] { Break }
}
}
Break
}
Default
{
$Host.UI.RawUI.WindowTitle = ($OptimizeData.CopyingImage -f $SourcePath.Extension.TrimStart('.').ToUpper(), $SourcePath.DirectoryName)
Write-Host ($OptimizeData.CopyingImage -f $SourcePath.Extension.TrimStart('.').ToUpper(), $SourcePath.DirectoryName) -ForegroundColor Cyan
Try { $InstallWim = Get-ChildItem -Path $SourcePath.FullName -Filter $SourcePath.Name | Copy-Item -Destination $ImageFolder -PassThru -ErrorAction Stop | Rename-Item -NewName ('install' + $SourcePath.Extension) -PassThru | Set-ItemProperty -Name IsReadOnly -Value $false -PassThru | Get-Item | Select-Object -ExpandProperty FullName }
Catch [Management.Automation.ItemNotFoundException] { Break }
If ($SourcePath.Extension -eq '.SWM')
{
Try { $SwmFiles = Get-ChildItem -Path $SourcePath.DirectoryName -Filter "$($SourcePath.BaseName)*$($SourcePath.Extension)" -Exclude $SourcePath.Name -Recurse | Where-Object -Property Name -Like "$($SourcePath.BaseName)*.swm" | Copy-Item -Destination $ImageFolder -PassThru -ErrorAction Stop | Set-ItemProperty -Name IsReadOnly -Value $false -PassThru }
Catch [Management.Automation.ItemNotFoundException] { Break }
$I = 2
$SwmFiles = Get-ChildItem -Path $ImageFolder -Include $SwmFiles.PSChildName -File -Recurse | ForEach-Object -Process { Rename-Item -Path $PSItem -NewName ('install{0:D1}.swm' -f $I++) -PassThru }
}
If ($ISO) { Remove-Variable -Name ISO }
Break
}
}
If ([IO.File]::Exists($InstallWim))
{
Switch ([IO.Path]::GetExtension($InstallWim))
{
'.ESD' { $DynamicParams.ESD = $true; Break }
'.SWM' { $DynamicParams.SWM = $true; Break }
Default { $DynamicParams.WIM = $true; Break }
}
If ($BootWim)
{
If ([IO.File]::Exists($BootWim)) { $DynamicParams.BootImage = $true }
}
}
Else
{
$PSCmdlet.WriteWarning($OptimizeData.FailedToReturnInstallImage -f $ImageFolder)
$TempDirectory | Purge
Break
}
#endregion Media Export
#region Image and Metadata Validation
If ((Get-WindowsImage -ImagePath $InstallWim -ScratchDirectory $ScratchFolder -LogPath $DISMLog -LogLevel 1).Count -gt 1)
{
Do
{
$Host.UI.RawUI.WindowTitle = $OptimizeData.SelectWindowsEdition
$EditionList = Get-WindowsImage -ImagePath $InstallWim -ScratchDirectory $ScratchFolder -LogPath $DISMLog -LogLevel 1 | Select-Object -Property @{ Label = 'Index'; Expression = { ($PSItem.ImageIndex) } }, @{ Label = 'Name'; Expression = { ($PSItem.ImageName) } }, @{ Label = 'Size (GB)'; Expression = { '{0:N2}' -f ($PSItem.ImageSize / 1GB) } } | Out-GridView -Title "Select the Windows 10 Edition to Optimize." -OutputMode Single
}
While ($EditionList.Length -eq 0)
$ImageIndex = $EditionList.Index
}
Else { $ImageIndex = 1 }
Try
{
$Host.UI.RawUI.WindowTitle = "Validating Image Metadata."
$InstallInfo = $InstallWim | Get-ImageData -Index $ImageIndex -ErrorAction Stop
}
Catch
{
$PSCmdlet.WriteWarning($OptimizeData.FailedToRetrieveImageMetadata -f (GetPath -Path $InstallWim -Split Leaf))
$TempDirectory | Purge
Break
}
If ($InstallInfo.VersionTable.Major -ne 10)
{
$PSCmdlet.WriteWarning($OptimizeData.UnsupportedImageVersion -f $InstallInfo.Version)
$TempDirectory | Purge
Break
}
If ($InstallInfo.Architecture -ne 'amd64')
{
$PSCmdlet.WriteWarning($OptimizeData.UnsupportedImageArch -f $InstallInfo.Architecture)
$TempDirectory | Purge
Break
}
If ($InstallInfo.InstallationType.Contains('Server') -or $InstallInfo.InstallationType.Contains('WindowsPE'))
{
$PSCmdlet.WriteWarning($OptimizeData.UnsupportedImageType -f $InstallInfo.InstallationType)
$TempDirectory | Purge
Break
}
If ($InstallInfo.Build -ge '17134' -and $InstallInfo.Build -le '19041')
{
If ($InstallInfo.Name -like "*LTSC*")
{
$DynamicParams.LTSC = $true
If ($WindowsApps) { Remove-Variable -Name WindowsApps }
If ($Win32Calc.IsPresent) { $Win32Calc = ![Switch]::Present }
}
Else
{
If ($WindowsStore.IsPresent) { $WindowsStore = ![Switch]::Present }
If ($MicrosoftEdge.IsPresent -and $InstallInfo.Build -ge '18362')
{
If ($InstallInfo.Build -eq '18362') { $EdgeChromiumUBR = 833 }
Else { $EdgeChromiumUBR = 601 }
}
Else { $MicrosoftEdge = ![Switch]::Present }
}
If ($InstallInfo.Build -eq '17134' -and $DeveloperMode.IsPresent) { $DeveloperMode = ![Switch]::Present }
If ($InstallInfo.Language -ne $OptimizeOffline.Culture)
{
If ($MicrosoftEdge.IsPresent) { $MicrosoftEdge = ![Switch]::Present }
If ($Win32Calc.IsPresent) { $Win32Calc = ![Switch]::Present }
If ($Dedup.IsPresent) { $Dedup = ![Switch]::Present }
If ($DaRT) { Remove-Variable -Name DaRT }
}
}
Else
{
$PSCmdlet.WriteWarning($OptimizeData.UnsupportedImageBuild -f $InstallInfo.Build)
$TempDirectory | Purge
Break
}
#endregion Image and Metadata Validation
#region Image Preparation
If (!$DynamicParams.WIM)
{
$ExportToWimParams = @{
SourceImagePath = $InstallWim
SourceIndex = $ImageIndex
DestinationImagePath = '{0}\install.wim' -f $WorkFolder
CheckIntegrity = $true
ScratchDirectory = $ScratchFolder
LogPath = $DISMLog
LogLevel = 1
ErrorAction = 'Stop'
}
If ($DynamicParams.ESD) { $ExportToWimParams.CompressionType = 'Maximum' }
Else { $ExportToWimParams.SplitImageFilePattern = ('{0}\install*.swm' -f $ImageFolder) }
Try
{
$Host.UI.RawUI.WindowTitle = ($OptimizeData.ExportingInstallToWim -f (GetPath -Path $InstallWim -Split Leaf), (GetPath -Path ([IO.Path]::ChangeExtension($InstallWim, '.wim')) -Split Leaf))
Write-Host ($OptimizeData.ExportingInstallToWim -f (GetPath -Path $InstallWim -Split Leaf), (GetPath -Path ([IO.Path]::ChangeExtension($InstallWim, '.wim')) -Split Leaf)) -ForegroundColor Cyan
[Void](Export-WindowsImage @ExportToWimParams)
$ImageIndex = 1
}
Catch
{
$PSCmdlet.WriteWarning($OptimizeData.FailedExportingInstallToWim -f (GetPath -Path $InstallWim -Split Leaf), (GetPath -Path ([IO.Path]::ChangeExtension($InstallWim, '.wim')) -Split Leaf))
$TempDirectory | Purge
Break
}
Finally
{
$InstallWim | Purge
If ($DynamicParams.SWM) { $SwmFiles | Purge }
}
Try
{
$InstallWim = Get-ChildItem -Path $WorkFolder -Filter install.wim | Move-Item -Destination $ImageFolder -Force -PassThru | Select-Object -ExpandProperty FullName
$InstallInfo = $InstallWim | Get-ImageData -Index $ImageIndex -ErrorAction Stop
}
Catch
{
$PSCmdlet.WriteWarning($OptimizeData.FailedToRetrieveImageMetadata -f (GetPath -Path $InstallWim -Split Leaf))
$TempDirectory | Purge
Break
}
}
If ($Global:Error.Count -ne 0) { $Global:Error.Clear() }
Try
{
Log ($OptimizeData.SupportedImageBuild -f $InstallInfo.Build)
Start-Sleep 3
$OptimizeTimer = [Diagnostics.Stopwatch]::StartNew()
$InstallMount | Create -ErrorAction Stop
$MountInstallParams = @{
ImagePath = $InstallWim
Index = $ImageIndex
Path = $InstallMount
CheckIntegrity = $true
ScratchDirectory = $ScratchFolder
LogPath = $DISMLog
LogLevel = 1
ErrorAction = 'Stop'
}
Log ($OptimizeData.MountingImage -f $InstallInfo.Name)
[Void](Mount-WindowsImage @MountInstallParams)
RegHives -Load
Get-ItemProperty -Path "HKLM:\WIM_HKLM_SOFTWARE\Microsoft\Windows NT\CurrentVersion" | Export-DataFile -File CurrentVersion
RegHives -Unload
}
Catch
{
Log ($OptimizeData.FailedMountingImage -f $InstallInfo.Name) -Type Error -ErrorRecord $Error[0]
Stop-Optimize
}
If ($DaRT -or $Additional.ContainsValue($true))
{
If ($DaRT -and $DaRT.Contains('Recovery') -or ($Additional.Drivers -and (Get-ChildItem -Path $OptimizeOffline.RecoveryDrivers -Include *.inf -Recurse -Force)))
{
$WinREPath = GetPath -Path $InstallMount -Child 'Windows\System32\Recovery\winre.wim'
If (Test-Path -Path $WinREPath)
{
$RecoveryWim = Move-Item -Path $WinREPath -Destination $ImageFolder -Force -PassThru | Select-Object -ExpandProperty FullName
$DynamicParams.RecoveryImage = $true
}
}
}
If ($DynamicParams.BootImage)
{
Try
{
$BootInfo = $BootWim | Get-ImageData -Index 2 -ErrorAction Stop
}
Catch
{
Log ($OptimizeData.FailedToRetrieveImageMetadata -f (GetPath -Path $BootWim -Split Leaf)) -Type Error -ErrorRecord $Error[0]
Stop-Optimize
}
Try
{
$BootMount | Create -ErrorAction Stop
$MountBootParams = @{
Path = $BootMount
ImagePath = $BootWim
Index = 2
CheckIntegrity = $true
ScratchDirectory = $ScratchFolder
LogPath = $DISMLog
LogLevel = 1
ErrorAction = 'Stop'
}
Log ($OptimizeData.MountingImage -f $BootInfo.Name)
[Void](Mount-WindowsImage @MountBootParams)
}
Catch
{
Log ($OptimizeData.FailedMountingImage -f $BootInfo.Name) -Type Error -ErrorRecord $Error[0]
Stop-Optimize
}
}
If ($DynamicParams.RecoveryImage)
{
Try
{
$RecoveryInfo = $RecoveryWim | Get-ImageData -Index 1 -ErrorAction Stop
}
Catch
{
Log ($OptimizeData.FailedToRetrieveImageMetadata -f (GetPath -Path $RecoveryWim -Split Leaf)) -Type Error -ErrorRecord $Error[0]
Stop-Optimize
}
Try
{
$RecoveryMount | Create -ErrorAction Stop
$MountRecoveryParams = @{
Path = $RecoveryMount
ImagePath = $RecoveryWim
Index = 1
CheckIntegrity = $true
ScratchDirectory = $ScratchFolder
LogPath = $DISMLog
LogLevel = 1
ErrorAction = 'Stop'
}
Log ($OptimizeData.MountingImage -f $RecoveryInfo.Name)
[Void](Mount-WindowsImage @MountRecoveryParams)
}
Catch
{
Log ($OptimizeData.FailedMountingImage -f $RecoveryInfo.Name) -Type Error -ErrorRecord $Error[0]
Stop-Optimize
}
}
If ((Repair-WindowsImage -Path $InstallMount -CheckHealth -ScratchDirectory $ScratchFolder -LogPath $DISMLog -LogLevel 1).ImageHealthState -eq 'Healthy')
{
Log $OptimizeData.PreOptimizedImageHealthHealthy
Start-Sleep 3; Clear-Host
}
Else
{
Log $OptimizeData.PreOptimizedImageHealthCorrupted -Type Error
Stop-Optimize
}
#endregion Image Preparation
#region Provisioned App Package Removal
If ($WindowsApps -and (Get-AppxProvisionedPackage -Path $InstallMount -ScratchDirectory $ScratchFolder -LogPath $DISMLog -LogLevel 1).Count -gt 0)
{
$Host.UI.RawUI.WindowTitle = "Remove Provisioned App Packages."
$AppxPackages = Get-AppxProvisionedPackage -Path $InstallMount -ScratchDirectory $ScratchFolder -LogPath $DISMLog -LogLevel 1 | Select-Object -Property DisplayName, PackageName | Sort-Object -Property DisplayName
If ($InstallInfo.Build -eq '19041')
{
$AppxPackages = $AppxPackages | ForEach-Object -Process {
$DisplayName = $PSItem.DisplayName; $PackageName = $PSItem.PackageName
If ($DisplayName -eq 'Microsoft.549981C3F5F10') { $DisplayName = 'CortanaApp.View.App' }
[PSCustomObject]@{ DisplayName = $DisplayName; PackageName = $PackageName }
}
}
$RemovedAppxPackages = [Collections.Hashtable]::New()
Switch ($PSBoundParameters.WindowsApps)
{
'Select'
{
Try
{
$AppxPackages | Out-GridView -Title "Select the Provisioned App Packages to Remove." -PassThru | ForEach-Object -Process {
$RemoveAppxParams = @{
Path = $InstallMount
PackageName = $PSItem.PackageName
ScratchDirectory = $ScratchFolder
LogPath = $DISMLog
LogLevel = 1
ErrorAction = 'Stop'
}
Log ($OptimizeData.RemovingWindowsApp -f $PSItem.DisplayName)
[Void](Remove-AppxProvisionedPackage @RemoveAppxParams)
$RemovedAppxPackages.Add($PSItem.DisplayName, $PSItem.PackageName)
}
$DynamicParams.WindowsApps = $true
}
Catch
{
Log $OptimizeData.FailedRemovingWindowsApps -Type Error -ErrorRecord $Error[0]
Stop-Optimize
}
Break
}
'Whitelist'
{
If (Test-Path -Path $OptimizeOffline.AppxWhitelist)
{
Try
{
If ($InstallInfo.Build -eq '19041')
{
$WhitelistJSON = Get-Content -Path $OptimizeOffline.AppxWhitelist -Raw -ErrorAction Stop
If ($WhitelistJSON.Contains('Microsoft.549981C3F5F10')) { $WhitelistJSON = $WhitelistJSON.Replace('Microsoft.549981C3F5F10', 'CortanaApp.View.App') }
$WhitelistJSON = $WhitelistJSON | ConvertFrom-Json -ErrorAction Stop
}
Else
{
$WhitelistJSON = Get-Content -Path $OptimizeOffline.AppxWhitelist -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
}
$AppxPackages | ForEach-Object -Process {
If ($PSItem.DisplayName -notin $WhitelistJSON.DisplayName)
{
$RemoveAppxParams = @{
Path = $InstallMount
PackageName = $PSItem.PackageName
ScratchDirectory = $ScratchFolder
LogPath = $DISMLog
LogLevel = 1
ErrorAction = 'Stop'
}
Log ($OptimizeData.RemovingWindowsApp -f $PSItem.DisplayName)
[Void](Remove-AppxProvisionedPackage @RemoveAppxParams)
$RemovedAppxPackages.Add($PSItem.DisplayName, $PSItem.PackageName)
}
}
$DynamicParams.WindowsApps = $true
}
Catch
{
Log $OptimizeData.FailedRemovingWindowsApps -Type Error -ErrorRecord $Error[0]
Stop-Optimize
}
}
Break
}
'All'
{
Try
{
$AppxPackages | ForEach-Object -Process {
$RemoveAppxParams = @{
Path = $InstallMount
PackageName = $PSItem.PackageName
ScratchDirectory = $ScratchFolder
LogPath = $DISMLog
LogLevel = 1
ErrorAction = 'Stop'
}
Log ($OptimizeData.RemovingWindowsApp -f $PSItem.DisplayName)
[Void](Remove-AppxProvisionedPackage @RemoveAppxParams)
$RemovedAppxPackages.Add($PSItem.DisplayName, $PSItem.PackageName)
}
$DynamicParams.WindowsApps = $true
}
Catch
{
Log $OptimizeData.FailedRemovingWindowsApps -Type Error -ErrorRecord $Error[0]
Stop-Optimize
}
Break
}
}
$Host.UI.RawUI.WindowTitle = $null; Clear-Host
}
#endregion Provisioned App Package Removal
#region System App Removal
If ($SystemApps.IsPresent)
{
Clear-Host
$Host.UI.RawUI.WindowTitle = "Remove System Apps."
$PSCmdlet.WriteWarning($OptimizeData.SystemAppsWarning)
Start-Sleep 5
$InboxAppsKey = "HKLM:\WIM_HKLM_SOFTWARE\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\InboxApplications"
RegHives -Load
$InboxAppsPackages = Get-ChildItem -Path $InboxAppsKey -Name | ForEach-Object -Process {
$DisplayName = $PSItem.Split('_')[0]; $PackageName = $PSItem
If ($DisplayName -like '1527c705-839a-4832-9118-54d4Bd6a0c89') { $DisplayName = 'Microsoft.Windows.FilePicker' }
If ($DisplayName -like 'c5e2524a-ea46-4f67-841f-6a9465d9d515') { $DisplayName = 'Microsoft.Windows.FileExplorer' }
If ($DisplayName -like 'E2A4F912-2574-4A75-9BB0-0D023378592B') { $DisplayName = 'Microsoft.Windows.AppResolverUX' }
If ($DisplayName -like 'F46D4000-FD22-4DB4-AC8E-4E1DDDE828FE') { $DisplayName = 'Microsoft.Windows.AddSuggestedFoldersToLibarayDialog' }
[PSCustomObject]@{ DisplayName = $DisplayName; PackageName = $PackageName }
} | Sort-Object -Property DisplayName | Out-GridView -Title "Remove System Apps." -PassThru
If ($InboxAppsPackages)
{
Clear-Host
$RemovedSystemApps = [Collections.Hashtable]::New()
Try
{
$InboxAppsPackages | ForEach-Object -Process {
$PackageKey = (GetPath -Path $InboxAppsKey -Child $PSItem.PackageName) -replace 'HKLM:', 'HKLM'
Log ($OptimizeData.RemovingSystemApp -f $PSItem.DisplayName)
$RET = StartExe $REG -Arguments ('DELETE "{0}" /F' -f $PackageKey) -ErrorAction Stop
If ($RET -eq 1) { Log ($OptimizeData.FailedRemovingSystemApp -f $PSItem.DisplayName) -Type Error; Continue }
$RemovedSystemApps.Add($PSItem.DisplayName, $PSItem.PackageName)
Start-Sleep 2
}
$DynamicParams.SystemApps = $true
}
Catch
{
Log $OptimizeData.FailedRemovingSystemApps -Type Error -ErrorRecord $Error[0]
Stop-Optimize
}
Finally
{
RegHives -Unload
}
}
$Host.UI.RawUI.WindowTitle = $null; Clear-Host
}
#endregion System App Removal
#region Removed Package Clean-up
If ($DynamicParams.WindowsApps -or $DynamicParams.SystemApps)
{
Log $OptimizeData.RemovedPackageCleanup
If ($DynamicParams.WindowsApps)
{
If ($InstallInfo.Build -lt '19041')
{
If ((Get-AppxProvisionedPackage -Path $InstallMount -ScratchDirectory $ScratchFolder -LogPath $DISMLog -LogLevel 1).Count -eq 0) { Get-ChildItem -Path (GetPath -Path $InstallMount -Child 'Program Files\WindowsApps') -Force | Purge -Force }
Else { Get-ChildItem -Path (GetPath -Path $InstallMount -Child 'Program Files\WindowsApps') -Force | Where-Object -Property Name -In $RemovedAppxPackages.Values | Purge -Force }
}
Else
{
If ((Get-AppxProvisionedPackage -Path $InstallMount -ScratchDirectory $ScratchFolder -LogPath $DISMLog -LogLevel 1).Count -eq 0) { Get-ChildItem -Path (GetPath -Path $InstallMount -Child 'Program Files\WindowsApps') -Force | Purge -Force }
}
}
RegHives -Load
$Visibility = [Text.StringBuilder]::New('hide:')
If ($RemovedAppxPackages.'Microsoft.WindowsMaps')
{
RegKey -Path "HKLM:\WIM_HKLM_SYSTEM\Maps" -Name "AutoUpdateEnabled" -Value 0 -Type DWord
If (Test-Path -Path "HKLM:\WIM_HKLM_SYSTEM\ControlSet001\Services\MapsBroker") { RegKey -Path "HKLM:\WIM_HKLM_SYSTEM\ControlSet001\Services\MapsBroker" -Name "Start" -Value 4 -Type DWord }
[Void]$Visibility.Append('maps;maps-downloadmaps;')
}
If ($RemovedAppxPackages.'Microsoft.Wallet' -and (Test-Path -Path "HKLM:\WIM_HKLM_SYSTEM\ControlSet001\Services\WalletService")) { RegKey -Path "HKLM:\WIM_HKLM_SYSTEM\ControlSet001\Services\WalletService" -Name "Start" -Value 4 -Type DWord }
If ($RemovedAppxPackages.'Microsoft.XboxIdentityProvider' -and ($RemovedAppxPackages.Keys -like "*Xbox*").Count -gt 1 -or $RemovedSystemApps.'Microsoft.XboxGameCallableUI')
{
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Windows\GameDVR" -Name "AllowGameDVR" -Value 0 -Type DWord
RegKey -Path "HKLM:\WIM_HKCU\Software\Microsoft\Windows\CurrentVersion\GameDVR" -Name "AppCaptureEnabled" -Value 0 -Type DWord
RegKey -Path "HKLM:\WIM_HKCU\Software\Microsoft\Windows\CurrentVersion\GameDVR" -Name "AudioCaptureEnabled" -Value 0 -Type DWord
RegKey -Path "HKLM:\WIM_HKCU\Software\Microsoft\Windows\CurrentVersion\GameDVR" -Name "CursorCaptureEnabled" -Value 0 -Type DWord
RegKey -Path "HKLM:\WIM_HKCU\Software\Microsoft\GameBar" -Name "AutoGameModeEnabled" -Value 0 -Type DWord
RegKey -Path "HKLM:\WIM_HKCU\Software\Microsoft\GameBar" -Name "AllowAutoGameMode" -Value 0 -Type DWord
RegKey -Path "HKLM:\WIM_HKCU\Software\Microsoft\GameBar" -Name "UseNexusForGameBarEnabled" -Value 0 -Type DWord
RegKey -Path "HKLM:\WIM_HKCU\Software\Microsoft\GameBar" -Name "ShowStartupPanel" -Value 0 -Type DWord
RegKey -Path "HKLM:\WIM_HKCU\System\GameConfigStore" -Name "GameDVR_Enabled" -Value 0 -Type DWord
RegKey -Path "HKLM:\WIM_HKCU\System\GameConfigStore" -Name "GameDVR_FSEBehavior" -Value 2 -Type DWord
RegKey -Path "HKLM:\WIM_HKCU\System\GameConfigStore" -Name "GameDVR_FSEBehaviorMode" -Value 2 -Type DWord
@("xbgm", "XblAuthManager", "XblGameSave", "xboxgip", "XboxGipSvc", "XboxNetApiSvc") | ForEach-Object -Process { If (Test-Path -Path "HKLM:\WIM_HKLM_SYSTEM\ControlSet001\Services\$($PSItem)") { RegKey -Path "HKLM:\WIM_HKLM_SYSTEM\ControlSet001\Services\$($PSItem)" -Name "Start" -Value 4 -Type DWord } }
[Void]$Visibility.Append('gaming-gamebar;gaming-gamedvr;gaming-broadcasting;gaming-gamemode;gaming-xboxnetworking;quietmomentsgame;')
If ($InstallInfo.Build -lt '17763') { [Void]$Visibility.Append('gaming-trueplay;') }
}
If ($RemovedAppxPackages.'Microsoft.YourPhone' -or $RemovedSystemApps.'Microsoft.Windows.CallingShellApp')
{
[Void]$Visibility.Append('mobile-devices;mobile-devices-addphone;mobile-devices-addphone-direct;')
If (Test-Path -Path "HKLM:\WIM_HKLM_SYSTEM\ControlSet001\Services\PhoneSvc") { RegKey -Path "HKLM:\WIM_HKLM_SYSTEM\ControlSet001\Services\PhoneSvc" -Name "Start" -Value 4 -Type DWord }
}
If ($RemovedSystemApps.'Microsoft.MicrosoftEdge' -and !$MicrosoftEdge.IsPresent) { RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Microsoft\EdgeUpdate" -Name "DoNotUpdateToEdgeWithChromium" -Value 1 -Type DWord }
If ($RemovedSystemApps.'Microsoft.BioEnrollment')
{
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Biometrics" -Name "Enabled" -Value 0 -Type DWord
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Biometrics\Credential Provider" -Name "Enabled" -Value 0 -Type DWord
If (Test-Path -Path "HKLM:\WIM_HKLM_SYSTEM\ControlSet001\Services\WbioSrvc") { RegKey -Path "HKLM:\WIM_HKLM_SYSTEM\ControlSet001\Services\WbioSrvc" -Name "Start" -Value 4 -Type DWord }
}
If ($RemovedSystemApps.'Microsoft.Windows.SecureAssessmentBrowser')
{
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Microsoft\Windows\CurrentVersion\SecureAssessment" -Name "AllowScreenMonitoring" -Value 0 -Type DWord
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Microsoft\Windows\CurrentVersion\SecureAssessment" -Name "AllowTextSuggestions" -Value 0 -Type DWord
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Microsoft\Windows\CurrentVersion\SecureAssessment" -Name "RequirePrinting" -Value 0 -Type DWord
}
If ($RemovedSystemApps.'Microsoft.Windows.ContentDeliveryManager')
{
@("ContentDeliveryAllowed", "FeatureManagementEnabled", "OemPreInstalledAppsEnabled", "PreInstalledAppsEnabled", "PreInstalledAppsEverEnabled", "RotatingLockScreenEnabled",
"RotatingLockScreenOverlayEnabled", "SilentInstalledAppsEnabled", "SoftLandingEnabled", "SystemPaneSuggestionsEnabled", "SubscribedContentEnabled",
"SubscribedContent-202913Enabled", "SubscribedContent-202914Enabled", "SubscribedContent-280797Enabled", "SubscribedContent-280811Enabled", "SubscribedContent-280812Enabled",
"SubscribedContent-280813Enabled", "SubscribedContent-280814Enabled", "SubscribedContent-280815Enabled", "SubscribedContent-280810Enabled", "SubscribedContent-280817Enabled",
"SubscribedContent-310091Enabled", "SubscribedContent-310092Enabled", "SubscribedContent-310093Enabled", "SubscribedContent-310094Enabled", "SubscribedContent-314558Enabled",
"SubscribedContent-314559Enabled", "SubscribedContent-314562Enabled", "SubscribedContent-314563Enabled", "SubscribedContent-314566Enabled", "SubscribedContent-314567Enabled",
"SubscribedContent-338380Enabled", "SubscribedContent-338387Enabled", "SubscribedContent-338381Enabled", "SubscribedContent-338388Enabled", "SubscribedContent-338382Enabled",
"SubscribedContent-338389Enabled", "SubscribedContent-338386Enabled", "SubscribedContent-338393Enabled", "SubscribedContent-346480Enabled", "SubscribedContent-346481Enabled",
"SubscribedContent-353694Enabled", "SubscribedContent-353695Enabled", "SubscribedContent-353696Enabled", "SubscribedContent-353697Enabled", "SubscribedContent-353698Enabled",
"SubscribedContent-353699Enabled", "SubscribedContent-88000044Enabled", "SubscribedContent-88000045Enabled", "SubscribedContent-88000105Enabled", "SubscribedContent-88000106Enabled",
"SubscribedContent-88000161Enabled", "SubscribedContent-88000162Enabled", "SubscribedContent-88000163Enabled", "SubscribedContent-88000164Enabled", "SubscribedContent-88000165Enabled",
"SubscribedContent-88000166Enabled") | ForEach-Object -Process { RegKey -Path "HKLM:\WIM_HKCU\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" -Name $PSItem -Value 0 -Type DWord }
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Windows\CloudContent" -Name "DisableWindowsConsumerFeatures" -Value 1 -Type DWord
RegKey -Path "HKLM:\WIM_HKCU\Software\Policies\Microsoft\Microsoft\Windows\CurrentVersion\PushNotifications" -Name "NoCloudApplicationNotification" -Value 1 -Type DWord
}
If ($RemovedSystemApps.'Microsoft.Windows.SecHealthUI')
{
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Windows Defender" -Name "DisableAntiSpyware" -Value 1 -Type DWord
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Windows Defender\Spynet" -Name "SpyNetReporting" -Value 0 -Type DWord
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Windows Defender\Spynet" -Name "SubmitSamplesConsent" -Value 2 -Type DWord
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Windows Defender\MpEngine" -Name "MpEnablePus" -Value 0 -Type DWord
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Windows Defender\Reporting" -Name "DisableEnhancedNotifications" -Value 1 -Type DWord
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection" -Name "DisableBehaviorMonitoring" -Value 1 -Type DWord
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection" -Name "DisableRealtimeMonitoring" -Value 1 -Type DWord
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection" -Name "DisableOnAccessProtection" -Value 1 -Type DWord
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection" -Name "DisableScanOnRealtimeEnable" -Value 1 -Type DWord
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection" -Name "DisableIOAVProtection" -Value 1 -Type DWord
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Windows Defender\Policy Manager" -Name "AllowBehaviorMonitoring" -Value 2 -Type DWord
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Windows Defender\Policy Manager" -Name "AllowCloudProtection" -Value 0 -Type DWord
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Windows Defender\Policy Manager" -Name "AllowRealtimeMonitoring" -Value 0 -Type DWord
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Windows Defender\Policy Manager" -Name "SubmitSamplesConsent" -Value 2 -Type DWord
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Windows Defender\UX Configuration" -Name "Notification_Suppress" -Value 1 -Type DWord
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\MRT" -Name "DontOfferThroughWUAU" -Value 1 -Type DWord
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\MRT" -Name "DontReportInfectionInformation" -Value 1 -Type DWord
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Windows Defender Security Center\Systray" -Name "HideSystray" -Value 1 -Type DWord
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Microsoft\Windows Defender\Features" -Name "TamperProtection" -Value 0 -Type DWord -Force
RegKey -Path "HKLM:\WIM_HKCU\Software\Microsoft\Windows Security Health\State" -Name "AccountProtection_MicrosoftAccount_Disconnected" -Value 1 -Type DWord
RegKey -Path "HKLM:\WIM_HKCU\Software\Microsoft\Windows Security Health\State" -Name "AppAndBrowser_EdgeSmartScreenOff" -Value 0 -Type DWord
RegKey -Path "HKLM:\WIM_HKCU\Software\Microsoft\Windows\CurrentVersion\AppHost" -Name "SmartScreenEnabled" -Value "Off" -Type String
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer" -Name "SmartScreenEnabled" -Value "Off" -Type String
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Explorer" -Name "SmartScreenEnabled" -Value "Off" -Type String
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Microsoft\Windows\CurrentVersion\AppHost" -Name "EnableWebContentEvaluation" -Value 0 -Type DWord
RegKey -Path "HKLM:\WIM_HKCU\Software\Microsoft\Windows\CurrentVersion\AppHost" -Name "EnableWebContentEvaluation" -Value 0 -Type DWord
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Windows\System" -Name "EnableSmartScreen" -Value 0 -Type DWord
@("SecurityHealthService", "WinDefend", "WdNisSvc", "WdNisDrv", "WdBoot", "WdFilter", "Sense") | ForEach-Object -Process { If (Test-Path -Path "HKLM:\WIM_HKLM_SYSTEM\ControlSet001\Services\$($PSItem)") { RegKey -Path "HKLM:\WIM_HKLM_SYSTEM\ControlSet001\Services\$($PSItem)" -Name "Start" -Value 4 -Type DWord } }
@("HKLM:\WIM_HKLM_SOFTWARE\Classes\*\shellex\ContextMenuHandlers\EPP", "HKLM:\WIM_HKLM_SOFTWARE\Classes\Directory\shellex\ContextMenuHandlers\EPP", "HKLM:\WIM_HKLM_SOFTWARE\Classes\Drive\shellex\ContextMenuHandlers\EPP",
"HKLM:\WIM_HKLM_SYSTEM\ControlSet001\Control\WMI\AutoLogger\DefenderApiLogger", "HKLM:\WIM_HKLM_SYSTEM\ControlSet001\Control\WMI\AutoLogger\DefenderAuditLogger") | Purge
Remove-KeyProperty -Path "HKLM:\WIM_HKLM_SOFTWARE\Microsoft\Windows\CurrentVersion\Run" -Name "SecurityHealth"
If (!$DynamicParams.LTSC -or $MicrosoftEdge.IsPresent)
{
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\MicrosoftEdge\PhishingFilter" -Name "EnabledV9" -Value 0 -Type DWord
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\WOW6432Node\Policies\Microsoft\MicrosoftEdge\PhishingFilter" -Name "EnabledV9" -Value 0 -Type DWord
}
If ($InstallInfo.Build -ge '17763')
{
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Windows Defender\SmartScreen" -Name "ConfigureAppInstallControlEnabled" -Value 1 -Type DWord
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Windows Defender\SmartScreen" -Name "ConfigureAppInstallControl" -Value "Anywhere" -Type String
}
[Void]$Visibility.Append('windowsdefender;')
$DynamicParams.SecHealthUI = $true
}
If ($Visibility.Length -gt 5)
{
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer" -Name "SettingsPageVisibility" -Value $Visibility.ToString().TrimEnd(';') -Type String
RegKey -Path "HKLM:\WIM_HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer" -Name "SettingsPageVisibility" -Value $Visibility.ToString().TrimEnd(';') -Type String
}
RegHives -Unload
If ($DynamicParams.SecHealthUI -and (Get-WindowsOptionalFeature -Path $InstallMount -FeatureName Windows-Defender-Default-Definitions -ScratchDirectory $ScratchFolder -LogPath $DISMLog -LogLevel 1 | Where-Object -Property State -EQ Enabled))
{
Try
{
$DisableDefenderOptionalFeature = @{
Path = $InstallMount
FeatureName = 'Windows-Defender-Default-Definitions'
Remove = $true
NoRestart = $true
ScratchDirectory = $ScratchFolder
LogPath = $DISMLog
LogLevel = 1
ErrorAction = 'Stop'
}
Log $OptimizeData.DisablingDefenderOptionalFeature
[Void](Disable-WindowsOptionalFeature @DisableDefenderOptionalFeature)
}
Catch
{
Log $OptimizeData.FailedDisablingDefenderOptionalFeature -Type Error -ErrorRecord $Error[0]
Start-Sleep 3
}
}
}
#endregion Removed Package Clean-up
#region Import Custom App Associations
If (Test-Path -Path $OptimizeOffline.CustomAppAssociations)
{
Log $OptimizeData.ImportingCustomAppAssociations
$RET = StartExe $DISM -Arguments ('/Image:"{0}" /Import-DefaultAppAssociations:"{1}" /ScratchDir:"{2}" /LogPath:"{3}" /LogLevel:1' -f $InstallMount, $OptimizeOffline.CustomAppAssociations, $ScratchFolder, $DISMLog)
If ($RET -ne 0) { Log $OptimizeData.FailedImportingCustomAppAssociations -Type Error; Start-Sleep 3 }
}
#endregion Import Custom App Associations
#region Windows Capability and Cabinet File Package Removal
If ($Capabilities.IsPresent)
{
Clear-Host
$Host.UI.RawUI.WindowTitle = "Remove Windows Capabilities."
$WindowsCapabilities = Get-WindowsCapability -Path $InstallMount -ScratchDirectory $ScratchFolder -LogPath $DISMLog -LogLevel 1 | Where-Object { $PSItem.Name -notlike "*Language.Basic*" -and $PSItem.Name -notlike "*TextToSpeech*" -and $PSItem.State -eq 'Installed' } | Select-Object -Property Name, State | Sort-Object -Property Name | Out-GridView -Title "Remove Windows Capabilities." -PassThru
If ($WindowsCapabilities)
{
Try
{
$WindowsCapabilities | ForEach-Object -Process {
$RemoveCapabilityParams = @{
Path = $InstallMount
Name = $PSItem.Name
ScratchDirectory = $ScratchFolder
LogPath = $DISMLog
LogLevel = 1
ErrorAction = 'Stop'
}
Log ($OptimizeData.RemovingWindowsCapability -f $PSItem.Name.Split('~')[0])
[Void](Remove-WindowsCapability @RemoveCapabilityParams)
}
$DynamicParams.Capabilities = $true
}
Catch
{
Log $OptimizeData.FailedRemovingWindowsCapabilities -Type Error -ErrorRecord $Error[0]
Stop-Optimize
}
$Host.UI.RawUI.WindowTitle = $null; Clear-Host
}
}
If ($Packages.IsPresent)
{
Clear-Host
$Host.UI.RawUI.WindowTitle = "Remove Windows Packages."
$WindowsPackages = Get-WindowsPackage -Path $InstallMount -ScratchDirectory $ScratchFolder -LogPath $DISMLog -LogLevel 1 | Where-Object { $PSItem.ReleaseType -eq 'OnDemandPack' -or $PSItem.ReleaseType -eq 'LanguagePack' -or $PSItem.ReleaseType -eq 'FeaturePack' -and $PSItem.PackageName -notlike "*20H2Enablement*" -and $PSItem.PackageName -notlike "*LanguageFeatures-Basic*" -and $PSItem.PackageName -notlike "*LanguageFeatures-TextToSpeech*" -and $PSItem.PackageState -eq 'Installed' } | Select-Object -Property PackageName, ReleaseType | Sort-Object -Property PackageName | Out-GridView -Title "Remove Windows Packages." -PassThru
If ($WindowsPackages)
{
Try
{
$WindowsPackages | ForEach-Object -Process {
$RemovePackageParams = @{
Path = $InstallMount
PackageName = $PSItem.PackageName
NoRestart = $true
ScratchDirectory = $ScratchFolder
LogPath = $DISMLog
LogLevel = 1
ErrorAction = 'Stop'
}
Log ($OptimizeData.RemovingWindowsPackage -f $PSItem.PackageName.Replace('Package', $null).Split('~')[0].TrimEnd('-'))
[Void](Remove-WindowsPackage @RemovePackageParams)
}
$DynamicParams.Packages = $true
}
Catch
{
Log $OptimizeData.FailedRemovingWindowsPackages -Type Error -ErrorRecord $Error[0]
Stop-Optimize
}
$Host.UI.RawUI.WindowTitle = $null; Clear-Host
}
}
#endregion Windows Capability and Cabinet File Package Removal
#region Disable Unsafe Optional Features
<#
@('SMB1Protocol', 'MicrosoftWindowsPowerShellV2Root') | ForEach-Object -Process { Get-WindowsOptionalFeature -Path $InstallMount -FeatureName $PSItem -ScratchDirectory $ScratchFolder -LogPath $DISMLog -LogLevel 1 | Where-Object -Property State -EQ Disabled | Disable-WindowsOptionalFeature -Path $InstallMount -Remove -NoRestart -ScratchDirectory $ScratchFolder -LogPath $DISMLog -LogLevel 1 }
#>
ForEach ($Feature In @('SMB1Protocol', 'MicrosoftWindowsPowerShellV2Root'))
{
If (Get-WindowsOptionalFeature -Path $InstallMount -FeatureName $Feature -ScratchDirectory $ScratchFolder -LogPath $DISMLog -LogLevel 1 | Where-Object -Property State -EQ Enabled)
{
Try
{
$DisableOptionalFeatureParams = @{
Path = $InstallMount
FeatureName = $Feature
Remove = $true
NoRestart = $true
ScratchDirectory = $ScratchFolder
LogPath = $DISMLog
LogLevel = 1
ErrorAction = 'Stop'
}
Log ($OptimizeData.DisablingUnsafeOptionalFeature -f $Feature)
[Void](Disable-WindowsOptionalFeature @DisableOptionalFeatureParams)
}
Catch
{
Log ($OptimizeData.FailedDisablingUnsafeOptionalFeature -f $Feature) -Type Error -ErrorRecord $Error[0]
Stop-Optimize
}
}
}
#endregion Disable Unsafe Optional Features
#region Disable/Enable Optional Features
If ($Features.IsPresent)
{
Clear-Host
$Host.UI.RawUI.WindowTitle = "Disable Optional Features."
$DisableFeatures = Get-WindowsOptionalFeature -Path $InstallMount -ScratchDirectory $ScratchFolder -LogPath $DISMLog -LogLevel 1 | Where-Object -Property State -EQ Enabled | Select-Object -Property FeatureName, State | Sort-Object -Property FeatureName | Out-GridView -Title "Disable Optional Features." -PassThru
If ($DisableFeatures)
{
Try
{
$DisableFeatures | ForEach-Object -Process {
$DisableFeatureParams = @{
Path = $InstallMount
FeatureName = $PSItem.FeatureName
Remove = $true
NoRestart = $true
ScratchDirectory = $ScratchFolder
LogPath = $DISMLog
LogLevel = 1
ErrorAction = 'Stop'
}
Log ($OptimizeData.DisablingOptionalFeature -f $PSItem.FeatureName)
[Void](Disable-WindowsOptionalFeature @DisableFeatureParams)
}
$DynamicParams.DisabledOptionalFeatures = $true
}
Catch
{
Log $OptimizeData.FailedDisablingOptionalFeatures -Type Error -ErrorRecord $Error[0]
Stop-Optimize
}
$Host.UI.RawUI.WindowTitle = $null; Clear-Host
}
Clear-Host
$Host.UI.RawUI.WindowTitle = "Enable Optional Features."
$EnableFeatures = Get-WindowsOptionalFeature -Path $InstallMount -ScratchDirectory $ScratchFolder -LogPath $DISMLog -LogLevel 1 | Where-Object { $PSItem.FeatureName -notlike "SMB1Protocol*" -and $PSItem.FeatureName -ne "Windows-Defender-Default-Definitions" -and $PSItem.FeatureName -notlike "MicrosoftWindowsPowerShellV2*" -and $PSItem.State -eq "Disabled" } | Select-Object -Property FeatureName, State | Sort-Object -Property FeatureName | Out-GridView -Title "Enable Optional Features." -PassThru
If ($EnableFeatures)
{
Try
{
$EnableFeatures | ForEach-Object -Process {
$EnableFeatureParams = @{
Path = $InstallMount
FeatureName = $PSItem.FeatureName
All = $true
LimitAccess = $true
NoRestart = $true
ScratchDirectory = $ScratchFolder
LogPath = $DISMLog
LogLevel = 1
ErrorAction = 'Stop'
}
Log ($OptimizeData.EnablingOptionalFeature -f $PSItem.FeatureName)
[Void](Enable-WindowsOptionalFeature @EnableFeatureParams)
}
$DynamicParams.EnabledOptionalFeatures = $true
}
Catch
{
Log $OptimizeData.FailedEnablingOptionalFeatures -Type Error -ErrorRecord $Error[0]
Stop-Optimize
}
$Host.UI.RawUI.WindowTitle = $null; Clear-Host
}
}
#endregion Disable/Enable Optional Features
#region DeveloperMode Integration
If ($DeveloperMode.IsPresent -and (Test-Path -Path $OptimizeOffline.DevMode -Filter *DeveloperMode-Desktop-Package*.cab) -and !(Get-WindowsPackage -Path $InstallMount -ScratchDirectory $ScratchFolder -LogPath $DISMLog -LogLevel 1 | Where-Object -Property PackageName -Like *DeveloperMode*))
{
$DevModeExpand = Create -Path (GetPath -Path $WorkFolder -Child DeveloperMode) -PassThru
[Void](StartExe $EXPAND -Arguments ('"{0}" F:* "{1}"' -f (GetPath -Path $OptimizeOffline.DevMode -Child "Microsoft-OneCore-DeveloperMode-Desktop-Package~$($InstallInfo.Architecture)~~10.0.$($InstallInfo.Build).1.cab"), $DevModeExpand.FullName))
Try
{
Log $OptimizeData.IntegratingDeveloperMode
$RET = StartExe $DISM -Arguments ('/Image:"{0}" /Add-Package /PackagePath:"{1}" /ScratchDir:"{2}" /LogPath:"{3}" /LogLevel:1' -f $InstallMount, (GetPath -Path $DevModeExpand.FullName -Child update.mum), $ScratchFolder, $DISMLog)
If ($RET -eq 0) { $DynamicParams.DeveloperMode = $true }
Else { Throw }
}
Catch
{
Log $OptimizeData.FailedIntegratingDeveloperMode -Type Error
Stop-Optimize
}
If ($DynamicParams.DeveloperMode)
{
RegHives -Load
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock" -Name "AllowAllTrustedApps" -Value 1 -Type DWord
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock" -Name "AllowDevelopmentWithoutDevLicense" -Value 1 -Type DWord
RegHives -Unload
}
}
#endregion DeveloperMode Integration
#region Windows Store Integration
If ($WindowsStore.IsPresent -and (Test-Path -Path $OptimizeOffline.WindowsStore -Filter Microsoft.WindowsStore*.appxbundle) -and !(Get-AppxProvisionedPackage -Path $InstallMount -ScratchDirectory $ScratchFolder -LogPath $DISMLog -LogLevel 1 | Where-Object -Property DisplayName -EQ Microsoft.WindowsStore))
{
Log $OptimizeData.IntegratingWindowsStore
$StoreBundle = Get-ChildItem -Path $OptimizeOffline.WindowsStore -Filter Microsoft.WindowsStore*.appxbundle -File | Select-Object -ExpandProperty FullName
$PurchaseBundle = Get-ChildItem -Path $OptimizeOffline.WindowsStore -Filter Microsoft.StorePurchaseApp*.appxbundle -File | Select-Object -ExpandProperty FullName
$XboxBundle = Get-ChildItem -Path $OptimizeOffline.WindowsStore -Filter Microsoft.XboxIdentityProvider*.appxbundle -File | Select-Object -ExpandProperty FullName
$InstallerBundle = Get-ChildItem -Path $OptimizeOffline.WindowsStore -Filter Microsoft.DesktopAppInstaller*.appxbundle -File | Select-Object -ExpandProperty FullName
$StoreLicense = Get-ChildItem -Path $OptimizeOffline.WindowsStore -Filter Microsoft.WindowsStore*.xml -File | Select-Object -ExpandProperty FullName
$PurchaseLicense = Get-ChildItem -Path $OptimizeOffline.WindowsStore -Filter Microsoft.StorePurchaseApp*.xml -File | Select-Object -ExpandProperty FullName
$XboxLicense = Get-ChildItem -Path $OptimizeOffline.WindowsStore -Filter Microsoft.XboxIdentityProvider*.xml -File | Select-Object -ExpandProperty FullName
$InstallerLicense = Get-ChildItem -Path $OptimizeOffline.WindowsStore -Filter Microsoft.DesktopAppInstaller*.xml -File | Select-Object -ExpandProperty FullName
$DependencyPackages = [Collections.Generic.List[String]]::New()
$DependencyPackages = Get-ChildItem -Path $OptimizeOffline.WindowsStore -Filter Microsoft.VCLibs*.appx -File | Select-Object -ExpandProperty FullName
$DependencyPackages += Get-ChildItem -Path $OptimizeOffline.WindowsStore -Filter *Native.Framework*.appx -File | Select-Object -ExpandProperty FullName
$DependencyPackages += Get-ChildItem -Path $OptimizeOffline.WindowsStore -Filter *Native.Runtime*.appx -File | Select-Object -ExpandProperty FullName
If (!$DynamicParams.DeveloperMode)
{
RegHives -Load
RegKey -Path "HKLM:\WIM_HKLM_SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock" -Name "AllowAllTrustedApps" -Value 1 -Type DWord
RegHives -Unload
}
Try
{
$StorePackage = @{
Path = $InstallMount
PackagePath = $StoreBundle
DependencyPackagePath = $DependencyPackages
LicensePath = $StoreLicense
ScratchDirectory = $ScratchFolder
LogPath = $DISMLog
LogLevel = 1
ErrorAction = 'Stop'
}
[Void](Add-AppxProvisionedPackage @StorePackage)
$PurchasePackage = @{
Path = $InstallMount
PackagePath = $PurchaseBundle