forked from pbatard/Fido
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFido.ps1
1152 lines (1056 loc) · 42.1 KB
/
Fido.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
#
# Fido v1.20 - Retail Windows ISO Downloader
# Copyright © 2019-2021 Pete Batard <pete@akeo.ie>
# ConvertTo-ImageSource: Copyright © 2016 Chris Carter
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# NB: You must have a BOM on your .ps1 if you want Powershell to actually
# realise it should use Unicode for the UI rather than ISO-8859-1.
#region Parameters
param(
# (Optional) The title to display on the application window.
[string]$AppTitle = "Fido - Retail Windows ISO Downloader",
# (Optional) '|' separated UI localization strings.
[string]$LocData,
# (Optional) Path to a file that should be used for the UI icon.
[string]$Icon,
# (Optional) Name of a pipe the download URL should be sent to.
# If not provided, a browser window is opened instead.
[string]$PipeName,
# Headless
[switch]$Headless = $False,
[string]$cliVersionName,
[string]$cliReleaseName,
[string]$cliEditionName,
[string]$cliLanguage,
[string]$cliArch,
[string]$cliFilename = "Windows.iso"
)
#endregion
try {
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
} catch {}
Write-Host Please Wait...
#region Assembly Types
$code = @"
[DllImport("shell32.dll", CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false, ThrowOnUnmappableChar = true)]
internal static extern int ExtractIconEx(string sFile, int iIndex, out IntPtr piLargeVersion, out IntPtr piSmallVersion, int amountIcons);
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr handle, int state);
// Extract an icon from a DLL
public static Icon ExtractIcon(string file, int number, bool largeIcon)
{
IntPtr large, small;
ExtractIconEx(file, number, out large, out small, 1);
try {
return Icon.FromHandle(largeIcon ? large : small);
} catch {
return null;
}
}
"@
if ( ! $Headless ) {
if ($host.version -ge "7.0") {
Add-Type -WarningAction Ignore -IgnoreWarnings -MemberDefinition $code -Namespace Gui -UsingNamespace System.Runtime, System.IO, System.Text, System.Drawing, System.Globalization -ReferencedAssemblies System.Drawing.Common -Name Utils -ErrorAction Stop
} else {
Add-Type -MemberDefinition $code -Namespace Gui -UsingNamespace System.IO, System.Text, System.Drawing, System.Globalization -ReferencedAssemblies System.Drawing -Name Utils -ErrorAction Stop
}
Add-Type -AssemblyName PresentationFramework
# Hide the powershell window: https://stackoverflow.com/a/27992426/1069307
[Gui.Utils]::ShowWindow(([System.Diagnostics.Process]::GetCurrentProcess() | Get-Process).MainWindowHandle, 0) | Out-Null
}
#endregion
#region Data
$zh = 0x10000
$ko = 0x20000
$WindowsVersions = @(
@(
@("Windows 10", "Windows10ISO"),
@(
"21H1 (Build 19043.985 - 2021.05)",
@("Windows 10 Home/Pro", 2033),
@("Windows 10 Education", 2032),
@("Windows 10 Home China ", ($zh + 2034))
),
@(
"20H2 (Build 19042.631 - 2020.12)",
@("Windows 10 Home/Pro", 1882),
@("Windows 10 Education", 1884),
@("Windows 10 Home China ", ($zh + 1883))
),
@(
"20H2 (Build 19042.508 - 2020.10)",
@("Windows 10 Home/Pro", 1807),
@("Windows 10 Education", 1805),
@("Windows 10 Home China ", ($zh + 1806))
),
@(
"20H1 (Build 19041.264 - 2020.05)",
@("Windows 10 Home/Pro", 1626),
@("Windows 10 Education", 1625),
@("Windows 10 Home China ", ($zh + 1627))
),
@(
"19H2 (Build 18363.418 - 2019.11)",
@("Windows 10 Home/Pro", 1429),
@("Windows 10 Education", 1431),
@("Windows 10 Home China ", ($zh + 1430))
),
@(
"19H1 (Build 18362.356 - 2019.09)",
@("Windows 10 Home/Pro", 1384),
@("Windows 10 Education", 1386),
@("Windows 10 Home China ", ($zh + 1385))
),
@(
"19H1 (Build 18362.30 - 2019.05)",
@("Windows 10 Home/Pro", 1214),
@("Windows 10 Education", 1216),
@("Windows 10 Home China ", ($zh + 1215))
),
@(
"1809 R2 (Build 17763.107 - 2018.10)",
@("Windows 10 Home/Pro", 1060),
@("Windows 10 Education", 1056),
@("Windows 10 Home China ", ($zh + 1061))
),
@(
"1809 R1 (Build 17763.1 - 2018.09)",
@("Windows 10 Home/Pro", 1019),
@("Windows 10 Education", 1021),
@("Windows 10 Home China ", ($zh + 1020))
),
@(
"1803 (Build 17134.1 - 2018.04)",
@("Windows 10 Home/Pro", 651),
@("Windows 10 Education", 655),
@("Windows 10 1803", 637),
@("Windows 10 Home China", ($zh + 652))
),
@(
"1709 (Build 16299.15 - 2017.09)",
@("Windows 10 Home/Pro", 484),
@("Windows 10 Education", 488),
@("Windows 10 Home China", ($zh + 485))
),
@(
"1703 [Redstone 2] (Build 15063.0 - 2017.03)",
@("Windows 10 Home/Pro", 361),
@("Windows 10 Home/Pro N", 362),
@("Windows 10 Single Language", 363),
@("Windows 10 Education", 423),
@("Windows 10 Education N", 424),
@("Windows 10 Home China", ($zh + 364))
),
@(
"1607 [Redstone 1] (Build 14393.0 - 2016.07)",
@("Windows 10 Home/Pro", 244),
@("Windows 10 Home/Pro N", 245),
@("Windows 10 Single Language", 246),
@("Windows 10 Education", 242),
@("Windows 10 Education N", 243),
@("Windows 10 China Get Genuine", ($zh + 247))
),
@(
"1511 R3 [Threshold 2] (Build 10586.164 - 2016.04)",
@("Windows 10 Home/Pro", 178),
@("Windows 10 Home/Pro N", 183),
@("Windows 10 Single Language", 184),
@("Windows 10 Education", 179),
@("Windows 10 Education N", 181),
@("Windows 10 KN", ($ko + 182)),
@("Windows 10 Education KN", ($ko + 180)),
@("Windows 10 China Get Genuine", ($zh + 185))
),
@(
"1511 R2 [Threshold 2] (Build 10586.104 - 2016.02)",
@("Windows 10 Home/Pro", 109),
@("Windows 10 Home/Pro N", 115),
@("Windows 10 Single Language", 116),
@("Windows 10 Education", 110),
@("Windows 10 Education N", 112),
@("Windows 10 KN", ($ko + 114)),
@("Windows 10 Education KN", ($ko + 111)),
@("Windows 10 China Get Genuine", ($zh + 113))
),
@(
"1511 R1 [Threshold 2] (Build 10586.0 - 2015.11)",
@("Windows 10 Home/Pro", 99),
@("Windows 10 Home/Pro N", 105),
@("Windows 10 Single Language", 106),
@("Windows 10 Education", 100),
@("Windows 10 Education N", 102),
@("Windows 10 KN", ($ko + 104)),
@("Windows 10 Education KN", ($ko + 101)),
@("Windows 10 China Get Genuine", ($zh + 103))
),
@(
"1507 [Threshold 1] (Build 10240.16384 - 2015.07)",
@("Windows 10 Home/Pro", 79),
@("Windows 10 Home/Pro N", 81),
@("Windows 10 Single Language", 82),
@("Windows 10 Education", 75)
@("Windows 10 Education N", 77),
@("Windows 10 KN", ($ko + 80)),
@("Windows 10 Education KN", ($ko + 76)),
@("Windows 10 China Get Genuine", ($zh + 78))
)
),
@(
@("Windows 8.1", "windows8ISO"),
@(
"Update 3 (build 9600)",
@("Windows 8.1", 52),
@("Windows 8.1 N", 55)
@("Windows 8.1 Single Language", 48),
@("Windows 8.1 K", ($ko + 61)),
@("Windows 8.1 KN", ($ko + 62))
)
),
@(
@("Windows 7", "WIN7"),
@(
"with SP1 (build 7601)",
@("Windows 7 Ultimate", 0),
@("Windows 7 Professional", 1),
@("Windows 7 Home Premium", 2)
)
)
)
$Windows7Versions = @(
# 0: Windows 7 Ultimate
@(
# Need a dummy to prevent PS from coalescing single array entries
@(""),
@("English (US)", "en-us",
@(
@("x64", "https://download.microsoft.com/download/5/1/9/5195A765-3A41-4A72-87D8-200D897CBE21/7601.24214.180801-1700.win7sp1_ldr_escrow_CLIENT_ULTIMATE_x64FRE_en-us.iso"),
@("x86", "https://download.microsoft.com/download/1/E/6/1E6B4803-DD2A-49DF-8468-69C0E6E36218/7601.24214.180801-1700.win7sp1_ldr_escrow_CLIENT_ULTIMATE_x86FRE_en-us.iso")
)
)
),
# 1: Windows 7 Profesional
@(
@(""),
@("English (US)", "en-us",
@(
@("x64", "https://download.microsoft.com/download/0/6/3/06365375-C346-4D65-87C7-EE41F55F736B/7601.24214.180801-1700.win7sp1_ldr_escrow_CLIENT_PROFESSIONAL_x64FRE_en-us.iso"),
@("x86", "https://download.microsoft.com/download/C/0/6/C067D0CD-3785-4727-898E-60DC3120BB14/7601.24214.180801-1700.win7sp1_ldr_escrow_CLIENT_PROFESSIONAL_x86FRE_en-us.iso")
)
)
),
# 2: Windows 7 Home Premium
@(
@(""),
@("English (US)", "en-us",
@(
@("x64", "https://download.microsoft.com/download/E/A/8/EA804D86-C3DF-4719-9966-6A66C9306598/7601.24214.180801-1700.win7sp1_ldr_escrow_CLIENT_HOMEPREMIUM_x64FRE_en-us.iso"),
@("x86", "https://download.microsoft.com/download/E/D/A/EDA6B508-7663-4E30-86F9-949932F443D0/7601.24214.180801-1700.win7sp1_ldr_escrow_CLIENT_HOMEPREMIUM_x86FRE_en-us.iso")
)
)
)
)
#endregion
#region Functions
function Select-Language([string]$LangName)
{
# Use the system locale to try select the most appropriate language
[string]$SysLocale = [System.Globalization.CultureInfo]::CurrentUICulture.Name
if (($SysLocale.StartsWith("ar") -and $LangName -like "*Arabic*") -or `
($SysLocale -eq "pt-BR" -and $LangName -like "*Brazil*") -or `
($SysLocale.StartsWith("ar") -and $LangName -like "*Bulgar*") -or `
($SysLocale -eq "zh-CN" -and $LangName -like "*Chinese*" -and $LangName -like "*simp*") -or `
($SysLocale -eq "zh-TW" -and $LangName -like "*Chinese*" -and $LangName -like "*trad*") -or `
($SysLocale.StartsWith("hr") -and $LangName -like "*Croat*") -or `
($SysLocale.StartsWith("cz") -and $LangName -like "*Czech*") -or `
($SysLocale.StartsWith("da") -and $LangName -like "*Danish*") -or `
($SysLocale.StartsWith("nl") -and $LangName -like "*Dutch*") -or `
($SysLocale -eq "en-US" -and $LangName -eq "English") -or `
($SysLocale.StartsWith("en") -and $LangName -like "*English*" -and ($LangName -like "*inter*" -or $LangName -like "*ingdom*")) -or `
($SysLocale.StartsWith("et") -and $LangName -like "*Eston*") -or `
($SysLocale.StartsWith("fi") -and $LangName -like "*Finn*") -or `
($SysLocale -eq "fr-CA" -and $LangName -like "*French*" -and $LangName -like "*Canad*") -or `
($SysLocale.StartsWith("fr") -and $LangName -eq "French") -or `
($SysLocale.StartsWith("de") -and $LangName -like "*German*") -or `
($SysLocale.StartsWith("el") -and $LangName -like "*Greek*") -or `
($SysLocale.StartsWith("he") -and $LangName -like "*Hebrew*") -or `
($SysLocale.StartsWith("hu") -and $LangName -like "*Hungar*") -or `
($SysLocale.StartsWith("id") -and $LangName -like "*Indones*") -or `
($SysLocale.StartsWith("it") -and $LangName -like "*Italia*") -or `
($SysLocale.StartsWith("ja") -and $LangName -like "*Japan*") -or `
($SysLocale.StartsWith("ko") -and $LangName -like "*Korea*") -or `
($SysLocale.StartsWith("lv") -and $LangName -like "*Latvia*") -or `
($SysLocale.StartsWith("lt") -and $LangName -like "*Lithuania*") -or `
($SysLocale.StartsWith("ms") -and $LangName -like "*Malay*") -or `
($SysLocale.StartsWith("nb") -and $LangName -like "*Norw*") -or `
($SysLocale.StartsWith("fa") -and $LangName -like "*Persia*") -or `
($SysLocale.StartsWith("pl") -and $LangName -like "*Polish*") -or `
($SysLocale -eq "pt-PT" -and $LangName -eq "Portuguese") -or `
($SysLocale.StartsWith("ro") -and $LangName -like "*Romania*") -or `
($SysLocale.StartsWith("ru") -and $LangName -like "*Russia*") -or `
($SysLocale.StartsWith("sr") -and $LangName -like "*Serbia*") -or `
($SysLocale.StartsWith("sk") -and $LangName -like "*Slovak*") -or `
($SysLocale.StartsWith("sl") -and $LangName -like "*Slovenia*") -or `
($SysLocale -eq "es-ES" -and $LangName -eq "Spanish") -or `
($SysLocale.StartsWith("es") -and $Locale -ne "es-ES" -and $LangName -like "*Spanish*") -or `
($SysLocale.StartsWith("sv") -and $LangName -like "*Swed*") -or `
($SysLocale.StartsWith("th") -and $LangName -like "*Thai*") -or `
($SysLocale.StartsWith("tr") -and $LangName -like "*Turk*") -or `
($SysLocale.StartsWith("uk") -and $LangName -like "*Ukrain*") -or `
($SysLocale.StartsWith("vi") -and $LangName -like "*Vietnam*")) {
return $True
}
return $False
}
function Add-Entry([int]$pos, [string]$Name, [array]$Items, [string]$DisplayName)
{
$Title = New-Object System.Windows.Controls.TextBlock
$Title.FontSize = $WindowsVersionTitle.FontSize
$Title.Height = $WindowsVersionTitle.Height;
$Title.Width = $WindowsVersionTitle.Width;
$Title.HorizontalAlignment = "Left"
$Title.VerticalAlignment = "Top"
$Margin = $WindowsVersionTitle.Margin
$Margin.Top += $pos * $dh
$Title.Margin = $Margin
$Title.Text = Get-Translation($Name)
$XMLGrid.Children.Insert(2 * $Stage + 2, $Title)
$Combo = New-Object System.Windows.Controls.ComboBox
$Combo.FontSize = $WindowsVersion.FontSize
$Combo.Height = $WindowsVersion.Height;
$Combo.Width = $WindowsVersion.Width;
$Combo.HorizontalAlignment = "Left"
$Combo.VerticalAlignment = "Top"
$Margin = $WindowsVersion.Margin
$Margin.Top += $pos * $script:dh
$Combo.Margin = $Margin
$Combo.SelectedIndex = 0
if ($Items) {
$Combo.ItemsSource = $Items
if ($DisplayName) {
$Combo.DisplayMemberPath = $DisplayName
} else {
$Combo.DisplayMemberPath = $Name
}
}
$XMLGrid.Children.Insert(2 * $Stage + 3, $Combo)
$XMLForm.Height += $dh;
$Margin = $Continue.Margin
$Margin.Top += $dh
$Continue.Margin = $Margin
$Margin = $Back.Margin
$Margin.Top += $dh
$Back.Margin = $Margin
return $Combo
}
function Refresh-Control([object]$Control)
{
$Control.Dispatcher.Invoke("Render", [Windows.Input.InputEventHandler] { $Continue.UpdateLayout() }, $null, $null)
}
function Send-Message([string]$PipeName, [string]$Message)
{
[System.Text.Encoding]$Encoding = [System.Text.Encoding]::UTF8
$Pipe = New-Object -TypeName System.IO.Pipes.NamedPipeClientStream -ArgumentList ".", $PipeName, ([System.IO.Pipes.PipeDirection]::Out), ([System.IO.Pipes.PipeOptions]::None), ([System.Security.Principal.TokenImpersonationLevel]::Impersonation)
try {
$Pipe.Connect(1000)
} catch {
Write-Host $_.Exception.Message
}
$bRequest = $Encoding.GetBytes($Message)
$cbRequest = $bRequest.Length;
$Pipe.Write($bRequest, 0, $cbRequest);
$Pipe.Dispose()
}
# From https://www.powershellgallery.com/packages/IconForGUI/1.5.2
# Copyright © 2016 Chris Carter. All rights reserved.
# License: https://creativecommons.org/licenses/by-sa/4.0/
function ConvertTo-ImageSource
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[System.Drawing.Icon]$Icon
)
Process {
foreach ($i in $Icon) {
[System.Windows.Interop.Imaging]::CreateBitmapSourceFromHIcon(
$i.Handle,
(New-Object System.Windows.Int32Rect -Args 0,0,$i.Width, $i.Height),
[System.Windows.Media.Imaging.BitmapSizeOptions]::FromEmptyOptions()
)
}
}
}
function Throw-Error([object]$Req, [string]$Alt)
{
$Err = $(GetElementById -Request $r -Id "errorModalMessage").innerText
if (-not $Err) {
$Err = $Alt
} else {
$Err = [System.Text.Encoding]::UTF8.GetString([byte[]][char[]]$Err)
}
throw $Err
}
# Translate a message string
function Get-Translation([string]$Text)
{
if (-not $English -contains $Text) {
Write-Host "Error: '$Text' is not a translatable string"
return "(Untranslated)"
}
if ($Localized) {
if ($Localized.Length -ne $English.Length) {
Write-Host "Error: '$Text' is not a translatable string"
}
for ($i = 0; $i -lt $English.Length; $i++) {
if ($English[$i] -eq $Text) {
if ($Localized[$i]) {
return $Localized[$i]
} else {
return $Text
}
}
}
}
return $Text
}
# Some PowerShells don't have Microsoft.mshtml assembly (comes with MS Office?)
# so we can't use ParsedHtml or IHTMLDocument[2|3] features there...
function GetElementById([object]$Request, [string]$Id)
{
try {
return $Request.ParsedHtml.IHTMLDocument3_GetElementByID($Id)
} catch {
return $Request.AllElements | ? {$_.id -eq $Id}
}
}
function Error([string]$ErrorMessage)
{
Write-Host Error: $ErrorMessage
$XMLForm.Title = $(Get-Translation("Error")) + ": " + $ErrorMessage
Refresh-Control($XMLForm)
$XMLGrid.Children[2 * $script:Stage + 1].IsEnabled = $True
$UserInput = [System.Windows.MessageBox]::Show($XMLForm.Title, $(Get-Translation("Error")), "OK", "Error")
$script:ExitCode = $script:Stage--
}
function Get-RandomDate()
{
[DateTime]$Min = "1/1/2008"
[DateTime]$Max = [DateTime]::Now
$RandomGen = new-object random
$RandomTicks = [Convert]::ToInt64( ($Max.ticks * 1.0 - $Min.Ticks * 1.0 ) * $RandomGen.NextDouble() + $Min.Ticks * 1.0 )
$Date = new-object DateTime($RandomTicks)
return $Date.ToString("yyyyMMdd")
}
#endregion
#region Form
[xml]$XAML = @"
<Window xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" Height = "162" Width = "384" ResizeMode = "NoResize">
<Grid Name = "XMLGrid">
<Button Name = "Continue" FontSize = "16" Height = "26" Width = "160" HorizontalAlignment = "Left" VerticalAlignment = "Top" Margin = "14,78,0,0"/>
<Button Name = "Back" FontSize = "16" Height = "26" Width = "160" HorizontalAlignment = "Left" VerticalAlignment = "Top" Margin = "194,78,0,0"/>
<TextBlock Name = "WindowsVersionTitle" FontSize = "16" Width="340" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="16,8,0,0"/>
<ComboBox Name = "WindowsVersion" FontSize = "14" Height = "24" Width = "340" HorizontalAlignment = "Left" VerticalAlignment="Top" Margin = "14,34,0,0" SelectedIndex = "0"/>
<CheckBox Name = "Check" FontSize = "14" Width = "340" HorizontalAlignment = "Left" VerticalAlignment="Top" Margin = "14,0,0,0" Visibility="Collapsed" />
</Grid>
</Window>
"@
#endregion
#region Globals
$ErrorActionPreference = "Stop"
$dh = 58;
$Stage = 0
$ltrm = ""
$MaxStage = 4
$SessionId = [guid]::NewGuid()
$ExitCode = 100
$Locale = "en-US"
$RequestData = @{}
$RequestData["GetLangs"] = @("a8f8f489-4c7f-463a-9ca6-5cff94d8d041", "getskuinformationbyproductedition" )
$RequestData["GetLinks"] = @("a224afab-2097-4dfa-a2ba-463eb191a285", "GetProductDownloadLinksBySku" )
# Create a semi-random Linux User-Agent string
$FirefoxVersion = Get-Random -Minimum 50 -Maximum 90
$FirefoxDate = Get-RandomDate
$UserAgent = "Mozilla/5.0 (X11; Linux i586; rv:$FirefoxVersion.0) Gecko/$FirefoxDate Firefox/$FirefoxVersion.0"
#endregion
# Localization
$EnglishMessages = "en-US|Version|Release|Edition|Language|Architecture|Download|Continue|Back|Close|Cancel|Error|Please wait...|" +
"Download using a browser|Temporarily banned by Microsoft for requesting too many downloads - Please try again later...|" +
"PowerShell 3.0 or later is required to run this script.|Do you want to go online and download it?"
[string[]]$English = $EnglishMessages.Split('|')
[string[]]$Localized = $null
if ($LocData -and (-not $LocData.StartsWith("en-US"))) {
$Localized = $LocData.Split('|')
if ($Localized.Length -ne $English.Length) {
Write-Host "Error: Missing or extra translated messages provided ($($Localized.Length)/$($English.Length))"
exit 101
}
$Locale = $Localized[0]
}
$QueryLocale = $Locale
# Make sure PowerShell 3.0 or later is used (for Invoke-WebRequest)
if ($PSVersionTable.PSVersion.Major -lt 3) {
Write-Host Error: PowerShell 3.0 or later is required to run this script.
$Msg = "$(Get-Translation($English[15]))`n$(Get-Translation($English[16]))"
if ([System.Windows.MessageBox]::Show($Msg, $(Get-Translation("Error")), "YesNo", "Error") -eq "Yes") {
Start-Process -FilePath https://www.microsoft.com/download/details.aspx?id=34595
}
exit 102
}
function CheckLocale {
# Check if the locale we want is available - Fall back to en-US otherwise
try {
$url = "https://www.microsoft.com/" + $QueryLocale + "/software-download/"
Write-Host Querying $url
Invoke-WebRequest -UseBasicParsing -MaximumRedirection 0 -UserAgent $UserAgent $url | Out-Null
} catch {
$script:QueryLocale = "en-US"
}
}
function Stage1 {
param (
$SelectedValue
)
CheckLocale
$i = 0
$array = @()
foreach ($Version in $WindowsVersions[$SelectedValue]) {
if (($i -ne 0) -and ($Version -is [array])) {
$array += @(New-Object PsObject -Property @{ Release = $ltrm + $Version[0].Replace(")", ")" + $ltrm); Index = $i })
}
$i++
}
return $array
}
function Stage2 {
param (
$Version,
$ReleaseId
)
$array = @()
foreach ($Release in $WindowsVersions[$Version][$ReleaseId])
{
if ($Release -is [array]) {
if (($Release[1] -lt 0x10000) -or ($Locale.StartsWith("ko") -and ($Release[1] -band $ko)) -or ($Locale.StartsWith("zh") -and ($Release[1] -band $zh))) {
$array += @(New-Object PsObject -Property @{ Edition = $Release[0]; Id = $($Release[1] -band 0xFFFF) })
}
}
}
return $array
}
function Stage3 {
param (
$Version,
$Edition
)
$array = @()
$i = 0;
if ($WindowsVersions[$Version][0][1] -eq "WIN7") {
foreach ($Entry in $Windows7Versions[$Edition]) {
if ($Entry[0] -ne "") {
$array += @(New-Object PsObject -Property @{ DisplayLanguage = $Entry[0]; Language = $Entry[1]; Id = $i })
}
$i++
}
} else {
$url = "https://www.microsoft.com/" + $QueryLocale + "/api/controls/contentinclude/html"
$url += "?pageId=" + $RequestData["GetLangs"][0]
$url += "&host=www.microsoft.com"
$url += "&segments=software-download," + $WindowsVersions[$Version][0][1]
$url += "&query=&action=" + $RequestData["GetLangs"][1]
$url += "&sessionId=" + $SessionId
$url += "&productEditionId=" + [Math]::Abs($Edition)
$url += "&sdVersion=2"
Write-Host Querying $url
$SelectedIndex = 0
try {
$r = Invoke-WebRequest -UseBasicParsing -UserAgent $UserAgent -SessionVariable "Session" $url
$pattern = '(?s)<select id="product-languages">(.*)?</select>'
$html = [regex]::Match($r, $pattern).Groups[1].Value
# Go through an XML conversion to keep all PowerShells happy...
$html = $html.Replace("selected value", "value")
$html = "<options>" + $html + "</options>"
$xml = [xml]$html
foreach ($var in $xml.options.option) {
$json = $var.value | ConvertFrom-Json;
if ($json) {
$array += @(New-Object PsObject -Property @{ DisplayLanguage = $var.InnerText; Language = $json.language; Id = $json.id })
if (Select-Language($json.language)) {
$SelectedIndex = $i
}
$i++
}
}
if ($array.Length -eq 0) {
Throw-Error -Req $r -Alt "Could not parse languages"
}
} catch {
Error($_.Exception.Message)
break
}
}
return $array
}
function Stage4 {
param (
$VersionId,
$Edition,
$LanguageId,
$LanguageName
)
$array = @()
if ($WindowsVersions[$VersionId][0][1] -eq "WIN7") {
foreach ($Version in $Windows7Versions[$Edition][$LanguageId][2]) {
$array += @(New-Object PsObject -Property @{ Type = $Version[0]; Link = $Version[1] })
}
} else {
if ( ! $Headless ) {
$XMLForm.Title = Get-Translation($English[12])
Refresh-Control($XMLForm)
}
$url = "https://www.microsoft.com/" + $QueryLocale + "/api/controls/contentinclude/html"
$url += "?pageId=" + $RequestData["GetLinks"][0]
$url += "&host=www.microsoft.com"
$url += "&segments=software-download," + $WindowsVersions[$VersionId][0][1]
$url += "&query=&action=" + $RequestData["GetLinks"][1]
$url += "&sessionId=" + $SessionId
$url += "&skuId=" + $LanguageId
$url += "&language=" + $LanguageName
$url += "&sdVersion=2"
Write-Host Querying $url
$i = 0
$SelectedIndex = 0
try {
$Is64 = [Environment]::Is64BitOperatingSystem
$r = Invoke-WebRequest -Method Post -UseBasicParsing -UserAgent $UserAgent -WebSession $Session $url
$pattern = '(?s)(<input.*?></input>)'
ForEach-Object { [regex]::Matches($r, $pattern) } | ForEach-Object { $html += $_.Groups[1].value }
$hashes = @{}
ForEach-Object { [regex]::Matches($r, '<tr><td>([\w]+)\s+(\d{2})\-bit</td><td>([A-F0-9]+)</td></tr>') } | ForEach-Object {
$arch = If ($_.Groups[2].value -eq "32") { "86" } else { $_.Groups[2].value }
$hashes["$($_.Groups[1].value)_x$($arch)"] = $_.Groups[3].value
}
# Need to fix the HTML and JSON data so that it is well-formed
$html = $html.Replace("class=product-download-hidden", "")
$html = $html.Replace("type=hidden", "")
$html = $html.Replace(" ", " ")
$html = $html.Replace("IsoX86", ""x86"")
$html = $html.Replace("IsoX64", ""x64"")
$html = "<inputs>" + $html + "</inputs>"
$xml = [xml]$html
foreach ($var in $xml.inputs.input) {
$json = $var.value | ConvertFrom-Json;
if ($json) {
if (($Is64 -and $json.DownloadType -eq "x64") -or (-not $Is64 -and $json.DownloadType -eq "x86")) {
$SelectedIndex = $i
}
Write-Host $json
$hash = $hashes["$($LanguageName)_$($json.DownloadType)"]
$array += @(New-Object PsObject -Property @{ Type = $json.DownloadType; Link = $json.Uri; Hash = $hash })
$i++
}
}
if ($array.Length -eq 0) {
Throw-Error -Req $r -Alt "Could not retrieve ISO download links"
}
} catch {
Error($_.Exception.Message)
break
}
}
return $array
}
function Stage5 {
param (
$ArchLink,
$File = $null,
$Hash = $null
)
if ($PipeName -and -not $Check.IsChecked) {
Send-Message -PipeName $PipeName -Message $ArchLink
$script:ExitCode = 0
} elseif ($Headless) {
Write-Host "Downloading $ArchLink into $File"
$client = New-Object System.Net.WebClient
$client.DownloadFile($ArchLink, $File)
if($Hash) {
$actualHash = Get-FileHash $File
if($actualHash.Hash -eq $Hash) {
Write-Host "Hash OK"
$script:ExitCode = 0
} else {
Write-Host "Hash FAIL"
$script:ExitCode = 1
}
}
} else {
Write-Host Download Link: $ArchLink
Start-Process -FilePath $ArchLink
$script:ExitCode = 0
}
}
if ( $Headless ) {
$winVersionId = $null
$winReleaseId = $null
$winEditionId = $null
$winLanguageId = $null
$winLanguageName = $null
$winLink = $null
Write-Host "Available Versions"
$i = 0
foreach($Version in $WindowsVersions) {
Write-Host " -" $Version[0][0]
if($Version[0][0] -eq $cliVersionName) {
$winVersionId = $i
}
$i++
}
if ($winVersionId -eq $null) {
exit 1
}
# Windows Version selection
Write-Host "=== Stage 1 ==="
$releases = Stage1 $winVersionId
Write-Host "Available Releases"
foreach($Release in $releases) {
Write-Host " -" $Release.Release
if($cliReleaseName -eq $Release.Release) {
$winReleaseId = $Release.Index
}
}
if($cliReleaseName -eq 'latest') {
$winReleaseId = $releases[0].Index
}
if ($winReleaseId -eq $null) {
exit 1
}
# Windows Release selection => Populate Product Edition
Write-Host "=== Stage 2 ==="
$editions = Stage2 $winVersionId $winReleaseId
Write-Host "Available Editions"
foreach($edition in $editions) {
Write-Host " -" $edition.Edition
if($cliEditionName -eq $edition.Edition) {
$winEditionId = $edition.Id
}
}
if ($winEditionId -eq $null) {
exit 1
}
# Product Edition selection => Request and populate Languages
Write-Host "=== Stage 3 ==="
$languages = Stage3 $winVersionId $winEditionId
Write-Host "Available Languages"
foreach($language in $languages) {
Write-Host " -" $language.Language
if($cliLanguage -eq $language.Language) {
$winLanguageId = $language.Id
$winLanguageName = $language.Language
}
}
if ($winLanguageId -eq $null -or $winLanguageName -eq $null) {
exit 1
}
# Language selection => Request and populate Arch download links
Write-Host "=== Stage 4 ==="
$architectures = Stage4 $winVersionId $winEditionId $winLanguageId $winLanguageName
Write-Host "Available Architectures"
foreach($arch in $architectures) {
Write-Host " -" $arch.Type $arch.Hash
if($cliArch -eq $arch.Type) {
$winLink = $arch
}
}
if ($winLink -eq $null) {
exit 1
}
# Arch selection => Return selected download link
Write-Host "=== Stage 5 ==="
Stage5 $winLink.Link $cliFilename $winLink.Hash
# Clean up & exit
exit $ExitCode
}
# Form creation
$XMLForm = [Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader $XAML))
$XAML.SelectNodes("//*[@Name]") | ForEach-Object { Set-Variable -Name ($_.Name) -Value $XMLForm.FindName($_.Name) -Scope Script }
$XMLForm.Title = $AppTitle
if ($Icon) {
$XMLForm.Icon = $Icon
} else {
$XMLForm.Icon = [Gui.Utils]::ExtractIcon("shell32.dll", -41, $true) | ConvertTo-ImageSource
}
if ($Locale.StartsWith("ar") -or $Locale.StartsWith("fa") -or $Locale.StartsWith("he")) {
$XMLForm.FlowDirection = "RightToLeft"
}
$WindowsVersionTitle.Text = Get-Translation("Version")
$Continue.Content = Get-Translation("Continue")
$Back.Content = Get-Translation("Close")
# Populate the Windows versions
$i = 0
$array = @()
foreach($Version in $WindowsVersions) {
$array += @(New-Object PsObject -Property @{ Version = $Version[0][0]; PageType = $Version[0][1]; Index = $i })
$i++
}
$WindowsVersion.ItemsSource = $array
$WindowsVersion.DisplayMemberPath = "Version"
# Button Action
$Continue.add_click({
$script:Stage++
$XMLGrid.Children[2 * $Stage + 1].IsEnabled = $False
$Continue.IsEnabled = $False
$Back.IsEnabled = $False
Refresh-Control($Continue)
Refresh-Control($Back)
switch ($Stage) {
1 { # Windows Version selection
$XMLForm.Title = Get-Translation($English[12])
Refresh-Control($XMLForm)
$array = Stage1 $WindowsVersion.SelectedValue.Index
$script:WindowsRelease = Add-Entry $Stage "Release" $array
$Back.Content = Get-Translation($English[8])
$XMLForm.Title = $AppTitle
}
2 { # Windows Release selection => Populate Product Edition
$array = Stage2 $WindowsVersion.SelectedValue.Index $WindowsRelease.SelectedValue.Index
$script:ProductEdition = Add-Entry $Stage "Edition" $array
}
3 { # Product Edition selection => Request and populate Languages
$XMLForm.Title = Get-Translation($English[12])
Refresh-Control($XMLForm)
$array = Stage3 $WindowsVersion.SelectedValue.Index $ProductEdition.SelectedValue.Id
$script:Language = Add-Entry $Stage "Language" $array "DisplayLanguage"
$Language.SelectedIndex = $SelectedIndex
$XMLForm.Title = $AppTitle
}
4 { # Language selection => Request and populate Arch download links
$array = Stage4 $WindowsVersion.SelectedValue.Index $ProductEdition.SelectedValue.Id $Language.SelectedValue.Id $Language.SelectedValue.Language
$script:Arch = Add-Entry $Stage "Architecture" $array "Type"
if ($PipeName) {
$XMLForm.Height += $dh / 2;
$Margin = $Continue.Margin
$top = $Margin.Top
$Margin.Top += $dh /2
$Continue.Margin = $Margin
$Margin = $Back.Margin
$Margin.Top += $dh / 2
$Back.Margin = $Margin
$Margin = $Check.Margin
$Margin.Top = $top - 2
$Check.Margin = $Margin
$Check.Content = Get-Translation($English[13])
$Check.Visibility = "Visible"
}
$Arch.SelectedIndex = $SelectedIndex
$Continue.Content = Get-Translation("Download")
$XMLForm.Title = $AppTitle
}
5 { # Arch selection => Return selected download link
Stage5 $Arch.SelectedValue.Link
$XMLForm.Close()
}
}
$Continue.IsEnabled = $True
if ($Stage -ge 0) {
$Back.IsEnabled = $True
}
})
$Back.add_click({
if ($Stage -eq 0) {
$XMLForm.Close()
} else {
$XMLGrid.Children.RemoveAt(2 * $Stage + 3)
$XMLGrid.Children.RemoveAt(2 * $Stage + 2)
$XMLGrid.Children[2 * $Stage + 1].IsEnabled = $True
$dh2 = $dh
if ($Stage -eq 4 -and $PipeName) {
$Check.Visibility = "Collapsed"
$dh2 += $dh / 2
}
$XMLForm.Height -= $dh2;
$Margin = $Continue.Margin
$Margin.Top -= $dh2
$Continue.Margin = $Margin
$Margin = $Back.Margin
$Margin.Top -= $dh2
$Back.Margin = $Margin
$script:Stage = $Stage - 1
$XMLForm.Title = $AppTitle
if ($Stage -eq 0) {
$Back.Content = Get-Translation("Close")
} else {
$Continue.Content = Get-Translation("Continue")
Refresh-Control($Continue)
}
}
})
# Display the dialog
$XMLForm.Add_Loaded( { $XMLForm.Activate() } )
$XMLForm.ShowDialog() | Out-Null
# Clean up & exit
exit $ExitCode
# SIG # Begin signature block