-
Notifications
You must be signed in to change notification settings - Fork 0
/
MTRoW_VM.ps1
1823 lines (1548 loc) · 71.1 KB
/
MTRoW_VM.ps1
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
<#
.SYNOPSIS
Create SRSv2 media appropriate for setting up an SRSv2 device.
.DESCRIPTION
This script automates some sanity checks and copying operations that are
necessary to create bootable SRSv2 media. Booting an SRSv2 device using the
media created from this process will result in the SRSv2 shutting down. The
SRSv2 can then either be put into service, or booted with separate WinPE
media for image capture.
To use this script, you will need:
1. An Internet connection
2. A USB drive with sufficient space (16GB+), inserted into this computer
3. Windows 10 Enterprise or Windows 10 Enterprise IoT media, which must be
accessible from this computer (you will be prompted for a path). The
Windows media build number must match the build required by the SRSv2
deployment kit.
.EXAMPLE
.\CreateSrsMedia
Prompt for required information, validate provided inputs, and (if all
validations pass) create media on the specified USB device.
.NOTES
This script requires that you provide Windows media targeted for the x64
architecture.
Only one driver pack can be used at a time. Each unique supported SKU of
SRSv2 computer hardware must have its own, separate image.
The build number of the Windows media being used *must* match the build
required by the SRSv2 deployment kit.
#>
<#
Revision history
1.0.0 - Initial release
1.0.1 - Support source media with WIM >4GB
1.1.0 - Switch Out-Null to Write-Debug for troubleshooting
Record transcripts for troubleshooting
Require the script be run from a path without spaces
Require the script be run from an NTFS filesystem
Soft check for sufficient scratch space
Warn that the target USB drive will be wiped
Rethrow exceptions after cleanup on main path
1.2.0 - Indicate where to get Enterprise media
Improve error handling for non-Enterprise media
Report and exit on copy errors
Work with spaces in the script's path
Explicitly reject Windows 10 Media Creation Tool media
Fix OEM media regression caused by splitting WIMs
1.3.1 - Read config information from MSI
Added infrastructure for downloading files
Support for automatically downloading Windows updates
Support for automatically downloading the deployment kit MSI
Support for self-updating
Added menu-driven driver selection/downloading
1.3.2 - Fix OEM media regression caused by splitting WIMs
1.4.0 - Support BIOS booting
1.4.1 - BIOS booting controlled by metadata
1.4.2 - Fix driver pack informative output
Add 64-bit check to prevent 32-bit accidents
Add debugging cross-check
Add checks to prevent the script being run in weird ways
Add warning about image cleanup taking a long time
Fix space handling in self-update
1.4.3 - Add non-terminating disk initialization logic
Delete "system volume information" to prevent Windows Setup issues
Add return code checking for native commands
1.4.4 - Improve rejection of non-LP CABs
1.4.5 - Add host OS check to prevent older DISM etc. mangling newer images
1.5.0 - Add support for mismatched OS build number vs. feature build number
1.5.1 - Change OEM default key.
1.6.0 - Add support for mismatched OS build number vs. language build number
1.6.1 - Use default credentials with the default proxy
1.7.0 - Add metadata for clearer "human readable" Windows version information
Change required input from Windows install media path to Windows ISO path
Add size and hash check for input Windows ISO
1.7.1 - Remove ePKEA references
Improve ISO path input handling to allow quoted paths
Fix directory left behind when script runs successfully
Improve diagnostic output so it's less obtrusive
1.8.0 - Add support for deployment kits that require Windows 11
Improve ISO requirements messaging, so it's always stated
Change names, add comments to reduce cases of mistaken code divers
#>
[CmdletBinding()]
param(
[Switch]$ShowVersion, <# If set, output the script version number and exit. #>
[Switch]$Manufacturing <# Internal use. #>
)
$ErrorActionPreference = "Stop"
$DebugPreference = if($PSCmdlet.MyInvocation.BoundParameters["Debug"]) { "Continue" } else { "SilentlyContinue" }
Set-StrictMode -Version Latest
$CreateSrsMediaScriptVersion = "1.8.0"
$SrsKitHumanVersion = $null
$SrsKitVlscName = $null
$SrsKitIsoSize = $null
$SrsKitIsoSha256 = $null
$robocopy_success = {$_ -lt 8 -and $_ -ge 0}
if ($ShowVersion) {
Write-Output $CreateSrsMediaScriptVersion
exit
}
function Remove-Directory {
<#
.SYNOPSIS
Recursively remove a directory and all its children.
.DESCRIPTION
Powershell can't handle 260+ character paths, but robocopy can. This
function allows us to safely remove a directory, even if the files
inside exceed Powershell's usual 260 character limit.
#>
param(
[parameter(Mandatory=$true)]
[string]$path <# The path to recursively remove #>
)
# Make an empty reference directory
$cleanup = Join-Path $PSScriptRoot "empty-temp"
if (Test-Path $cleanup) {
Remove-Item -Path $cleanup -Recurse -Force
}
New-Item -ItemType Directory $cleanup | Write-Debug
# Use robocopy to clear out the guts of the victim path
(Invoke-Native "& robocopy '$cleanup' '$path' /mir" $robocopy_success) | Write-Debug
# Remove the folders, now that they're empty.
Remove-Item $path -Force
Remove-Item $cleanup -Force
}
function Test-OsIsoPath {
<#
.SYNOPSIS
Test if $OsIsoPath is the expected Windows setup ISO for SRSv2.
.DESCRIPTION
Tests if the provided path references the Windows setup ISO
that matches the media indicated in the SRSv2 installation
metadata. Specifically, the ISO must:
- Be the correct size
- Produce the correct SHA256 hash
.OUTPUTS bool
$true if $OsIsoPath refers to the expected ISO, $false otherwise.
#>
param(
[parameter(Mandatory=$true)]
$OsIsoPath, <# Path to the ISO file to check #>
[parameter(Mandatory=$true)]
$KitIsoSize, <# Expected size of the ISO in bytes #>
[parameter(Mandatory=$true)]
$KitIsoSha256, <# Expected SHA256 hash of the ISO file #>
[parameter(Mandatory=$true)]
[switch]$IsOem <# Whether OEM media is being used #>
)
if (!(Test-Path $OsIsoPath)) {
Write-Host "The path provided does not exist. Please specify a path to a Windows installation ISO file."
return $false
}
if (!(Test-Path $OsIsoPath -PathType Leaf)) {
Write-Host "The path provided does not refer to a file. Please specify a path to a Windows installation ISO file."
return $false
}
$Iso = Get-ChildItem $OsIsoPath
if ($Iso.Length -ne $KitIsoSize) {
Write-Host "The ISO does not match the expected size."
Write-Host "Verify that you downloaded the correct file, and that it is not corrupted."
PrintWhereToGetMedia -IsOem:$IsOem
return $false
}
if ((Get-FileHash -Algorithm SHA256 $Iso).Hash -ne $KitIsoSha256) {
Write-Host "The ISO does not match the expected SHA256 hash."
Write-Host "Verify that you downloaded the correct file, and that it is not corrupted."
PrintWhereToGetMedia -IsOem:$IsOem
return $false
}
return $true
}
function Test-Unattend-Compat {
<#
.SYNOPSIS
Test to see if this script is compatible with a given SRSv2 Unattend.xml file.
.DESCRIPTION
Looks for metadata in the $xml parameter indicating the lowest version of
the CreateSrsMedia script the XML file will work with.
.OUTPUTS bool
Return $true if CreateSrsMedia is compatible with the SRSv2
Unattend.xml file in $xml, $false otherwise.
#>
param(
[parameter(Mandatory=$true)]
[System.Xml.XmlDocument]$Xml, <# The SRSv2 AutoUnattend to check compatibility with. #>
[parameter(Mandatory=$true)]
[int]$Rev <# The maximum compatibility revision this script supports. #>
)
$nodes = $Xml.SelectNodes("//comment()[starts-with(normalize-space(translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')), 'srsv2-compat-rev:')]")
# If the file has no srsv2-compat-rev value, assume rev 0, which all scripts work with.
if ($nodes -eq $null -or $nodes.Count -eq 0) {
return $true
}
$URev = 0
# If there is more than one value, be conservative: take the biggest value
$nodes |
ForEach-Object {
$current = $_.InnerText.Split(":")[1]
if ($URev -lt $current) {
$URev = $current
}
}
return $Rev -ge $URev
}
function Remove-Xml-Comments {
<#
.SYNOPSIS
Remove all comments that are direct children of $node.
.DESCRIPTION
Remove all the comment children nodes (non-recursively) from the specified $node.
#>
param(
[parameter(Mandatory=$true)]
[System.Xml.XmlNode]$node <# The XML node to strip comments from. #>
)
$node.SelectNodes("comment()") |
ForEach-Object {
$node.RemoveChild($_) | Write-Debug
}
}
function Add-AutoUnattend-Key {
<#
.SYNOPSIS
Inject $key as a product key into the AutoUnattend XML $xml.
.DESCRIPTION
Injects the $key value as a product key in $xml, where $xml is an
AutoUnattend file already containing a Microsoft-Windows-Setup UserData
node. Any comments in the UserData node are stripped.
If a ProductKey node already exists, this function does *not* remove or
replace it.
#>
param(
[parameter(Mandatory=$true)]
[System.Xml.XmlDocument]$xml, <# The SRSv2 AutoUnattend to modify. #>
[parameter(Mandatory=$true)]
[string]$key <# The Windows license key to inject. #>
)
$XmlNs = @{"u"="urn:schemas-microsoft-com:unattend"}
$node = (Select-Xml -Namespace $XmlNs -Xml $xml -XPath "//u:settings[@pass='specialize']").Node
$NShellSetup = $xml.CreateElement("", "component", $XmlNs["u"])
$NShellSetup.SetAttribute("name", "Microsoft-Windows-Shell-Setup") | Write-Debug
$NShellSetup.SetAttribute("processorArchitecture", "amd64") | Write-Debug
$NShellSetup.SetAttribute("publicKeyToken", "31bf3856ad364e35") | Write-Debug
$NShellSetup.SetAttribute("language", "neutral") | Write-Debug
$NShellSetup.SetAttribute("versionScope", "nonSxS") | Write-Debug
$NProductKey = $xml.CreateElement("", "ProductKey", $XmlNs["u"])
$NProductKey.InnerText = $key
$NShellSetup.AppendChild($NProductKey) | Write-Debug
$node.PrependChild($NShellSetup) | Write-Debug
}
function Set-AutoUnattend-Partitions {
<#
.SYNOPSIS
Set up the AutoUnattend file for use with BIOS based systems, if requested.
.DESCRIPTION
If -BIOS is specified, reconfigure a (nominally UEFI) AutoUnattend
partition configuration to be compatible with BIOS-based systems
instead. Otherwise, do nothing.
#>
param(
[parameter(Mandatory=$true)]
[System.Xml.XmlDocument]$xml, <# The SRSv2 AutoUnattend to modify. #>
[parameter(Mandatory=$true)]
[switch]$BIOS <# If True, assume UEFI input and reconfigure for BIOS. #>
)
# for UEFI, do nothing.
if (!$BIOS) {
return
}
# BIOS logic...
$XmlNs = @{"u"="urn:schemas-microsoft-com:unattend"}
$node = (Select-Xml -Namespace $XmlNs -Xml $xml -XPath "//u:settings[@pass='windowsPE']/u:component[@name='Microsoft-Windows-Setup']").Node
# Remove the first partition (EFI)
$node.DiskConfiguration.Disk.CreatePartitions.RemoveChild($node.DiskConfiguration.Disk.CreatePartitions.CreatePartition[0]) | Write-Debug
# Re-number the remaining partition as 1
$node.DiskConfiguration.Disk.CreatePartitions.CreatePartition.Order = "1"
# Install to partition 1
$node.ImageInstall.OSImage.InstallTo.PartitionID = "1"
}
function Set-AutoUnattend-Sysprep-Mode {
<#
.SYNOPSIS
Set the SRSv2 sysprep mode to "reboot" or "shutdown" in the AutoUnattend file $xml.
.DESCRIPTION
Sets the SRSv2 AutoUnattend represented by $xml to either reboot (if
-Reboot is used), or shut down (if -shutdown is used). Any comments
under the containing RunSynchronousCommand node are stripped.
This function assumes that a singular sysprep command is specified in
$xml with /generalize and /oobe flags, in the auditUser pass,
Microsoft-Windows-Deployment component. It further assumes that the
sysprep command has the /reboot option specified by default.
#>
param(
[parameter(Mandatory=$true)]
[System.Xml.XmlDocument]$Xml, <# The SRSv2 AutoUnattend to modify. #>
[parameter(Mandatory=$true,ParameterSetName='reboot')]
[switch]$Reboot, <# Whether sysprep should perform a reboot or a shutdown. #>
[parameter(Mandatory=$true,ParameterSetName='shutdown')]
[switch]$Shutdown <# Whether sysprep should perform a shutdown or a reboot. #>
)
$XmlNs = @{"u"="urn:schemas-microsoft-com:unattend"}
$node = (Select-Xml -Namespace $XmlNs -Xml $Xml -XPath "//u:settings[@pass='auditUser']/u:component[@name='Microsoft-Windows-Deployment']/u:RunSynchronous/u:RunSynchronousCommand/u:Path[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'sysprep') and contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'generalize') and contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'oobe')]").Node
Remove-Xml-Comments $node.ParentNode
if ($Shutdown -or !$Reboot) {
$node.InnerText = $node.InnerText.ToLowerInvariant() -replace ("/reboot", "/shutdown")
}
}
function Get-TextListSelection {
<#
.SYNOPSIS
Prompt the user to pick an item from an array.
.DESCRIPTION
Given an array of items, presents the user with a text-based, numbered
list of the array items. The user must then select one item from the
array (by index). That index is then returned.
Invalid selections cause the user to be re-prompted for input.
.OUTPUTS int
The index of the item the user selected from the array.
#>
param(
[parameter(Mandatory=$true)]<# The list of objects to select from #>
$Options,
[parameter(Mandatory=$false)]<# The property of the objects to use for the list #>
$Property = $null,
[parameter(Mandatory=$false)]<# The prompt to display to the user #>
$Prompt = "Selection",
[parameter(Mandatory=$false)]<# Whether to allow a blank entry to make the default selection #>
[switch]
$AllowDefault = $true,
[parameter(Mandatory=$false)]<# Whether to automatically select the default value, without prompting #>
[switch]
$AutoDefault = $false
)
$index = 0
$response = -1
$DefaultValue = $null
$DefaultIndex = -1
if ($AllowDefault) {
$DefaultIndex = 0
if ($AutoDefault) {
return $DefaultIndex
}
}
$Options | Foreach-Object -Process {
$value = $_
if ($Property -ne $null) {
$value = $_.$Property
}
if ($DefaultValue -eq $null) {
$DefaultValue = $value
}
Write-Host("[{0,2}] {1}" -f $index, $value)
$index++
} -End {
if ($AllowDefault) {
Write-Host("(Default: {0})" -f $DefaultValue)
}
while ($response -lt 0 -or $response -ge $Options.Count) {
try {
$response = Read-Host -Prompt $Prompt -ErrorAction SilentlyContinue
if ([string]::IsNullOrEmpty($response)) {
[int]$response = $DefaultIndex
} else {
[int]$response = $response
}
} catch {}
}
}
# Write this out for transcript purposes.
Write-Transcript ("Selected option {0}." -f $response)
return $response
}
function SyncDirectory {
<#
.SYNOPSIS
Sync a source directory to a destination.
.DESCRIPTION
Given a source and destination directories, make the destination
directory's contents match the source's, recursively.
#>
param(
[parameter(Mandatory=$true)] <# The source directory containing the subirectory to sync. #>
$Src,
[parameter(Mandatory=$true)] <# The destination directory that may or may not yet contain the subdirectory being synchronized #>
$Dst,
[parameter(Mandatory=$false)] <# Any additional flags to pass to robocopy #>
$Flags
)
(Invoke-Native "& robocopy /mir '$Src' '$Dst' /R:0 $Flags" $robocopy_success) | Write-Debug
if ($LASTEXITCODE -gt 7) {
Write-Error ("Copy failed. Try re-running with -Debug to see more details.{0}Source: {1}{0}Destination: {2}{0}Flags: {3}{0}Error code: {4}" -f "`n`t", $Src, $Dst, ($Flags -Join " "), $LASTEXITCODE)
}
}
function SyncSubdirectory {
<#
.SYNOPSIS
Sync a single subdirectory from a source directory to a destination.
.DESCRIPTION
Given a source directory Src with a subdirectory Subdir, recreate Subdir
as a subdirectory under Dst.
#>
param(
[parameter(Mandatory=$true)] <# The source directory containing the subirectory to sync. #>
$Src,
[parameter(Mandatory=$true)] <# The destination directory that may or may not yet contain the subdirectory being synchronized #>
$Dst,
[parameter(Mandatory=$true)] <# The name of the subdirectory to synchronize #>
$Subdir,
[parameter(Mandatory=$false)] <# Any additional flags to pass to robocopy #>
$Flags
)
$Paths = Join-Path -Path @($Src, $Dst) -ChildPath $Subdir
SyncDirectory $Paths[0] $Paths[1] $Flags
}
function SyncSubdirectories {
<#
.SYNOPSIS
Recreate each subdirectory from the source in the destination.
.DESCRIPTION
For each subdirectory contained in the source, synchronize with a
corresponding subdirectory in the destination. This does not synchronize
non-directory files from the source to the destination, nor does it
purge "extra" subdirectories in the destination where the source does
not contain such directories.
#>
param(
[parameter(Mandatory=$true)] <# The source directory #>
$Src,
[parameter(Mandatory=$true)] <# The destination directory #>
$Dst,
[parameter(Mandatory=$false)] <# Any additional flags to pass to robocopy #>
$Flags
)
Get-ChildItem $Src -Directory | ForEach-Object { SyncSubdirectory $Src $Dst $_.Name $Flags }
}
function ConvertFrom-PSCustomObject {
<#
.SYNOPSIS
Recursively convert a PSCustomObject to a hashtable.
.DESCRIPTION
Converts a set of (potentially nested) PSCustomObjects into an easier-to-
manipulate set of (potentially nested) hashtables. This operation does not
recurse into arrays; any PSCustomObjects embedded in arrays will be left
as-is.
.OUTPUT hashtable
#>
param(
[parameter(Mandatory=$true)]
[PSCustomObject]$object <# The PSCustomeObject to recursively convert to a hashtable #>
)
$retval = @{}
$object.PSObject.Properties |% {
$value = $null
if ($_.Value -ne $null -and $_.Value.GetType().Name -eq "PSCustomObject") {
$value = ConvertFrom-PSCustomObject $_.Value
} else {
$value = $_.Value
}
$retval.Add($_.Name, $value)
}
return $retval
}
function Resolve-Url {
<#
.SYNOPSIS
Recursively follow URL redirections until a non-redirecting URL is reached.
.DESCRIPTION
Chase URL redirections (e.g., FWLinks, safe links, URL-shortener links)
until a non-redirection URL is found, or the redirection chain is deemed
to be too long.
.OUTPUT System.Uri
#>
param(
[Parameter(Mandatory=$true)]
[String]$url <# The URL to (recursively) resolve to a concrete target. #>
)
$orig = $url
$result = $null
$depth = 0
$maxdepth = 10
do {
if ($depth -ge $maxdepth) {
Write-Error "Unable to resolve $orig after $maxdepth redirects."
}
$depth++
$resolve = [Net.WebRequest]::Create($url)
$resolve.Method = "HEAD"
$resolve.AllowAutoRedirect = $false
$result = $resolve.GetResponse()
$url = $result.GetResponseHeader("Location")
} while ($result.StatusCode -eq "Redirect")
if ($result.StatusCode -ne "OK") {
Write-Error ("Unable to resolve {0} due to status code {1}" -f $orig, $result.StatusCode)
}
return $result.ResponseUri
}
function Save-Url {
<#
.SYNOPSIS
Given a URL, download the target file to the same path as the currently-
running script.
.DESCRIPTION
Download a file referenced by a URL, with some added niceties:
- Tell the user the file is being downloaded
- Skip the download if the file already exists
- Keep track of partial downloads, and don't count them as "already
downloaded" if they're interrupted
Optionally, an output file name can be specified, and it will be used. If
none is specified, then the file name is determined from the (fully
resolved) URL that was provided.
.OUTPUT string
#>
param(
[Parameter(Mandatory=$true)]
[String]$url, <# URL to download #>
[Parameter(Mandatory=$true)]
[String]$name, <# A friendly name describing what (functionally) is being downloaded; for the user. #>
[Parameter(Mandatory=$false)]
[String]$output = $null <# An optional file name to download the file as. Just a file name -- not a path! #>
)
$res = (Resolve-Url $url)
# If the filename is not specified, use the filename in the URL.
if ([string]::IsNullOrEmpty($output)) {
$output = (Split-Path $res.LocalPath -Leaf)
}
$File = Join-Path $PSScriptRoot $output
if (!(Test-Path $File)) {
Write-Host "Downloading $name... " -NoNewline
$TmpFile = "${File}.downloading"
# Clean up any existing (unfinished, previous) download.
Remove-Item $TmpFile -Force -ErrorAction SilentlyContinue
# Download to the temp file, then rename when the download is complete
(New-Object System.Net.WebClient).DownloadFile($res, $TmpFile)
Rename-Item $TmpFile $File -Force
Write-Host "done"
} else {
Write-Host "Found $name already downloaded."
}
return $File
}
function Test-Signature {
<#
.SYNOPSIS
Verify the AuthentiCode signature of a file, deleting the file and writing
an error if it fails verification.
.DESCRIPTION
Given a path, check that the target file has a valid AuthentiCode signature.
If it does not, delete the file, and write an error to the error stream.
#>
param(
[Parameter(Mandatory=$true)]
[String]$Path <# The path of the file to verify the Authenticode signature of. #>
)
if (!(Test-Path $Path)) {
Write-Error ("File does not exist: {0}" -f $Path)
}
$name = (Get-Item $Path).Name
Write-Host ("Validating signature for {0}... " -f $name) -NoNewline
switch ((Get-AuthenticodeSignature $Path).Status) {
("Valid") {
Write-Host "success."
}
default {
Write-Host "failed."
# Invalid files should not remain where they could do harm.
Remove-Item $Path | Write-Debug
Write-Error ("File {0} failed signature validation." -f $name)
}
}
}
function PrintWhereToGetLangpacks {
param(
[parameter(Mandatory=$false)]
[switch]$IsOem
)
if ($IsOem) {
Write-Host (" OEMs: http://go.microsoft.com/fwlink/?LinkId=131359")
Write-Host (" System builders: http://go.microsoft.com/fwlink/?LinkId=131358")
} else {
Write-Host (" MPSA customers: http://go.microsoft.com/fwlink/?LinkId=125893")
Write-Host (" Other volume licensees: http://www.microsoft.com/licensing/servicecenter")
}
}
function PrintWhereToGetMedia {
param(
[parameter(Mandatory=$false)]
[switch]$IsOem
)
if ($IsOem) {
Write-Host (" OEMs must order physical Windows 10 Enterprise IoT media.")
} else {
Write-Host (" Enterprise customers can access Windows 10 Enterprise media from the Volume Licensing Service Center:")
Write-Host (" http://www.microsoft.com/licensing/servicecenter")
}
if ($script:SrsKitIsoSize -eq $null) {
return
}
Write-Host ("")
Write-Host (" The correct media for this release has the following characteristics:")
Write-Host ("")
Write-Host (" Major release: $script:SrsKitHumanVersion")
if (!$IsOem) {
Write-Host (" Name in VLSC: $script:SrsKitVlscName")
}
Write-Host (" Size (bytes): $script:SrsKitIsoSize")
Write-Host (" SHA256: $script:SrsKitIsoSha256")
Write-Host ("")
Write-Host (" You must supply an ISO that matches the exact characteristics above.")
}
function Render-Menu {
<#
.SYNOPSIS
Present a data-driven menu system to the user.
.DESCRIPTION
Render a data-driven menu system to guide the user through more complicated
decision-making processes.
.NOTES
Right now, the menu system is used only for selecting which driver pack to
download.
Action: Download
Parameters:
- Targets: an array of strings (URLs)
Description:
Chases redirects and downloads each URL listed in the "Targets" array.
Verifies the downloaded file's AuthentiCode signature.
Returns:
a string (file path) for each downloaded file.
Action: Menu
Parameters:
- Targets: an array of other MenuItem names (each must be a key in $MenuItems)
- Message: Optional. The prompt text to use when asking for the user's
selection.
Description:
Presents a menu, composed of the names listed in "Targets," to the user. The
menu item that is selected by the user is then recursively passed to
Render-Menu for processing.
Action: Redirect
Parameters:
- Target: A MenuItem name (must be a key in $MenuItems)
Description:
The menu item indicated by "Target" is recursively passed to Render-Menu
for processing.
Action: Warn
Parameters:
- Message: The warning to display to the user
Description:
Displays a warning consisting of the "Message" text to the user.
.OUTPUT string
One or more strings, each representing a downloaded file.
#>
[CmdletBinding()]
param(
[parameter(Mandatory=$true)]
$MenuItem, <# The initial menu item to process #>
[parameter(Mandatory=$true)]
$MenuItems, <# The menu items (recursively) referenced by the initial menu item #>
[parameter(Mandatory=$true)]
[hashtable]$Variables
)
if ($MenuItem.ContainsKey("Variables")) {
foreach ($Key in $MenuItem["Variables"].Keys) {
if ($Variables.ContainsKey($Key)) {
$Variables[$Key] = $MenuItem["Variables"][$Key]
} else {
$Variables.Add($Key, $MenuItem["Variables"][$Key])
}
}
}
Switch ($MenuItem.Action) {
"Download" {
Write-Verbose "Processing download menu entry."
ForEach ($URL in $MenuItem["Targets"]) {
$file = (Save-Url $URL "driver")
Test-Signature $file
Write-Output $file
}
}
"Menu" {
Write-Verbose "Processing nested menu entry."
$Options = $MenuItem["Targets"]
$Prompt = @{}
if ($MenuItem.ContainsKey("Message")) {
$Prompt = @{ "Prompt"=($MenuItem["Message"]) }
}
$Selection = $MenuItem["Targets"][(Get-TextListSelection -Options $Options -AllowDefault:$false @Prompt)]
Render-Menu -MenuItem $MenuItems[$Selection] -MenuItems $MenuItems -Variables $Variables
}
"Redirect" {
Write-Verbose ("Redirecting to {0}" -f $MenuItem["Target"])
Render-Menu -MenuItem $MenuItems[$MenuItem["Target"]] -MenuItems $MenuItems -Variables $Variables
}
"Warn" {
Write-Warning $MenuItem["Message"]
}
}
}
function Invoke-Native {
<#
.SYNOPSIS
Run a native command and process its exit code.
.DESCRIPTION
Invoke a command line specified in $command, and check the resulting $LASTEXITCODE against
$success to determine if the command succeeded or failed. If the command failed, error out.
#>
[CmdletBinding()]
param(
[parameter(Mandatory=$true)]
[string]$command, <# The native command to execute. #>
[parameter(Mandatory=$false)]
[ScriptBlock]$success = {$_ -eq 0} <# Test of $_ (last exit code) that returns $true if $command was successful, $false otherwise. #>
)
Invoke-Expression $command
$result = $LASTEXITCODE
if (!($result |% $success)) {
Write-Error "Command '$command' failed test '$success' with code '$result'."
exit 1
}
}
function Expand-Archive {
<#
.SYNOPSIS
Extract files from supported archives.
.NOTES
Supported file types are .msi and .cab.
#>
[CmdletBinding()]
param(
[parameter(Mandatory=$true)]
[string]$source, <# The archive file to expand. #>
[parameter(Mandatory=$true)]
[string]$destination <# The directory to place the extracted archive files in. #>
)
if (!(Test-Path $destination)) {
mkdir $destination | Write-Debug
}
switch ([IO.Path]::GetExtension($source)) {
".msi" {
Start-Process "msiexec" -ArgumentList ('/a "{0}" /qn TARGETDIR="{1}"' -f $source, $destination) -NoNewWindow -Wait
}
".cab" {
(& expand.exe "$source" -F:* "$destination") | Write-Debug
}
default {
Write-Error "Unsupported archive type."
exit 1
}
}
}
function Write-Transcript {
<#
.SYNOPSIS
Write diagnostic strings to the transcript, while keeping them
unobtrusive in the normal script output.
#>
[CmdletBinding()]
param(
[parameter(Mandatory=$true)]
[string]$message
)
Write-Host -ForegroundColor (Get-Host).UI.RawUI.BackgroundColor $message
}
####
## Start of main script
####
Start-Transcript
$WindowsIsoMount = $null
try {
$AutoUnattendCompatLevel = 2
# Set the default proxy to use default credentials.
# .NET really should do this (and can, via System.Net DefaultProxy's "UseDefaultCredentials" flag), but
# that flag is not set by default, and getting it set external to this script is unreasonably cumbersome.
# Setting this value once, here, is sufficient for all further instances in this script to use the
# default credentials.
(New-Object System.Net.WebClient).Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
# Just creating a lower scope for the temp vars.
$ActualRuntime = "0.0.0.0"
if ($true) {
# Build a complete version string for the current OS this script is running on.
$a = [System.Environment]::OSVersion.Version
$b = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name UBR).UBR
$ActualRuntime = [version]::New($a.Major, $a.Minor, $a.Build, $b)
}
# Warn about versions of Windows the script may not be tested with.
# This ONLY has to do with the machine this script is ACTIVELY RUNNING ON.
[version]$ScriptMinimumTestedRuntime = [version]::New("10", "0", "19045", "2604")
if ($ActualRuntime -lt $ScriptMinimumTestedRuntime) {
Write-Warning "This version of Windows may not be new enough to run this script."
Write-Warning "If you encounter problems, please update to the latest widely-available version of Windows."
}
Write-Host "This script is running on OS build $ActualRuntime"
# We have to do the copy-paste check first, as an "exit" from a copy-paste context will
# close the PowerShell instance (even PowerShell ISE), and prevent other exit-inducing
# errors from being seen.
if ([string]::IsNullOrEmpty($PSCommandPath)) {
Write-Host "This script must be saved to a file, and run as a script."
Write-Host "It cannot be copy-pasted into a PowerShell prompt."
# PowerShell ISE doesn't allow reading a key, so just wait a day...
if (Test-Path Variable:psISE) {
Start-Sleep -Seconds (60*60*24)
exit
}
# Wait for the user to see the error and acknowledge before closing the shell.
Write-Host -NoNewLine 'Press any key to continue...'
$Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown') | Out-Null
exit
}
# DISM commands don't work in 32-bit PowerShell.
try {
if (!([Environment]::Is64BitProcess)) {
Write-Host "This script must be run from 64-bit PowerShell."
exit
}
} catch {
Write-Host "Please make sure you have the latest version of PowerShell and the .NET runtime installed."
exit
}
# Dot-sourcing is unecessary for this script, and has weird behaviors/side-effects.
# Don't permit it.
if ($MyInvocation.InvocationName -eq ".") {
Write-Host "This script does not support being 'dot sourced.'"
Write-Host "Please call the script using only its full or relative path, without a preceding dot/period."
exit
}
# Like dot-sourcing, PowerShell ISE executes stuff in a way that causes weird behaviors/side-effects,
# and is generally a hassle (and unecessary) to support.
if (Test-Path Variable:psISE) {
Write-Host "This script does not support being run in Powershell ISE."
Write-Host "Please call this script using the normal PowerShell prompt, or by passing the script name directly to the PowerShell.exe executable."
exit
}
# Have to be admin to do things like DISM commands.
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
[Security.Principal.WindowsBuiltInRole] "Administrator")) {