forked from DrEmpiricism/Optimize-Offline
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOptimize-Offline.ps1
More file actions
2996 lines (2914 loc) · 225 KB
/
Optimize-Offline.ps1
File metadata and controls
2996 lines (2914 loc) · 225 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 -RunAsAdministrator
#Requires -Version 5
<#
.SYNOPSIS
Optimize-Offline is a Windows Image (WIM) optimization script designed for 64-bit Windows 10 builds RS2-RS5.
.DESCRIPTION
Primary focus' are the removal of unnecessary bloat, enhanced privacy, cleaner aesthetics, increased performance and a significantly better user experience.
.PARAMETER ImagePath
The full path to a Windows Installation ISO or an install WIM file.
.PARAMETER Index
If using a multi-index image, specify the index of the image.
.PARAMETER Build
The build number of the Windows image being optimized.
.PARAMETER MetroApps
Select = Populates and outputs a Gridview list of all Provisioned Application Packages for selective removal.
All = Automatically removes all Provisioned Application Packages.
.PARAMETER SystemApps
Populates and outputs a Gridview list of all System Applications for selective removal.
.PARAMETER Packages
Populates and outputs a Gridview list of all installed Windows Capability Packages for selective removal.
.PARAMETER Features
Populates and outputs a Gridview list of all enabled Windows Optional Features for selective disabling.
.PARAMETER OneDrive
Performs a complete removal of Microsoft OneDrive, its associated directories and registry keys.
.PARAMETER Registry
Applies optimized registry values into the registry hives of the image.
.PARAMETER DaRT
Applies the Microsoft Diagnostic and Recovery Toolset (DaRT 10) and Windows 10 Debugging Tools to Windows Setup and Windows Recovery.
.PARAMETER Drivers
The full path to a collection of driver packages, or a driver .inf file, to be injected into the image.
.PARAMETER NetFx3
Either a boolean value of $true or the full path to the .NET Framework 3 payload packages to be applied to the image.
.PARAMETER NoSetup
Excludes the Setup and Post Installation Script(s) from being applied to the image.
.EXAMPLE
.\Optimize-Offline.ps1 -ImagePath "D:\WIM Files\Win10Pro\Win10Pro_Full.iso" -Index 3 -Build 16299 -MetroApps "Select" -SystemApps -Packages -OneDrive -Registry "Default" -DaRT -NetFx3 $true -Drivers "E:\Driver Folder"
.EXAMPLE
.\Optimize-Offline.ps1 -ImagePath "D:\Win Images\install.wim" -Build 17134 -MetroApps "All" -SystemApps -Packages -Features -OneDrive -NetFx3 "C:\Windows 10\sources\sxs" -NoSetup
.NOTES
In order for Microsoft DaRT 10 to be applied to both the Windows Setup Boot Image (boot.wim), and the default Recovery Image (winre.wim), the source image used must be a full Windows 10 ISO.
A full Windows 10 ISO, along with the use of the -DaRT switch, will enable the script to extract the boot.wim along with the install.wim during the start of the script.
If only a WIM file is used with the -DaRT switch, DaRT 10 will only be applied to the default Recovery Image (winre.wim).
.NOTES
===========================================================================
Created with: SAPIEN Technologies, Inc., PowerShell Studio 2018 v5.5.150
Created on: 11/30/2017
Created by: BenTheGreat
Contact: Ben@Omnic.Tech
Filename: Optimize-Offline.ps1
Version: 3.1.1.7
Last updated: 10/06/2018
===========================================================================
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true,
HelpMessage = 'The full path to a Windows Installation ISO or an install WIM file.')]
[ValidateScript( {
If ((Test-Path $(Resolve-Path -Path $_) -PathType Leaf) -and ($_ -like "*.iso")) { $_ }
ElseIf ((Test-Path $(Resolve-Path -Path $_) -PathType Leaf) -and ($_ -like "*.wim")) { $_ }
Else { Throw "Invalid image path: $_" }
})]
[Alias('ISO', 'WIM')]
[string]$ImagePath,
[Parameter(HelpMessage = 'If using a multi-index image, specify the index of the image.')]
[ValidateRange(1, 16)]
[int]$Index = 1,
[Parameter(Mandatory = $true,
HelpMessage = 'The build number of the Windows image being optimized.')]
[ValidateRange(15063, 18204)]
[int]$Build,
[Parameter(HelpMessage = 'Populates and outputs a Gridview list of all Provisioned Application Packages for selective removal or performs a complete removal of all packages.')]
[ValidateSet('Select', 'All')]
[Alias('Appx')]
[string]$MetroApps = 'Select',
[Parameter(HelpMessage = 'Populates and outputs a Gridview list of all System Applications for selective removal.')]
[switch]$SystemApps,
[Parameter(HelpMessage = 'Populates and outputs a Gridview list of all installed Windows Capability Packages for selective removal.')]
[switch]$Packages,
[Parameter(HelpMessage = 'Populates and outputs a Gridview list of all enabled Windows Optional Features for selective disabling.')]
[switch]$Features,
[Parameter(HelpMessage = 'Performs a complete removal of Microsoft OneDrive, its associated directories and registry keys.')]
[switch]$OneDrive,
[Parameter(HelpMessage = 'Applies optimized registry values into the registry hives of the image.')]
[switch]$Registry,
[Parameter(HelpMessage = 'Applies the Microsoft Diagnostic and Recovery Toolset (DaRT 10) and Windows 10 Debugging Tools to Windows Setup and Windows Recovery.')]
[switch]$DaRT,
[Parameter(HelpMessage = 'The full path to a collection of driver packages, or a driver .inf file, to be injected into the image.')]
[ValidateScript( { Test-Path $(Resolve-Path -Path $_) })]
[string]$Drivers,
[Parameter(HelpMessage = 'Either a boolean value of $true or the full path to the .NET Framework 3 payload packages to be applied to the image.')]
[string]$NetFx3,
[Parameter(HelpMessage = 'Excludes the Setup and Post Installation Script(s) from being applied to the image.')]
[switch]$NoSetup
)
#region Script Variables
$Host.UI.RawUI.BackgroundColor = "Black"; Clear-Host
$ProgressPreference = 'SilentlyContinue'
$TimeStamp = Get-Date -Format "MM-dd-yyyy hh:mm:ss tt"
$OfflineBackupDirectory = $WorkFolder + '\' + "OfflineRegistryBackup_" + $(Get-Date -Format "MM-dd-yyyy")
$BkpTimestamp = Get-Date -Format "[M.dd.yy-hh.mm.ss]"
$OScript = "Optimize-Offline"
$LogFile = "$Env:TEMP\Optimize-Offline.log"
$DISMLog = "$Env:TEMP\DISM.log"
#endregion Script Variables
#region Helper Functions
Function Test-Admin
{
$CurrentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
$IsAdmin = $CurrentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
Write-Verbose "IsUserAdmin? $IsAdmin"
Return $IsAdmin
}
Function Out-Log
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true)]
[string]$Content,
[ValidateSet('Info', 'Error')]
[string]$Level = "Info"
)
Switch ($Level)
{
'Info' { Write-Host $Content -ForegroundColor Cyan; $LogLevel = "INFO:" }
'Error' { Write-Host $Content -ForegroundColor Red; $LogLevel = "ERROR:" }
}
Add-Content -Path $LogFile -Value "$LogLevel $Content"
}
Function Invoke-ProcessPrivilege
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true)]
[string]$Privilege,
[int]$Process = $PID,
[switch]$Disable
)
Begin
{
Add-Type @'
using System;
using System.Runtime.InteropServices;
using System.ComponentModel;
public class AccessTokens
{
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool LookupPrivilegeValue(
string host,
string name,
ref long luid
);
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
static extern bool AdjustTokenPrivileges(
IntPtr token,
bool disall,
ref TOKEN_PRIVILEGES newst,
int len,
IntPtr prev,
IntPtr relen
);
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
static extern bool OpenProcessToken(
IntPtr curProcess,
int acc,
ref IntPtr processToken
);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CloseHandle(
IntPtr handle
);
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct TOKEN_PRIVILEGES
{
public int Count;
public long Luid;
public int Attr;
}
internal const int SE_PRIVILEGE_DISABLED = 0x00000000;
internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
internal const int TOKEN_QUERY = 0x00000008;
internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
public static void AdjustPrivilege(IntPtr curProcess, string privilege, bool enable)
{
var processToken = IntPtr.Zero;
if (!OpenProcessToken(curProcess, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref processToken))
{
throw new Win32Exception();
}
try
{
var privileges = new TOKEN_PRIVILEGES
{
Count = 1,
Luid = 0,
Attr = enable ? SE_PRIVILEGE_ENABLED : SE_PRIVILEGE_DISABLED,
};
if (!LookupPrivilegeValue(
null,
privilege,
ref privileges.Luid))
{
throw new Win32Exception();
}
if (!AdjustTokenPrivileges(
processToken,
false,
ref privileges,
0,
IntPtr.Zero,
IntPtr.Zero))
{
throw new Win32Exception();
}
}
finally
{
CloseHandle(
processToken
);
}
}
}
'@
$CurProcess = Get-Process -Id $Process
}
Process
{
[AccessTokens]::AdjustPrivilege($CurProcess.Handle, $Privilege, !$Disable)
}
End
{
$CurProcess.Close()
}
}
Function Set-RegistryOwner
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
Position = 0)]
[string]$SubKey
)
Begin
{
$TakeOwnership = "SeTakeOwnershipPrivilege"
}
Process
{
$TakeOwnership | Invoke-ProcessPrivilege
$Key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($SubKey, [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree, [System.Security.AccessControl.RegistryRights]::TakeOwnership)
$ACL = $Key.GetAccessControl([System.Security.AccessControl.AccessControlSections]::None)
$Admin = ((New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-544')).Translate([System.Security.Principal.NTAccount]))
$ACL.SetOwner($Admin)
$Key.SetAccessControl($ACL)
$TakeOwnership | Invoke-ProcessPrivilege -Disable
$ACL = $Key.GetAccessControl()
$ACL.SetAccessRule((New-Object System.Security.AccessControl.RegistryAccessRule($Admin, "FullControl", "ContainerInherit", "None", "Allow")))
$Key.SetAccessControl($ACL)
$Key.Close()
}
}
Function Set-FileOwnership
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true)]
[string]$Path
)
Begin
{
$TakeOwnership = "SeTakeOwnershipPrivilege"
}
Process
{
$TakeOwnership | Invoke-ProcessPrivilege
$ACL = Get-Acl -Path $Path
$Admin = ((New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-544')).Translate([System.Security.Principal.NTAccount]))
$ACL.SetOwner($Admin)
$ACL.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule($Admin, "FullControl", "None", "None", "Allow")))
$TakeOwnership | Invoke-ProcessPrivilege -Disable
$ACL | Set-Acl -Path $Path
}
}
Function Set-FolderOwnership
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true)]
[string]$Path
)
Set-FileOwnership -Path $Path
ForEach ($Object In Get-ChildItem -Path $Path -Recurse -Force)
{
If (Test-Path -Path $Object -PathType Container)
{
Set-FolderOwnership -Path $Object.FullName
}
Else
{
Set-FileOwnership -Path $Object.FullName
}
}
}
Function New-WorkDirectory
{
$WorkDir = [System.IO.Directory]::CreateDirectory((Join-Path -Path $ScriptDirectory -ChildPath "WorkOffline_$(Get-Random)"))
$WorkDir = Get-Item -LiteralPath $ScriptDirectory\$WorkDir -Force
$WorkDir
}
Function New-ScratchDirectory
{
$TempDir = [System.IO.Directory]::CreateDirectory((Join-Path -Path $ScriptDirectory -ChildPath "TempOffline_$(Get-Random)"))
$TempDir = Get-Item -LiteralPath $ScriptDirectory\$TempDir -Force
$TempDir
}
Function New-ImageDirectory
{
$ImageDir = [System.IO.Directory]::CreateDirectory((Join-Path -Path $ScriptDirectory -ChildPath "ImageOffline_$(Get-Random)"))
$ImageDir = Get-Item -LiteralPath $ScriptDirectory\$ImageDir -Force
$ImageDir
}
Function New-MountDirectory
{
$MountDir = [System.IO.Directory]::CreateDirectory((Join-Path -Path $ScriptDirectory -ChildPath "MountOffline_$(Get-Random)"))
$MountDir = Get-Item -LiteralPath $ScriptDirectory\$MountDir -Force
$MountDir
}
Function New-SaveDirectory
{
$SaveDir = [System.IO.Directory]::CreateDirectory((Join-Path -Path $ScriptRoot -ChildPath Optimize-Offline"-[$((Get-Date).ToString('MM.dd.yy hh.mm.ss'))]"))
$SaveDir = Get-Item -LiteralPath $ScriptRoot\$SaveDir
$SaveDir
}
Function Mount-OfflineHives
{
Start-Process -FilePath REG -ArgumentList ("LOAD HKLM\WIM_HKLM_SOFTWARE `"$MountFolder\Windows\System32\config\software`"") -WindowStyle Hidden -Wait
Start-Process -FilePath REG -ArgumentList ("LOAD HKLM\WIM_HKLM_SYSTEM `"$MountFolder\Windows\System32\config\system`"") -WindowStyle Hidden -Wait
Start-Process -FilePath REG -ArgumentList ("LOAD HKLM\WIM_HKCU `"$MountFolder\Users\Default\NTUSER.DAT`"") -WindowStyle Hidden -Wait
Start-Process -FilePath REG -ArgumentList ("LOAD HKLM\WIM_HKU_DEFAULT `"$MountFolder\Windows\System32\config\default`"") -WindowStyle Hidden -Wait
}
Function Dismount-OfflineHives
{
[System.GC]::Collect()
Start-Process -FilePath REG -ArgumentList ("UNLOAD HKLM\WIM_HKLM_SOFTWARE") -WindowStyle Hidden -Wait
Start-Process -FilePath REG -ArgumentList ("UNLOAD HKLM\WIM_HKLM_SYSTEM") -WindowStyle Hidden -Wait
Start-Process -FilePath REG -ArgumentList ("UNLOAD HKLM\WIM_HKCU") -WindowStyle Hidden -Wait
Start-Process -FilePath REG -ArgumentList ("UNLOAD HKLM\WIM_HKU_DEFAULT") -WindowStyle Hidden -Wait
}
Function Test-OfflineHives
{
@("HKLM:\WIM_HKLM_SOFTWARE", "HKLM:\WIM_HKLM_SYSTEM", "HKLM:\WIM_HKCU", "HKLM:\WIM_HKU_DEFAULT") | ForEach {
If (Test-Path -Path $_) { $HivesLoaded = $true }
}
Return $HivesLoaded
}
Function Clear-CurrentMount
{
[CmdletBinding()]
Param ()
$Host.UI.RawUI.WindowTitle = "Cleaning-up mount path."
Write-Host "Mount path detected. Performing clean-up." -ForegroundColor Cyan
$MountPath = (Get-WindowsImage -Mounted).MountPath
$QueryHives = Invoke-Expression -Command ('REG QUERY HKLM | FINDSTR "WIM"')
If ($QueryHives) { [void]($QueryHives.ForEach{ REG UNLOAD $_ }) }
Start-Process -FilePath DISM -ArgumentList ("/English /Unmount-Wim /MountDir:`"${MountPath}`" /Discard") -WindowStyle Hidden -Wait
Get-ChildItem -Path '.' -Filter "OptimizeOfflineTemp_*" -Directory -Name -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
[void](Clear-WindowsCorruptMountPoint)
}
Function Exit-Script
{
$Host.UI.RawUI.WindowTitle = "Terminating Script."
Start-Sleep 3
Write-Output ''
Out-Log -Content "Cleaning-up and terminating script." -Level Info
If (Test-OfflineHives) { [void](Dismount-OfflineHives) }
[void](Dismount-WindowsImage -Path $MountFolder -Discard -ScratchDirectory $ScratchFolder -LogPath $DISMLog -LogLevel 1)
[void](Clear-WindowsCorruptMountPoint)
$SaveDir = [System.IO.Directory]::CreateDirectory((Join-Path -Path $ScriptRoot -ChildPath Optimize-Offline"-[$((Get-Date).ToString('MM.dd.yy hh.mm.ss'))]")); [void]$SaveDir
If ($Error.Count)
{
$ErrorLog = Join-Path -Path $Env:TEMP -ChildPath "ErrorLog.log"
Set-Content -Path $ErrorLog -Value $Error.ToArray() -Force -ErrorAction SilentlyContinue
Move-Item -Path $ErrorLog -Destination $SaveDir -Force -ErrorAction SilentlyContinue
}
Add-Content -Path $LogFile -Value ''
Add-Content -Path $LogFile -Value "***************************************************************************************************"
Add-Content -Path $LogFile -Value "`t`t$($OScript) stopped at [$($TimeStamp)]"
Add-Content -Path $LogFile -Value "***************************************************************************************************"
Move-Item -Path $LogFile -Destination $SaveDir -Force -ErrorAction SilentlyContinue
If (Test-Path -Path "$WorkFolder\Registry-Optimizations.log") { Move-Item -Path "$WorkFolder\Registry-Optimizations.log" -Destination $SaveDir -Force -ErrorAction SilentlyContinue }
Remove-Item -Path "$Env:TEMP\DISM.log" -Force -ErrorAction SilentlyContinue
Get-ChildItem -Path $ScriptRoot -Filter "OptimizeOfflineTemp_*" -Directory -Name -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
Write-Output ''
}
Function New-Container
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true)]
[string]$Path
)
If (!(Test-Path -Path $Path))
{
[void](New-Item -Path $Path -ItemType Directory -Force)
}
}
#endregion Helper Functions
If (!(Test-Admin)) { Write-Warning "Administrative access is required. Please re-launch $OScript with elevation."; Break }
If ((Get-CimInstance -ClassName Win32_OperatingSystem).OSArchitecture -ne "64-bit") { Write-Warning "$OScript only supports a 64-bit architecture."; Break }
If (Get-WindowsImage -Mounted) { Clear-CurrentMount }
Try
{
Get-Module -ListAvailable Dism -ErrorAction Stop | Import-Module
}
Catch
{
Write-Warning "Missing the required PowerShell Dism module."
Break
}
Try
{
Get-ChildItem -Path '.' -Filter "OptimizeOfflineTemp_*" -Directory -Name -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
$ScriptRoot = (Get-Item -Path '.' -Force -ErrorAction Stop).FullName
$CreateScriptDir = [System.IO.Directory]::CreateDirectory((Join-Path -Path $ScriptRoot -ChildPath "OptimizeOfflineTemp_$(Get-Random)"))
If ($CreateScriptDir) { $ScriptDirectory = Get-Item -LiteralPath $ScriptRoot\$CreateScriptDir -ErrorAction Stop }
$Host.UI.RawUI.WindowTitle = "Preparing image for optimizations."
$Timer = New-Object System.Diagnostics.Stopwatch
$Timer.Start()
}
Catch
{
Write-Warning "Failed to create the script directory. Ensure the script path is writable."
Break
}
Try
{
If (([IO.FileInfo]$ImagePath).Extension -eq ".ISO")
{
$Source = ([System.IO.Path]::ChangeExtension($ImagePath, ([System.IO.Path]::GetExtension($ImagePath)).ToString().ToLower()))
$Source = (Resolve-Path -Path $Source -ErrorAction Stop).ProviderPath
$SourceMount = Mount-DiskImage -ImagePath $Source -StorageType ISO -PassThru -ErrorAction Stop
$DriveLetter = ($SourceMount | Get-Volume).DriveLetter + ':'
$ISODrive = Get-Item -Path $DriveLetter -Force -ErrorAction Stop
$SourceName = $($Source.Split('\')[-1]).TrimEnd('.iso')
$ISOMedia = "$($ScriptDirectory)\$($SourceName)"
[void](New-Item -Path $ISOMedia -ItemType Directory -Force -ErrorAction Stop)
$InstallWim = "$($DriveLetter)\sources\install.wim"
If (!(Test-Path -Path $InstallWim))
{
Write-Warning "$(Split-Path -Path $ImagePath -Leaf) does not contain valid Windows Installation media."
Remove-Item -Path $ScriptDirectory -Recurse -Force -ErrorAction SilentlyContinue
Break
}
Else
{
Write-Host ('Exporting media from "{0}"' -f $(Split-Path -Path $Source -Leaf)) -ForegroundColor Cyan
ForEach ($File In Get-ChildItem -Path $ISODrive.FullName -Recurse)
{
$NewPath = $ISOMedia + $File.FullName.Replace($ISODrive, '\')
Copy-Item -Path $File.FullName -Destination $NewPath -Force -ErrorAction Stop
}
Dismount-DiskImage -ImagePath $Source -StorageType ISO
$ISOIsExported = $true
}
If (Test-Path -Path "$ISOMedia\sources\install.wim")
{
[void]($MountFolder = New-MountDirectory)
[void]($ImageFolder = New-ImageDirectory)
[void]($WorkFolder = New-WorkDirectory)
[void]($ScratchFolder = New-ScratchDirectory)
Move-Item -Path "$ISOMedia\sources\install.wim" -Destination $ImageFolder -Force -ErrorAction Stop
$InstallWim = Get-Item -Path "$ImageFolder\install.wim" -Force -ErrorAction Stop
Set-ItemProperty -LiteralPath $InstallWim -Name IsReadOnly -Value $false -ErrorAction Stop
If ((Test-Path -Path "$ISOMedia\sources\boot.wim") -and ($DaRT))
{
Move-Item -Path "$ISOMedia\sources\boot.wim" -Destination $ImageFolder -Force -ErrorAction Stop
$BootWim = Get-Item -Path "$ImageFolder\boot.wim" -Force -ErrorAction Stop
Set-ItemProperty -LiteralPath $BootWim -Name IsReadOnly -Value $false -ErrorAction Stop
$BootIsPresent = $true
}
}
}
ElseIf (([IO.FileInfo]$ImagePath).Extension -eq ".WIM")
{
If (Test-Path -Path $ImagePath -Filter "install.wim")
{
$ImagePath = (Resolve-Path -Path $ImagePath -ErrorAction Stop).ProviderPath
Write-Host ('Copying WIM from "{0}"' -f $(Split-Path -Path $ImagePath -Parent)) -ForegroundColor Cyan
[void]($MountFolder = New-MountDirectory)
[void]($ImageFolder = New-ImageDirectory)
[void]($WorkFolder = New-WorkDirectory)
[void]($ScratchFolder = New-ScratchDirectory)
Copy-Item -Path $ImagePath -Destination $ImageFolder -Force -ErrorAction Stop
$InstallWim = Get-Item -Path "$ImageFolder\install.wim" -Force -ErrorAction Stop
If ($InstallWim.IsReadOnly) { Set-ItemProperty -LiteralPath $InstallWim -Name IsReadOnly -Value $false -ErrorAction Stop }
}
Else
{
Write-Warning "$ImagePath is not labeled as an install.wim"
Remove-Item -Path $ScriptDirectory -Recurse -Force -ErrorAction SilentlyContinue
Break
}
}
}
Catch
{
Write-Output ''
Write-Host "Unable to attain required image data content." -ForegroundColor Red
Remove-Item -Path $ScriptDirectory -Recurse -Force -ErrorAction SilentlyContinue
Break
}
If (Test-Path -Path "$Env:SystemRoot\Logs\DISM\dism.log") { Remove-Item -Path "$Env:SystemRoot\Logs\DISM\dism.log" -Force -ErrorAction SilentlyContinue }
If (Test-Path -Path $DISMLog) { Remove-Item -Path $DISMLog -Force -ErrorAction SilentlyContinue }
If (Test-Path -Path $LogFile) { Remove-Item -Path $LogFile -Force -ErrorAction SilentlyContinue }
If ((Get-WindowsImage -ImagePath $InstallWim -Index $Index).InstallationType -eq "Server")
{
Write-Output ''
Write-Warning "Server editions are not supported."
Remove-Item -Path $ScriptDirectory -Recurse -Force -ErrorAction SilentlyContinue
Break
}
Else
{
[void](New-Item -Path $LogFile -ItemType File -Force)
@"
***************************************************************************************************
$($OScript) started at [$($TimeStamp)]
***************************************************************************************************
"@ | Out-File -FilePath $LogFile -Append -Encoding ASCII
}
Try
{
$CheckVersion = (Get-WindowsImage -ImagePath $InstallWim -Index $Index -ErrorAction Stop).Version
$CheckBuild = (Get-WindowsImage -ImagePath $InstallWim -Index $Index -ErrorAction Stop).Build
If ($CheckVersion -like "10.*")
{
If ($CheckBuild -lt '15063')
{
Write-Output ''
Write-Warning "The image build is not supported [$($CheckBuild.ToString())]"
Remove-Item -Path $ScriptDirectory -Recurse -Force -ErrorAction SilentlyContinue
Break
}
Else
{
Write-Output ''
Out-Log -Content "The image build is supported [$($CheckBuild.ToString())]" -Level Info
Start-Sleep 3
$Error.Clear()
}
}
Else
{
Write-Output ''
Write-Warning "The image version is not supported [$($CheckVersion.ToString())]"
Remove-Item -Path $ScriptDirectory -Recurse -Force -ErrorAction SilentlyContinue
Break
}
}
Catch
{
Write-Output ''
Write-Warning "Failed to return the image version and build."
Remove-Item -Path $ScriptDirectory -Recurse -Force -ErrorAction SilentlyContinue
Break
}
Try
{
Write-Output ''
Out-Log -Content "Mounting Image." -Level Info
$MountWindowsImage = @{
ImagePath = $InstallWim
Index = $Index
Path = $MountFolder
ScratchDirectory = $ScratchFolder
LogPath = $DISMLog
LogLevel = 1
ErrorAction = "Stop"
}
[void](Mount-WindowsImage @MountWindowsImage)
$StartHealthCheck = (Repair-WindowsImage -Path $MountFolder -CheckHealth -ErrorAction Stop).ImageHealthState
If ($StartHealthCheck -eq "Healthy")
{
Write-Output ''
Out-Log -Content "The image health state has returned as [Healthy]" -Level Info
Start-Sleep 3
}
Else
{
Write-Output ''
Out-Log -Content "The image has been flagged for corruption. Further servicing is required before the image can be optimized." -Level Error
Exit-Script
Break
}
}
Catch
{
Write-Output ''
Out-Log -Content "Failed to return the image health state." -Level Error
Exit-Script
Break
}
Try
{
$Host.UI.RawUI.WindowTitle = "Backing-up the Default Registry."
Write-Output ''
Out-Log -Content "Backing-up the Default Registry." -Level Info
[void](New-Item -Path $OfflineBackupDirectory -ItemType Directory -Force -ErrorAction Stop)
[void](Mount-OfflineHives)
Start-Process -FilePath REGEDIT -ArgumentList ("/E $OfflineBackupDirectory\HKLM_$BkpTimestamp.reg HKEY_LOCAL_MACHINE\WIM_HKLM_SOFTWARE") -WindowStyle Hidden -Wait -ErrorAction Stop
Start-Process -FilePath REGEDIT -ArgumentList ("/E $OfflineBackupDirectory\HKLM_$BkpTimestamp.reg HKEY_LOCAL_MACHINE\WIM_HKLM_SYSTEM") -WindowStyle Hidden -Wait -ErrorAction Stop
Start-Process -FilePath REGEDIT -ArgumentList ("/E $OfflineBackupDirectory\HKCU_$BkpTimestamp.reg HKEY_LOCAL_MACHINE\WIM_HKCU") -WindowStyle Hidden -Wait -ErrorAction Stop
Start-Process -FilePath REGEDIT -ArgumentList ("/E $OfflineBackupDirectory\HKU_$BkpTimestamp.reg HKEY_LOCAL_MACHINE\WIM_HKU_DEFAULT") -WindowStyle Hidden -Wait -ErrorAction Stop
[void](Dismount-OfflineHives)
[void](Compress-Archive -Path $OfflineBackupDirectory -DestinationPath "$WorkFolder\RegistryBackup.Zip" -CompressionLevel Optimal -ErrorAction Stop)
Remove-Item -Path $OfflineBackupDirectory -Recurse -Force -ErrorAction SilentlyContinue
}
Catch
{
Write-Output ''
Out-Log -Content "Failed to back-up the Default Registry." -Level Error
Exit-Script
Break
}
Finally
{
If (Test-OfflineHives) { [void](Dismount-OfflineHives) }
}
If (($MetroApps -and (Get-WindowsImage -ImagePath $InstallWim).ImageName -notlike "*LTSC"))
{
Try
{
$RemovedProvisionedApps = [System.Collections.ArrayList]@()
Clear-Host
$Host.UI.RawUI.WindowTitle = "Removing Metro Apps."
If ($MetroApps -eq "Select")
{
$GetAppx = Get-AppxProvisionedPackage -Path $MountFolder
$Int = 1
ForEach ($Appx In $GetAppx)
{
$GetAppx = New-Object -TypeName PSObject
$GetAppx | Add-Member -MemberType NoteProperty -Name Num -Value $Int
$GetAppx | Add-Member -MemberType NoteProperty -Name DisplayName -Value $Appx.DisplayName
$GetAppx | Add-Member -MemberType NoteProperty -Name PackageName -Value $Appx.PackageName
$Int++
[void]$RemovedProvisionedApps.Add($GetAppx)
}
$RemoveAppx = $RemovedProvisionedApps | Out-GridView -Title "Remove Provisioned App Packages." -PassThru
$PackageName = $RemoveAppx.PackageName
If ($RemoveAppx)
{
$PackageName | ForEach {
Out-Log -Content "Removing Provisioned App Package: $($_.Split('_')[0])" -Level Info
$RemoveSelectAppx = @{
Path = $MountFolder
PackageName = $($_)
ScratchDirectory = $ScratchFolder
LogPath = $DISMLog
LogLevel = 1
ErrorAction = "Stop"
}
[void](Remove-AppxProvisionedPackage @RemoveSelectAppx)
}
}
}
ElseIf ($MetroApps -eq "All")
{
Get-AppxProvisionedPackage -Path $MountFolder | ForEach {
Out-Log -Content "Removing Provisioned App Package: $($_.DisplayName)" -Level Info
$RemoveAllAppx = @{
Path = $MountFolder
PackageName = $($_.PackageName)
ScratchDirectory = $ScratchFolder
LogPath = $DISMLog
LogLevel = 1
ErrorAction = "Stop"
}
[void](Remove-AppxProvisionedPackage @RemoveAllAppx)
}
}
$MetroAppsComplete = $true
Clear-Host
}
Catch
{
Write-Output ''
Out-Log -Content "Failed to remove Provisioned App Packages." -Level Error
Exit-Script
Break
}
Finally
{
$Int = $null
}
}
If ($SystemApps)
{
$RemovedSystemApps = [System.Collections.ArrayList]@()
Try
{
Clear-Host
$Host.UI.RawUI.WindowTitle = "Removing System Applications."
Write-Warning "Do NOT remove any System Application if you are unsure of its impact on a live installation."
Start-Sleep 5
Start-Process -FilePath REG -ArgumentList ("LOAD HKLM\WIM_HKLM_SOFTWARE `"$MountFolder\Windows\System32\config\software`"") -WindowStyle Hidden -Wait
$InboxAppsKey = "HKLM:\WIM_HKLM_SOFTWARE\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\InboxApplications"
$InboxAppsPackage = (Get-ChildItem -Path $InboxAppsKey).Name.Split('\') | Where { $_ -like "*Microsoft.*" }
$GetSystemApps = $InboxAppsPackage | Select -Property `
@{ Label = 'Name'; Expression = { ($_.Split('_')[0]) } },
@{ Label = 'PackageName'; Expression = { ($_) } } |
Out-GridView -Title "Remove System Applications." -PassThru
$SystemAppPackage = $GetSystemApps.PackageName
If ($GetSystemApps)
{
Clear-Host
$SystemAppPackage | ForEach {
$FullKeyPath = $InboxAppsKey + '\' + $($_)
$AppKey = $FullKeyPath.Replace("HKLM:", "HKLM")
Out-Log -Content "Removing System Application: $($_.Split('_')[0])" -Level Info
[void](Invoke-Expression -Command ('REG DELETE $AppKey /F') -ErrorAction Stop)
[void]$RemovedSystemApps.Add($($_.Split('_')[0]))
Start-Sleep 2
}
}
Start-Process -FilePath REG -ArgumentList ("UNLOAD HKLM\WIM_HKLM_SOFTWARE") -WindowStyle Hidden -Wait
$SystemAppsComplete = $true
Clear-Host
}
Catch
{
Out-Log -Content "Failed to remove required registry subkeys." -Level Error
Exit-Script
Break
}
}
If ($Packages)
{
$RemovedWindowsPackages = [System.Collections.ArrayList]@()
Try
{
Clear-Host
$Host.UI.RawUI.WindowTitle = "Removing Windows Capability Packages."
$CapabilityPackages = Get-WindowsCapability -Path $MountFolder | Where State -EQ Installed
$Int = 1
ForEach ($CapabilityPackage In $CapabilityPackages)
{
$CapabilityPackages = New-Object -TypeName PSObject
$CapabilityPackages | Add-Member -MemberType NoteProperty -Name Num -Value $Int
$CapabilityPackages | Add-Member -MemberType NoteProperty -Name Name -Value $CapabilityPackage.Name
$CapabilityPackages | Add-Member -MemberType NoteProperty -Name State -Value $CapabilityPackage.State
$Int++
[void]$RemovedWindowsPackages.Add($CapabilityPackages)
}
$RemovePackages = $RemovedWindowsPackages | Out-GridView -Title "Remove Windows Capability Packages." -PassThru
$PackageName = $RemovePackages.Name
If ($RemovePackages)
{
$PackageName | ForEach {
Out-Log -Content "Removing Windows Capability Package: $($_.Split('~')[0])" -Level Info
$CapabilityPackage = @{
Path = $MountFolder
Name = $($_)
ScratchDirectory = $ScratchFolder
LogPath = $DISMLog
LogLevel = 1
ErrorAction = "Stop"
}
[void](Remove-WindowsCapability @CapabilityPackage)
}
}
Clear-Host
}
Catch
{
Write-Output ''
Out-Log -Content "Failed to remove Windows Capability Packages." -Level Error
Exit-Script
Break
}
Finally
{
$Int = $null
}
}
If ($OneDrive)
{
Try
{
$Host.UI.RawUI.WindowTitle = "Removing Microsoft OneDrive."
Out-Log -Content "Removing Microsoft OneDrive." -Level Info
Start-Sleep 3
[void](Mount-OfflineHives)
New-Container -Path "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Windows\OneDrive" -ErrorAction Stop
New-Container -Path "HKLM:\WIM_HKLM_SOFTWARE\Wow6432Node\Policies\Microsoft\Windows\OneDrive" -ErrorAction Stop
New-Container -Path "HKLM:\WIM_HKCU\SOFTWARE\Microsoft\OneDrive" -ErrorAction Stop
Set-ItemProperty -LiteralPath "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Windows\OneDrive" -Name "DisableFileSyncNGSC" -Value 1 -Type DWord
Set-ItemProperty -LiteralPath "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Windows\OneDrive" -Name "DisableFileSync" -Value 1 -Type DWord
Set-ItemProperty -LiteralPath "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Windows\OneDrive" -Name "DisableMeteredNetworkFileSync" -Value 1 -Type DWord
Set-ItemProperty -LiteralPath "HKLM:\WIM_HKLM_SOFTWARE\Policies\Microsoft\Windows\OneDrive" -Name "DisableLibrariesDefaultSaveToOneDrive" -Value 1 -Type DWord
Set-ItemProperty -LiteralPath "HKLM:\WIM_HKLM_SOFTWARE\Wow6432Node\Policies\Microsoft\Windows\OneDrive" -Name "DisableFileSyncNGSC" -Value 1 -Type DWord
Set-ItemProperty -LiteralPath "HKLM:\WIM_HKCU\SOFTWARE\Microsoft\OneDrive" -Name "DisablePersonalSync" -Value 1 -Type DWord
If ((Get-WindowsImage -ImagePath $InstallWim).ImageName -notlike "*LTSC")
{
If ((Get-ItemProperty -LiteralPath "HKLM:\WIM_HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" -ErrorAction SilentlyContinue) -match "OneDriveSetup")
{
Remove-ItemProperty -LiteralPath "HKLM:\WIM_HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" -Name "OneDriveSetup" -Force -ErrorAction Stop
}
}
If (Test-Path -Path "HKLM:\WIM_HKLM_SOFTWARE\Classes\CLSID\{018D5C66-4533-4307-9B53-224DE2ED1FE6}")
{
Remove-Item -LiteralPath "HKLM:\WIM_HKLM_SOFTWARE\Classes\CLSID\{018D5C66-4533-4307-9B53-224DE2ED1FE6}" -Force -Recurse -ErrorAction Stop
}
If (Test-Path -Path "HKLM:\WIM_HKLM_SOFTWARE\WOW6432Node\Classes\CLSID\{018D5C66-4533-4307-9B53-224DE2ED1FE6}")
{
Remove-Item -LiteralPath "HKLM:\WIM_HKLM_SOFTWARE\WOW6432Node\Classes\CLSID\{018D5C66-4533-4307-9B53-224DE2ED1FE6}" -Force -Recurse -ErrorAction Stop
}
[void](Dismount-OfflineHives)
If (Test-Path -Path "$MountFolder\Users\Default\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\OneDrive.lnk")
{
Remove-Item -LiteralPath "$MountFolder\Users\Default\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\OneDrive.lnk" -Force -ErrorAction Stop
}
If (Test-Path -Path "$MountFolder\Windows\WinSxS\*onedrive*")
{
[void](New-Item -Path $WorkFolder -ItemType Directory -Name OneDriveWinSxS -Force -ErrorAction Stop)
Copy-Item -Path "$MountFolder\Windows\WinSxS\*onedrive*" -Destination "$WorkFolder\OneDriveWinSxS" -Recurse -ErrorAction Stop
[void](Compress-Archive -Path "$WorkFolder\OneDriveWinSxS\*" -DestinationPath "$WorkFolder\OneDriveBackup.Zip" -CompressionLevel Optimal -ErrorAction Stop)
[void](Set-FolderOwnership -Path "$MountFolder\Windows\WinSxS\*onedrive*" -ErrorAction SilentlyContinue)
Get-ChildItem -Path "$MountFolder\Windows\WinSxS\*onedrive*" -Recurse -Force -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item -Path "$WorkFolder\OneDriveWinSxS" -Recurse -Force -ErrorAction SilentlyContinue
}
}
Catch
{
Write-Output ''
Out-Log -Content "Failed to remove Microsoft OneDrive." -Level Error
Exit-Script
Break
}
}
If ($MetroAppsComplete -eq $true)
{
Try
{
If ((Get-AppxProvisionedPackage -Path $MountFolder |
Where DisplayName -Match "Microsoft.Wallet").Count.Equals(0) -or (Get-AppxProvisionedPackage -Path $MountFolder |
Where DisplayName -Match "Microsoft.WindowsMaps").Count.Equals(0))
{
$Host.UI.RawUI.WindowTitle = "Disabling Provisioned App Package Services."
If ($OneDrive) { Write-Output '' }
Out-Log -Content "Disabling Provisioned App Package Services." -Level Info
Start-Process -FilePath REG -ArgumentList ("LOAD HKLM\WIM_HKLM_SYSTEM `"$MountFolder\Windows\System32\config\system`"") -WindowStyle Hidden -Wait
If (Test-Path -Path "HKLM:\WIM_HKLM_SYSTEM\ControlSet001\Services\WalletService")
{
Set-ItemProperty -LiteralPath "HKLM:\WIM_HKLM_SYSTEM\ControlSet001\Services\WalletService" -Name "Start" -Value 4 -Type DWord -ErrorAction Stop
}
If (Test-Path -Path "HKLM:\WIM_HKLM_SYSTEM\ControlSet001\Services\MapsBroker")
{
Set-ItemProperty -LiteralPath "HKLM:\WIM_HKLM_SYSTEM\ControlSet001\Services\MapsBroker" -Name "Start" -Value 4 -Type DWord -ErrorAction Stop
}
Start-Process -FilePath REG -ArgumentList ("UNLOAD HKLM\WIM_HKLM_SYSTEM") -WindowStyle Hidden -Wait
}
}
Catch
{
Out-Log -Content "An error occurred removing Provisoned App Package Services." -Level Error
Exit-Script
Break
}
}
If ((Get-WindowsImage -ImagePath $InstallWim).ImageName -notlike "*LTSC")
{
Try
{
$Host.UI.RawUI.WindowTitle = "Cleaning-up the Start Menu and Taskbar Layout."
Write-Output ''
Out-Log -Content "Cleaning-up the Start Menu and Taskbar Layout." -Level Info
Start-Sleep 3
@'
<LayoutModificationTemplate xmlns:defaultlayout="http://schemas.microsoft.com/Start/2014/FullDefaultLayout" xmlns:start="http://schemas.microsoft.com/Start/2014/StartLayout" Version="1" xmlns:taskbar="http://schemas.microsoft.com/Start/2014/TaskbarLayout" xmlns="http://schemas.microsoft.com/Start/2014/LayoutModification">
<LayoutOptions StartTileGroupCellWidth="6" />
<DefaultLayoutOverride>
<StartLayoutCollection>
<defaultlayout:StartLayout GroupCellWidth="6">
<start:Group Name="">
<start:DesktopApplicationTile Size="2x2" Column="0" Row="0" DesktopApplicationID="Microsoft.Windows.Computer" />
<start:DesktopApplicationTile Size="2x2" Column="2" Row="0" DesktopApplicationID="Microsoft.Windows.ControlPanel" />
<start:DesktopApplicationTile Size="1x1" Column="4" Row="0" DesktopApplicationLinkPath="%APPDATA%\Microsoft\Windows\Start Menu\Programs\Windows PowerShell\Windows PowerShell.lnk" />
<start:DesktopApplicationTile Size="1x1" Column="4" Row="1" DesktopApplicationLinkPath="%APPDATA%\Microsoft\Windows\Start Menu\Programs\Windows PowerShell\Windows PowerShell ISE.lnk" />
<start:DesktopApplicationTile Size="1x1" Column="5" Row="0" DesktopApplicationLinkPath="%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs\UWP File Explorer.lnk" />
<start:DesktopApplicationTile Size="1x1" Column="5" Row="1" DesktopApplicationLinkPath="%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs\UEFI Firmware.lnk" />
</start:Group>
</defaultlayout:StartLayout>
</StartLayoutCollection>
</DefaultLayoutOverride>
<CustomTaskbarLayoutCollection>
<defaultlayout:TaskbarLayout>
<taskbar:TaskbarPinList>
<taskbar:UWA AppUserModelID="windows.immersivecontrolpanel_cw5n1h2txyewy!microsoft.windows.immersivecontrolpanel" />
</taskbar:TaskbarPinList>
</defaultlayout:TaskbarLayout>
</CustomTaskbarLayoutCollection>
</LayoutModificationTemplate>
'@ | Out-File -FilePath "$MountFolder\Users\Default\AppData\Local\Microsoft\Windows\Shell\LayoutModification.xml" -ErrorAction Stop
Start-Sleep 3
$UWPShell = New-Object -ComObject WScript.Shell -ErrorAction Stop
$UWPShortcut = $UWPShell.CreateShortcut("$MountFolder\ProgramData\Microsoft\Windows\Start Menu\Programs\UWP File Explorer.lnk")
$UWPShortcut.TargetPath = "%SystemRoot%\explorer.exe"
$UWPShortcut.Arguments = "shell:AppsFolder\c5e2524a-ea46-4f67-841f-6a9465d9d515_cw5n1h2txyewy!App"
$UWPShortcut.IconLocation = "imageres.dll,-1023"
$UWPShortcut.WorkingDirectory = "%SystemRoot%"
$UWPShortcut.Description = "The UWP File Explorer Application."
$UWPShortcut.Save()
$UEFIShell = New-Object -ComObject WScript.Shell -ErrorAction Stop
$UEFIShortcut = $UEFIShell.CreateShortcut("$MountFolder\ProgramData\Microsoft\Windows\Start Menu\Programs\UEFI Firmware.lnk")
$UEFIShortcut.TargetPath = "%SystemRoot%\System32\shutdown.exe"
$UEFIShortcut.Arguments = "/R /FW"
$UEFIShortcut.IconLocation = "bootux.dll,-1016"
$UEFIShortcut.WorkingDirectory = "%SystemRoot%\System32"
$UEFIShortcut.Description = "Reboot directly into the system's UEFI firmware."
$UEFIShortcut.Save()
$Bytes = [System.IO.File]::ReadAllBytes("$MountFolder\ProgramData\Microsoft\Windows\Start Menu\Programs\UEFI Firmware.lnk")
$Bytes[0x15] = $Bytes[0x15] -bor 0x20
[System.IO.File]::WriteAllBytes("$MountFolder\ProgramData\Microsoft\Windows\Start Menu\Programs\UEFI Firmware.lnk", $Bytes)
}
Catch
{
Write-Output ''
Out-Log -Content "Failed to clean-up the Start Menu and Taskbar Layout." -Level Error
Exit-Script
Break
}
}