forked from microsoft/SurfaceDeploymentAccelerator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CreateSurfaceWindowsImage.ps1
2437 lines (2075 loc) · 96.7 KB
/
CreateSurfaceWindowsImage.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
This script downloads the ADK and WinPE addon.
.DESCRIPTION
This script downloads the ADK and WinPE addon, uninstalls any previous versions and installs the version referenced by the aka.ms link in the script.
// *************
// * CAUTION *
// *************
Please review this script THOROUGHLY before applying, and disable changes below as necessary to suit your current environment.
This script is provided AS-IS - usage of this source assumes that you are at the very least familiar with PowerShell, and the
tools used to create and debug this script.
In other words, if you break it, you get to keep the pieces.
.EXAMPLE
.\CreateSurfaceWindowsImage.ps1 -ISO <ISO path> -OSSKU Pro -Device SurfacePro7
.NOTES
Author: Microsoft
Last Update: 6th May 2020
Version: 1.1.0
Version 1.1.0
- Added support for local driver paths
- Added support for Surface Go 2 and Surface Book 3
Version 1.0.0
- Initial release
#>
# Parse Params:
[CmdletBinding()]
Param(
[Parameter(
Position=1,
Mandatory=$True,
HelpMessage="Location of ISO containing Windows image (ex. D:\18362.1.190318-1202.19h1_release_CLIENT_BUSINESS_VOL_x64FRE_en-us.iso) to use as template"
)]
[string]$ISO,
[Parameter(
Position=2,
Mandatory=$False,
HelpMessage="What SKU should be used inside ISO (valid parameters are 'Pro' or 'Enterprise'), default is Pro"
)]
[ValidateSet('Pro', 'Enterprise')]
[string]$OSSKU = 'Pro',
[Parameter(
Position=3,
Mandatory=$True,
HelpMessage="Destination folder to where resulting WIM image(s) should be placed"
)]
[string]$DestinationFolder,
[Parameter(
Position=4,
Mandatory=$False,
HelpMessage="Architecture of image being used (valid options are x64 and ARM64), default is x64"
)]
[ValidateSet('x64', 'ARM64')]
[string]$Architecture = 'x64',
[Parameter(
Position=5,
Mandatory=$False,
HelpMessage="Install .NET 3.5 (bool true/false, default is false)"
)]
[bool]$DotNet35 = $False,
[Parameter(
Position=6,
Mandatory=$False,
HelpMessage="Add latest servicing stack update (bool true/false, default is true)"
)]
[bool]$ServicingStack = $True,
[Parameter(
Position=7,
Mandatory=$False,
HelpMessage="Add latest cumulative update (bool true/false, default is true)"
)]
[bool]$CumulativeUpdate = $True,
[Parameter(
Position=8,
Mandatory=$False,
HelpMessage="Add latest Adobe Flash Player Security update (bool true/false, default is true)"
)]
[bool]$AdobeFlashUpdate = $True,
[Parameter(
Position=9,
Mandatory=$False,
HelpMessage="Surface device type to add drivers to image for, if not specified no drivers injected - Custom can be used if using with a non-Surface device"
)]
[ValidateSet('SurfacePro4', 'SurfacePro5', 'SurfacePro6', 'SurfacePro7', 'SurfaceLaptop', 'SurfaceLaptop2', 'SurfaceLaptop3', 'SurfaceBook', 'SurfaceBook2', 'SurfaceBook3', 'SurfaceStudio', 'SurfaceStudio2', 'SurfaceGo', 'SurfaceGoLTE', 'SurfaceGo2', 'Custom')]
[string]$Device = "SurfacePro7",
[Parameter(
Position=10,
Mandatory=$False,
HelpMessage="Create USB key when finished (bool true/false, default is false)"
)]
[bool]$CreateUSB = $False,
[Parameter(
Position=11,
Mandatory=$False,
HelpMessage="Create bootable ISO file (useful for testing) when finished (bool true/false, default is false)"
)]
[bool]$CreateISO = $False,
[Parameter(
Position=12,
Mandatory=$False,
HelpMessage="Location of Windows ADK installation"
)]
[string]$WindowsKitsInstall = "${env:ProgramFiles(x86)}\Windows Kits\10\Assessment and Deployment Kit",
[Parameter(
Position=13,
Mandatory=$False,
HelpMessage="Use BITS for downloads"
)]
[bool]$BITSTransfer = $True,
[Parameter(
Position=14,
Mandatory=$False,
HelpMessage="Edit Install.wim"
)]
[bool]$InstallWIM = $True,
[Parameter(
Position=15,
Mandatory=$False,
HelpMessage="Edit boot.wim"
)]
[bool]$BootWIM = $True,
[Parameter(
Position=16,
Mandatory=$False,
HelpMessage="Keep original unsplit WIM even if resulting image size >4GB (bool true false, default is true)"
)]
[bool]$KeepOriginalWIM = $True,
[Parameter(
Position=17,
Mandatory=$False,
HelpMessage="Use a local driver path instead of downloading an MSI (bool true false, default is false)"
)]
[bool]$UseLocalDriverPath = $False,
[Parameter(
Position=18,
Mandatory=$False,
HelpMessage="Path to an extracted driver folder - required if you set UseLocalDriverPath variable to true or script will not find any drivers to inject"
)]
[string]$LocalDriverPath,
[Parameter(
Position=19,
Mandatory=$False,
HelpMessage="WinPE language to be set"
)]
[ValidateSet('ar-sa', 'bg-bg', 'cs-cz', 'da-dk', 'de-de', 'el-gr', 'en-gb', 'en-us', 'es-es', 'es-mx', 'et-ee', 'fi-fi', 'fr-ca', 'fr-fr', 'he-il', 'hr-hr', 'hu-hu', 'it-it', 'ja-jp', 'ko-kr', 'lt-lt', 'lv-lv', 'nb-no', 'nl-nl', 'pl-pl', 'pt-br', 'pt-pt', 'ro-ro', 'ru-ru', 'sk-sk', 'sl-si', 'sr-latn-rs', 'sv-se', 'th-th', 'tr-tr', 'uk-ua', 'zh-cn', 'zh-tw')]
[string]$Language = "en-us",
[Parameter(
Position=20,
Mandatory=$False,
HelpMessage="If you want to use a network share to get the install.wim. (bool true false, default is false)"
)]
[bool]$WDS = $False
)
Function Receive-Output
{
Param(
$Color
)
Process { Write-Host $_ -ForegroundColor $Color }
}
Function AddHeaderSpace
{
Write-Output "This space intentionally left blank..." | Receive-Output -Color Gray
Write-Output ""
Write-Output ""
Write-Output ""
Write-Output ""
Write-Output ""
Write-Output ""
}
Function CheckIfRunAsAdmin
{
If (!([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] “Administrator”))
{
Write-Warning “You do not have Administrator rights to run this script!`nPlease re-run this script as an Administrator to continue.”
Break
}
}
Function Check-Internet
{
While (([Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]‘{DCB00C01-570F-4A9B-8D69-199FDBA5723B}’)).IsConnectedToInternet) -eq $False)
{
Write-Output "No internet connection detected. Retrying in 60 seconds..." | Receive-Output -Color Yellow
Start-Sleep -Seconds 60
}
}
Function Get-RedirectedUrl
{
Param(
$URL
)
$Request = [System.Net.WebRequest]::Create($URL)
$Request.AllowAutoRedirect=$false
$Request.Timeout = 3000
$Response = $Request.GetResponse()
If ($Response.ResponseUri)
{
$Response.GetResponseHeader("Location")
}
$Response.Close()
}
Function DownloadFile
{
Param(
[System.Uri]$URL,
[System.String]$Path
)
# Get file name
Start-Sleep 1
If ($URL.Host -like "*aka.ms*")
{
$ActualURL = Get-RedirectedUrl -URL "$URL" -ErrorAction Continue -WarningAction Continue
$FileName = $ActualURL.Substring($ActualURL.LastIndexOf("/") + 1)
Write-Output "aka.ms link: $URL" | Receive-Output -Color Gray
Write-Output "Actual URL: $ActualURL" | Receive-Output -Color Gray
Write-Output "File name: $FileName" | Receive-Output -Color White
Write-Output ""
}
Else
{
$ActualURL = $URL
$FileName = $URL.AbsoluteUri.Substring($URL.AbsoluteUri.LastIndexOf("/") +1)
Write-Output "Actual URL: $URL" | Receive-Output -Color Gray
Write-Output "File name: $FileName" | Receive-Output -Color White
Write-Output ""
}
$global:Output = "$Path\$Filename"
# If file does not exist, download file
If (!(Test-Path -Path "$global:Output"))
{
Write-Output "Using BITS to download files" | Receive-Output -Color White
Write-Output "Downloading $FileName to $Path..." | Receive-Output -Color White
Write-Output ""
Import-Module BitsTransfer
Start-BitsTransfer -Source $ActualURL -Destination "$global:Output" -Priority Foreground -RetryTimeout 60 -RetryInterval 120
}
Else
{
Write-Output "File $global:Output exists, skipping file download." | Receive-Output -Color Gray
Write-Output ""
}
Return $global:Output
}
# Using this to avoid reinstalling and breaking installed Win32 MSI apps via WMI calls to Win32_Product!
Function GetInstalledAppStatus
{
Param(
$AppName,
$AppVersion
)
$OSArch = Get-WmiObject -Class Win32_OperatingSystem
If ($OSArch.OSArchitecture -eq "64-bit")
{
$InstalledPrograms32 = Get-ChildItem "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall" -Recurse
$InstalledPrograms64 = Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall" -Recurse
ForEach ($Item in $InstalledPrograms32)
{
If ($Item.GetValue("DisplayName") -like "*$AppName*" -and ($Item.GetValue("DisplayVersion")) -like "*$AppVersion*")
{
$global:IsInstalled = $true
Break
}
}
ForEach ($Item in $InstalledPrograms64)
{
If ($Item.GetValue("DisplayName") -like "*$AppName*" -and ($Item.GetValue("DisplayVersion")) -like "*$AppVersion*")
{
$global:IsInstalled = $true
Break
}
}
}
Else
{
$InstalledPrograms32 = Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall" -Recurse
ForEach ($Item in $InstalledPrograms32)
{
If ($Item.GetValue("DisplayName") -like "*$AppName*" -and ($Item.GetValue("DisplayVersion")) -like "*$AppVersion*")
{
$global:IsInstalled = $true
Break
}
}
}
}
Function PrereqCheck
{
# Check for admin rights
CheckIfRunAsAdmin
# Windows Version Check
$OSCaption = (Get-WmiObject win32_operatingsystem).caption
If ($OSCaption -like "Microsoft Windows 10*" -or $OSCaption -like "Microsoft Windows Server 2016*" -or $OSCaption -like "Microsoft Windows Server 2019*")
{
# All OK
}
Else
{
Write-Warning "$Env:Computername You must use Windows 10 or Windows Server 2016/2019 when servicing Windows 10 offline, with the latest ADK installed."
Write-Warning "$Env:Computername Aborting script..."
Exit
}
# Validating that the ADK is installed
If (!(Test-Path $DISMFile))
{
Write-Warning "DISM in Windows ADK not found, attempting installation..." | Receive-Output -Color Yellow
Write-Output ""
$global:Output = $null
$global:IsInstalled = $null
$ScriptFolder = $DestinationFolder
$ADKSourceFile = "$ScriptFolder\adksetup.exe"
$WinPESourceFile = "$ScriptFolder\adkwinpesetup.exe"
$ADKArguments = " /features OptionId.DeploymentTools /quiet"
$WinPEArguments = " /features OptionId.WindowsPreinstallationEnvironment /quiet"
GetInstalledAppStatus -AppName "Windows Assessment and Deployment Kit - Windows 10" -AppVersion "10.1.18362"
If ($global:IsInstalled -eq $null)
{
# ADK cannot do an "in place" upgrade. Do we need to uninstall the old version?
$uninstall32 = gci "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall" | ForEach { gp $_.PSPath } | ? { $_ -like "*Assessment and Deployment*" } | select UninstallString
$uninstall64 = gci "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" | ForEach { gp $_.PSPath } | ? { $_ -like "*Assessment and Deployment*" } | select UninstallString
If ($uninstall64)
{
ForEach ($u in $uninstall64)
{
$u = $u.UninstallString -Replace "/uninstall",""
$u = $u.Trim()
Write-Output "Command is $u Args are /uninstall /quiet" | Receive-Output -Color Gray
Start-Process -filepath $u -argumentlist "/uninstall /quiet" -wait
}
}
If ($uninstall32)
{
ForEach ($u in $uninstall32)
{
$u = $u.UninstallString -Replace "/uninstall",""
$u = $u.Trim()
Write-Output "Command is $u Args are /uninstall /quiet" | Receive-Output -Color Gray
Start-Process -filepath $u -argumentlist "/uninstall /quiet" -wait
}
}
If ((Test-Path -Path $ADKSourceFile) -eq $true)
{
$SourceFilePath = $(Get-Item $SourceFile).FullName
Write-Output "Found Installation files for ADK at $SourceFilePath" | Receive-Output -Color Gray
}
Else
{
Check-Internet
$URL = "https://aka.ms/sdaadk/1903"
$Path = "$env:TEMP"
DownloadFile $URL $Path
$SourceFilePath = $global:Output
}
Try
{
Write-Output "Installing Windows Assessment and Deployment Kit" | Receive-Output -Color White
Start-Process -File $SourceFilePath -Arg $ADKArguments -passthru | wait-process
Write-Output "$AppName - ADK INSTALLATION SUCCESSFULLY COMPLETED" | Receive-Output -Color Green
Write-Output ""
}
Catch
{
Write-Output "$AppName - INSTALLATION ERROR - check logs in $env:TEMP\adk for more info." | Receive-Output -Color Yellow
Write-Output ""
}
}
If ((Test-Path -Path $WinPESourceFile) -eq $true)
{
$SourceFilePath = $(Get-Item $SourceFile).FullName
Write-Output "Found Installation files for ADK WinPE at $SourceFilePath" | Receive-Output -Color Gray
}
Else
{
Check-Internet
$URL = "https://aka.ms/sdaadkpe/1903"
$Path = "$env:TEMP"
DownloadFile $URL $Path
$SourceFilePath = $global:Output
}
Try
{
Write-Output "Installing Windows Assessment and Deployment Kit Windows Preinstallation Environment Add-Ons" | Receive-Output -Color White
Start-Process -File $SourceFilePath -Arg $WinPEArguments -passthru | wait-process
Write-Output "$AppName - ADK WinPE Add-Ons INSTALLATION SUCCESSFULLY COMPLETED" | Receive-Output -Color Green
Write-Output ""
}
Catch
{
Write-Output "$AppName - INSTALLATION ERROR - check logs in $env:TEMP\adkwinpeaddons for more info." | Receive-Output -Color Yellow
Write-Output ""
}
}
}
Function Download-LatestUpdates
{
Param(
$uri,
$Path,
$Date,
$Servicing,
$Cumulative,
$CumulativeDotNet,
$Adobe,
$OSBuild
)
$kbObj = Invoke-WebRequest -Uri $uri -UseBasicParsing
# Parse the Response
$global:KBGUID = $null
$kbObjectLinks = ($kbObj.Links | Where-Object {$_.id -match "_link"})
$array = @()
ForEach ($link in $kbObjectLinks)
{
$xmlNode = [XML]($link.outerHTML)
If ($xmlNode.HasChildNodes)
{
$kbId = $link.id -replace "_link", ""
$description = $xmlNode.FirstChild.InnerText.Trim()
$array += [PSCustomObject]@{
kbId = $kbId
description = $description
}
}
}
If ($array.count -gt 0)
{
If ($Servicing)
{
$global:KBGUID = $array | Where-Object {($_.description -like "*$Date*") -and ($_.description -like "*Servicing Stack Update for Windows 10*") -and ($_.description -like "*$OSBuild*") -and ($_.description -like "*$Architecture*")}
If ($global:KBGUID.Count -gt 1)
{
$largest = ($global:KBGUID | Measure-Object -Property description -Maximum)
$global:KBGUID = $global:KBGUID | Where-Object {$_.description -eq $largest.Maximum}
}
}
If ($Cumulative)
{
$global:KBGUID = $array | Where-Object {($_.description -like "*$Date*") -and ($_.description -like "*Cumulative Update for Windows 10*") -and ($_.description -like "*$OSBuild*") -and ($_.description -like "*$Architecture*")}
If ($global:KBGUID.Count -gt 1)
{
$largest = ($global:KBGUID | Measure-Object -Property description -Maximum)
$global:KBGUID = $global:KBGUID | Where-Object {$_.description -eq $largest.Maximum}
}
}
If ($CumulativeDotNet)
{
$global:KBGUID = $array | Where-Object {($_.description -like "*$Date*") -and ($_.description -like "*Cumulative Update for .NET Framework*") -and ($_.description -like "*Windows 10*") -and ($_.description -like "*$OSBuild*")}
}
If ($Adobe)
{
$global:KBGUID = $array | Where-Object {($_.description -like "*$Date*") -and ($_.description -like "*Security Update for Adobe Flash Player for Windows 10*") -and ($_.description -like "*$OSBuild*")}
}
$updatesFound = $false
ForEach ($Object in $global:KBGUID)
{
$kb = $Object.kbId
$curTxt = $Object.description
##Create Post Request to get the Download URL of the Update
$Post = @{ size = 0; updateID = $kb; uidInfo = $kb } | ConvertTo-Json -Compress
$PostBody = @{ updateIDs = "[$Post]" }
## Fetch and parse the download URL
$PostRes = (Invoke-WebRequest -Uri 'http://www.catalog.update.microsoft.com/DownloadDialog.aspx' -Method Post -Body $postBody).content
$DownloadLinks = ($PostRes | Select-String -AllMatches -Pattern "(http[s]?\://download\.windowsupdate\.com\/[^\'\""]*)" | Select-Object -Unique | ForEach-Object { [PSCustomObject] @{ Source = $_.matches.value } } ).source
If ($DownloadLinks)
{
$updatesFound = $true
If ($DownloadLinks.Count -gt 1)
{
ForEach ($URL in $DownloadLinks)
{
Write-Output "Download found:" | Receive-Output -Color Green
Write-Output $curTxt | Receive-Output -Color White
Write-Output ""
Write-Output ""
DownloadFile -URL $URL -Path "$Path"
Write-Output ""
Write-Output ""
Write-Output ""
Write-Output ""
Write-Output ""
}
}
Else
{
Write-Output "Download found:" | Receive-Output -Color Green
Write-Output $curTxt | Receive-Output -Color White
Write-Output ""
Write-Output ""
DownloadFile -URL $DownloadLinks -Path "$Path"
Write-Output ""
Write-Output ""
Write-Output ""
Write-Output ""
Write-Output ""
}
}
}
if(!($updatesFound))
{
$global:KBGUID = $null
Write-Output "No update found." | Receive-Output -Color Yellow
}
}
}
Function Get-LatestUpdates
{
Param(
$Servicing = $False,
$Cumulative = $False,
$CumulativeDotNet = $False,
$Adobe = $False,
$Path,
$Date,
$OSBuild,
$Architecture
)
If (!($Path))
{
$Path = $WorkingDirPath
}
If (!(Test-Path -Path $Path))
{
New-Item -path "$Path" -ItemType "directory" | Out-Null
}
If (!($Date))
{
$Date = Get-Date -Format "yyyy-MM"
}
$ServicingURI = "http://www.catalog.update.microsoft.com/Search.aspx?q=" + $Date + " Servicing Stack " + $Architecture + " windows 10 " + $OSBuild
$CumulativeURI = "http://www.catalog.update.microsoft.com/Search.aspx?q=" + $Date + ' "cumulative update for Windows 10" ' + $Architecture + " " + $OSBuild
$CumulativeDotNetURI = "http://www.catalog.update.microsoft.com/Search.aspx?q=" + $Date + ' "cumulative update for .NET Framework" ' + $Architecture + " windows 10 " + $OSBuild
$AdobeURI = "http://www.catalog.update.microsoft.com/Search.aspx?q=" + $Date + ' "Security Update for Adobe Flash Player for Windows 10" ' + $Architecture + " " + $OSBuild
If ($Servicing)
{
Write-Output "Attempting to find and download Servicing Stack updates for $Architecture Windows 10 version $OSBuild for month $Date..." | Receive-Output -Color Gray
$uri = $ServicingURI
Download-LatestUpdates -uri $uri -Path $Path -Date $Date -Servicing $True -Cumulative $False -CumulativeDotNet $False -Adobe $False -OSBuild $OSBuild
If (!($global:KBGUID))
{
While (!($global:KBGUID))
{
If ($LoopBreak -le 5)
{
$LoopBreak++
Start-Sleep 1
$NewDate = (Get-Date).AddMonths(-$LoopBreak)
$NewDate = $NewDate.ToString("yyyy-MM")
Write-Output "No update found for month ($Date) - attempting previous month ($NewDate)..." | Receive-Output -Color Yellow
$Date = $NewDate
$ServicingURI = "http://www.catalog.update.microsoft.com/Search.aspx?q=" + $Date + " Servicing Stack " + $Architecture + " windows 10 " + $OSBuild
$uri = $ServicingURI
Download-LatestUpdates -uri $uri -Path $Path -Date $Date -Servicing $True -Cumulative $False -CumulativeDotNet $False -Adobe $False -OSBuild $OSBuild
}
Else
{
Write-Output "Unable to find update for past $LoopBreak months of searches. Continuing..." | Receive-Output -Color Yellow
Break
}
}
}
$LoopBreak = $null
$Date = Get-Date -Format "yyyy-MM"
}
If ($Cumulative)
{
Write-Output "Attempting to find and download Cumulative Update updates for $Architecture Windows 10 version $OSBuild for month $Date..." | Receive-Output -Color Gray
$uri = $CumulativeURI
Download-LatestUpdates -uri $uri -Path $Path -Date $Date -Servicing $False -Cumulative $True -CumulativeDotNet $False -Adobe $False -OSBuild $OSBuild
If (!($global:KBGUID))
{
While (!($global:KBGUID))
{
If ($LoopBreak -le 5)
{
$LoopBreak++
Start-Sleep 1
$NewDate = (Get-Date).AddMonths(-$LoopBreak)
$NewDate = $NewDate.ToString("yyyy-MM")
Write-Output "No update found for month ($Date) - attempting previous month ($NewDate)..." | Receive-Output -Color Yellow
$Date = $NewDate
$CumulativeURI = "http://www.catalog.update.microsoft.com/Search.aspx?q=" + $Date + ' "cumulative update for Windows 10" ' + $Architecture + " " + $OSBuild
$uri = $CumulativeURI
Download-LatestUpdates -uri $uri -Path $Path -Date $Date -Servicing $False -Cumulative $True -CumulativeDotNet $False -Adobe $False -OSBuild $OSBuild
}
Else
{
Write-Output "Unable to find update for past $LoopBreak months of searches. Continuing..." | Receive-Output -Color Yellow
Break
}
}
}
$Date = Get-Date -Format "yyyy-MM"
$LoopBreak = $null
}
If ($CumulativeDotNet)
{
Write-Output "Attempting to find and download Cumulative .NET Framework Update updates for $Architecture Windows 10 version $OSBuild for month $Date..." | Receive-Output -Color Gray
$uri = $CumulativeDotNetURI
Download-LatestUpdates -uri $uri -Path $Path -Date $Date -Servicing $False -Cumulative $False -CumulativeDotNet $True -Adobe $False -OSBuild $OSBuild
If (!($global:KBGUID))
{
While (!($global:KBGUID))
{
If ($LoopBreak -le 5)
{
$LoopBreak++
Start-Sleep 1
$NewDate = (Get-Date).AddMonths(-$LoopBreak)
$NewDate = $NewDate.ToString("yyyy-MM")
Write-Output "No update found for month ($Date) - attempting previous month ($NewDate)..." | Receive-Output -Color Yellow
$Date = $NewDate
$CumulativeDotNetURI = "http://www.catalog.update.microsoft.com/Search.aspx?q=" + $Date + ' "cumulative update for .NET Framework" ' + $Architecture + " windows 10 " + $OSBuild
$uri = $CumulativeDotNetURI
Download-LatestUpdates -uri $uri -Path $Path -Date $Date -Servicing $False -Cumulative $False -CumulativeDotNet $True -Adobe $False -OSBuild $OSBuild
}
Else
{
Write-Output "Unable to find update for past $LoopBreak months of searches. Continuing..." | Receive-Output -Color Yellow
Break
}
}
}
$Date = Get-Date -Format "yyyy-MM"
$LoopBreak = $null
}
If ($Adobe)
{
Write-Output "Attempting to find and download Adobe Flash Player updates for $Architecture Windows 10 version $OSBuild for month $Date..." | Receive-Output -Color Gray
$uri = $AdobeURI
Download-LatestUpdates -uri $uri -Path $Path -Date $Date -Servicing $False -Cumulative $False -CumulativeDotNet $False -Adobe $True -OSBuild $OSBuild
If (!($global:KBGUID))
{
While (!($global:KBGUID))
{
If ($LoopBreak -le 10)
{
$LoopBreak++
Start-Sleep 1
$NewDate = (Get-Date).AddMonths(-$LoopBreak)
$NewDate = $NewDate.ToString("yyyy-MM")
Write-Output "No update found for month ($Date) - attempting previous month ($NewDate)..." | Receive-Output -Color Yellow
$Date = $NewDate
$AdobeURI = "http://www.catalog.update.microsoft.com/Search.aspx?q=" + $Date + ' "Security Update for Adobe Flash Player for Windows 10" ' + $Architecture + " " + $OSBuild
$uri = $AdobeURI
Download-LatestUpdates -uri $uri -Path $Path -Date $Date -Servicing $False -Cumulative $False -CumulativeDotNet $False -Adobe $True -OSBuild $OSBuild
}
Else
{
Write-Output "Unable to find update for past $LoopBreak month's of searches. Continuing..." | Receive-Output -Color Yellow
Break
}
}
}
$Date = Get-Date -Format "yyyy-MM"
$LoopBreak = $null
}
}
Function ExtractMSIFile
{
Param
(
$MsiFile,
$Path
)
If (Test-Path "$Path\Extract")
{
Write-Output "Deleting $Path\Extract\..." | Receive-Output -Color Gray
Get-ChildItem -Path "$Path\Extract\" -Recurse | Remove-Item -Force -Recurse
Remove-Item -Path "$Path\Extract" -Force
}
If (!(Test-Path "$Path\Extract"))
{
New-Item -Path "$Path\Extract" -ItemType "directory" | Out-Null
}
Write-Output "Extracting file $MsiFile to $Path\Extract..." | Receive-Output -Color White
Start-Process "msiexec" -ArgumentList "/a $MsiFile /qn TARGETDIR=$Path\Extract" -Wait -NoNewWindow
}
Function Get-LatestSurfaceEthernetDrivers
{
Param(
$Device,
$TempFolder
)
Write-Output ""
Write-Output ""
$DeviceDriverPath = "$TempFolder\$Device"
If ($Device -eq "SurfaceHub2S")
{
# Nothing yet
}
Else
{
$URI = "http://www.catalog.update.microsoft.com/Search.aspx?q=Surface net Windows 10"
$kbObj = Invoke-WebRequest -Uri $URI -UseBasicParsing
$global:KBGUID = $null
$kbObjectLinks = ($kbObj.Links | Where-Object {$_.id -match "_link"})
$array = @()
$kbObj = Invoke-WebRequest -Uri $uri -UseBasicParsing
# Parse the Response
$global:KBGUID = $null
$kbObjectLinks = ($kbObj.Links | Where-Object {$_.id -match "_link"})
$array = @()
ForEach ($link in $kbObjectLinks)
{
$xmlNode = [XML]($link.outerHTML)
If ($xmlNode.HasChildNodes)
{
$kbId = $link.id -replace "_link", ""
$description = $xmlNode.FirstChild.InnerText.Trim()
$array += [PSCustomObject]@{
kbId = $kbId
description = $description
}
}
}
If ($array.count -gt 0)
{
$global:KBGUID = $array | Where-Object {($_.description -like "*Surface - Net - 10.*")}
If ($global:KBGUID.Count -gt 1)
{
$largest = ($global:KBGUID | Measure-Object -Property description -Maximum)
$global:KBGUID = $global:KBGUID | Where-Object {$_.description -eq $largest.Maximum}
}
}
ForEach ($Object in $global:KBGUID)
{
$kb = $Object.kbId
$curTxt = $Object.description
##Create Post Request to get the Download URL of the Update
$Post = @{ size = 0; updateID = $kb; uidInfo = $kb } | ConvertTo-Json -Compress
$PostBody = @{ updateIDs = "[$Post]" }
## Fetch and parse the download URL
$PostRes = (Invoke-WebRequest -Uri 'http://www.catalog.update.microsoft.com/DownloadDialog.aspx' -Method Post -Body $postBody).content
$DownloadLinks = ($PostRes | Select-String -AllMatches -Pattern "(http[s]?\://download\.windowsupdate\.com\/[^\'\""]*)" | Select-Object -Unique | ForEach-Object { [PSCustomObject] @{ Source = $_.matches.value } } ).source
If ($DownloadLinks)
{
If ($DownloadLinks.Count -gt 1)
{
ForEach ($URL in $DownloadLinks)
{
Write-Output "Download found:" | Receive-Output -Color Green
Write-Output $curTxt | Receive-Output -Color White
Write-Output ""
Write-Output ""
DownloadFile -URL $URL -Path "$DeviceDriverPath"
Write-Output ""
Write-Output ""
Write-Output ""
Write-Output ""
Write-Output ""
}
}
Else
{
Write-Output "Download found:" | Receive-Output -Color Green
Write-Output $curTxt | Receive-Output -Color White
Write-Output ""
Write-Output ""
DownloadFile -URL $DownloadLinks -Path "$DeviceDriverPath"
Write-Output ""
Write-Output ""
Write-Output ""
Write-Output ""
Write-Output ""
}
}
}
}
}
Function Get-LatestDrivers
{
Param(
$Device,
$TempFolder
)
Write-Output ""
Write-Output ""
$DeviceDriverPath = "$TempFolder\$Device"
If (Test-Path "$DeviceDriverPath")
{
Write-Output "Deleting $DeviceDriverPath\..." | Receive-Output -Color Gray
Get-ChildItem -Path "$DeviceDriverPath" -Recurse | Remove-Item -Force -Recurse
Remove-Item -Path "$DeviceDriverPath" -Force
}
If (!(Test-Path "$DeviceDriverPath"))
{
New-Item -path "$DeviceDriverPath" -ItemType "directory" | Out-Null
}
If ($UseLocalDriverPath -eq $True)
{
If (!(Test-Path "$LocalDriverPath"))
{
Write-Output "$LocalDriverPath not found, continuing without drivers..." | Receive-Output -Color Yellow
$Device = $null
}
Else
{
# Use local drivers
Write-Output "Using $LocalDriverPath..." | Receive-Output -Color White
$TempDeviceDriverPath = "$DeviceDriverPath\Extract"
If (Test-Path "$TempDeviceDriverPath")
{
Write-Output "Deleting $TempDeviceDriverPath\..." | Receive-Output -Color Gray
Get-ChildItem -Path "$TempDeviceDriverPath" -Recurse | Remove-Item -Force -Recurse
Remove-Item -Path "$TempDeviceDriverPath" -Force
}
If (!(Test-Path "$TempDeviceDriverPath"))
{
New-Item -path "$TempDeviceDriverPath" -ItemType "directory" | Out-Null
}
Write-Output "Copying drivers from $LocalDriverPath to $TempDeviceDriverPath..." | Receive-Output -Color White
& xcopy.exe /herky "$LocalDriverPath" "$TempDeviceDriverPath"
Write-Output ""
}
}
Else
{
Write-Output "Downloading latest drivers for $Device, Windows 10 version $global:OSVersion..." | Receive-Output -Color White
$OSBuild = New-Object string (,@($global:OSVersion.ToCharArray() | Select-Object -Last 5))
$URL = "https://aka.ms/" + $Device + "/" + $OSBuild
$DownloadedFile = DownloadFile -URL $URL -Path "$DeviceDriverPath"
Write-Output "Downloaded File: $DownloadedFile"
$FileToExtract = $DownloadedFile
ExtractMSIFile -MsiFile $FileToExtract -Path $DeviceDriverPath
Write-Output ""
}
Write-Output "Downloading latest Surface Ethernet drivers for $Device..." | Receive-Output -Color White
Get-LatestSurfaceEthernetDrivers -Device $Device -TempFolder $TempFolder
Write-Output ""
}
Function Get-LatestVCRuntimes
{
Param(
$TempFolder
)
Write-Output ""
Write-Output ""
$VisualCRuntimePath = "$TempFolder\VCRuntimes"
If (Test-Path "$VisualCRuntimePath")
{
Write-Output "Deleting $VisualCRuntimePath\..." | Receive-Output -Color Gray
Get-ChildItem -Path "$VisualCRuntimePath" -Recurse | Remove-Item -Force -Recurse
Remove-Item -Path "$VisualCRuntimePath" -Force
}
If (!(Test-Path "$VisualCRuntimePath"))
{
New-Item -path "$VisualCRuntimePath" -ItemType "directory" | Out-Null
}
If (!(Test-Path "$VisualCRuntimePath\2013"))
{