-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInvoke-PowerShellDownload.ps1
1019 lines (915 loc) · 44.3 KB
/
Invoke-PowerShellDownload.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
# Version 0.2.20241001.0
#region License ####################################################################
# Copyright (c) 2024 Frank Lesniak
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify,
# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be included in all copies
# or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#endregion License ####################################################################
param(
[switch]$PreferZIP,
[switch]$Windows,
[switch]$Linux,
[switch]$macOS,
[switch]$ARM64,
[switch]$ARM,
[switch]$x86,
[switch]$x8664,
[switch]$x64,
[switch]$AMD64
)
# TODO: Add capability to download to temp folder instead of downloads folder?
function Get-PSVersion {
<#
.SYNOPSIS
Returns the version of PowerShell that is running
.DESCRIPTION
Returns the version of PowerShell that is running, including on the original
release of Windows PowerShell (version 1.0)
.EXAMPLE
Get-PSVersion
This example returns the version of PowerShell that is running. On versions of
PowerShell greater than or equal to version 2.0, this function returns the
equivalent of $PSVersionTable.PSVersion
.OUTPUTS
A [version] object representing the version of PowerShell that is running
.NOTES
PowerShell 1.0 does not have a $PSVersionTable variable, so this function returns
[version]('1.0') on PowerShell 1.0
#>
[CmdletBinding()]
[OutputType([version])]
param ()
#region License ################################################################
# Copyright (c) 2023 Frank Lesniak
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
# Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#endregion License ################################################################
$versionThisFunction = [version]('1.0.20230613.0')
if (Test-Path variable:\PSVersionTable) {
$PSVersionTable.PSVersion
} else {
[version]('1.0')
}
}
function Test-Windows {
# Returns a boolean ($true or $false) indicating whether the current PowerShell
# session is running on Windows. This function is useful for writing scripts that
# need to behave differently on Windows and non-Windows platforms (Linux, macOS,
# etc.). Additionally, this function is useful because it works on Windows
# PowerShell 1.0 through 5.1, which do not have the $IsWindows global variable.
#
# Example:
# $boolIsWindows = Test-Windows
#
# This example returns $true if the current PowerShell session is running on
# Windows, and $false if the current PowerShell session is running on a non-Windows
# platform (Linux, macOS, etc.)
#
# Version 1.0.20240917.0
#region License ################################################################
# Copyright (c) 2024 Frank Lesniak
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
# Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#endregion License ################################################################
#region DownloadLocationNotice #############################################
# The most up-to-date version of this script can be found on the author's
# GitHub repository at https://github.com/franklesniak/PowerShell_Resources
#endregion DownloadLocationNotice #############################################
function Get-PSVersion {
# Returns the version of PowerShell that is running, including on the original
# release of Windows PowerShell (version 1.0)
#
# Example:
# Get-PSVersion
#
# This example returns the version of PowerShell that is running. On versions
# of PowerShell greater than or equal to version 2.0, this function returns the
# equivalent of $PSVersionTable.PSVersion
#
# The function outputs a [version] object representing the version of
# PowerShell that is running
#
# PowerShell 1.0 does not have a $PSVersionTable variable, so this function
# returns [version]('1.0') on PowerShell 1.0
#
# Version 1.0.20240917.0
#region License ############################################################
# Copyright (c) 2024 Frank Lesniak
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#endregion License ############################################################
#region DownloadLocationNotice #############################################
# The most up-to-date version of this script can be found on the author's
# GitHub repository at https://github.com/franklesniak/PowerShell_Resources
#endregion DownloadLocationNotice #############################################
if (Test-Path variable:\PSVersionTable) {
return ($PSVersionTable.PSVersion)
} else {
return ([version]('1.0'))
}
}
$versionPS = Get-PSVersion
if ($versionPS.Major -ge 6) {
$IsWindows
} else {
$true
}
}
function Get-DownloadFolder {
if (Test-Path variable:\HOME) {
$strBasePath = $HOME
} elseif (Test-Path env:\USERPROFILE) {
$strBasePath = $env:USERPROFILE
} else {
$strBasePath = $null
}
if ($null -ne $strBasePath) {
$strDownloads = Join-Path $strBasePath "Downloads"
if ((Test-Path $strDownloads) -eq $false) {
New-Item -Path $strDownloads -ItemType Directory | Out-Null
}
$strDownloads
} else {
Write-Warning "Get-DownloadFolder was unable to locate suitable folder path for downloads. Returning `$null"
$null
}
}
function Get-WScriptShellCOMObject {
#region FunctionHeader #########################################################
# Attempts to create a new COM object "WScript.Shell"; if successful, it returns it
#
# One positional arguments is required:
#
# The first argument is a reference to a ComObject that will be used to store the
# WScript.Shell COM object, (if it is successfully created)
#
# The function returns $true if the process completed successfully; $false
# otherwise
#
# # Example usage:
# $objWScriptShell = $null
# $boolResult = Get-WScriptShellCOMObject ([ref]$objWScriptShell)
# # If $boolResult is $true, then $objWScriptShell is a WScript.Shell object
#
# Version: 1.0.20240925.0
#endregion FunctionHeader #########################################################
#region License ################################################################
# Copyright (c) 2024 Frank Lesniak
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
# Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#endregion License ################################################################
function Get-ReferenceToLastError {
#region FunctionHeader #####################################################
# Function returns $null if no errors on on the $error stack;
# Otherwise, function returns a reference (memory pointer) to the last error
# that occurred.
#
# Version: 1.0.20240127.0
#endregion FunctionHeader #####################################################
#region License ############################################################
# Copyright (c) 2024 Frank Lesniak
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#endregion License ############################################################
#region DownloadLocationNotice #############################################
# The most up-to-date version of this script can be found on the author's
# GitHub repository at https://github.com/franklesniak/PowerShell_Resources
#endregion DownloadLocationNotice #############################################
if ($error.Count -gt 0) {
[ref]($error[0])
} else {
$null
}
}
function Test-ErrorOccurred {
#region FunctionHeader #####################################################
# Function accepts two positional arguments:
#
# The first argument is a reference (memory pointer) to the last error that had
# occurred prior to calling the command in question - that is, the command that
# we want to test to see if an error occurred.
#
# The second argument is a reference to the last error that had occurred as-of
# the completion of the command in question.
#
# Function returns $true if it appears that an error occurred; $false otherwise
#
# Version: 1.0.20240127.0
#endregion FunctionHeader #####################################################
#region License ############################################################
# Copyright (c) 2024 Frank Lesniak
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#endregion License ############################################################
#region DownloadLocationNotice #############################################
# The most up-to-date version of this script can be found on the author's
# GitHub repository at https://github.com/franklesniak/PowerShell_Resources
#endregion DownloadLocationNotice #############################################
# TO-DO: Validate input
$boolErrorOccurred = $false
if (($null -ne ($args[0])) -and ($null -ne ($args[1]))) {
# Both not $null
if ((($args[0]).Value) -ne (($args[1]).Value)) {
$boolErrorOccurred = $true
}
} else {
# One is $null, or both are $null
# NOTE: ($args[0]) could be non-null, while ($args[1])
# could be null if $error was cleared; this does not indicate an error.
# So:
# If both are null, no error
# If ($args[0]) is null and ($args[1]) is non-null, error
# If ($args[0]) is non-null and ($args[1]) is null, no error
if (($null -eq ($args[0])) -and ($null -ne ($args[1]))) {
$boolErrorOccurred
}
}
$boolErrorOccurred
}
trap {
# Intentionally left empty to prevent terminating errors from halting
# processing
}
$refOutput = $args[0]
# Retrieve the newest error on the stack prior to doing work
$refLastKnownError = Get-ReferenceToLastError
# Store current error preference; we will restore it after we do the work of this
# function
$actionPreferenceFormerErrorPreference = $global:ErrorActionPreference
# Set ErrorActionPreference to SilentlyContinue; this will suppress error output.
# Terminating errors will not output anything, kick to the empty trap statement and
# then continue on. Likewise, non-terminating errors will also not output anything,
# but they do not kick to the trap statement; they simply continue on.
$global:ErrorActionPreference = [System.Management.Automation.ActionPreference]::SilentlyContinue
# Attempt to create the WScript.Shell object
$output = New-Object -ComObject WScript.Shell
# Restore the former error preference
$global:ErrorActionPreference = $actionPreferenceFormerErrorPreference
# Retrieve the newest error on the error stack
$refNewestCurrentError = Get-ReferenceToLastError
if (Test-ErrorOccurred $refLastKnownError $refNewestCurrentError) {
# Error occurred
return $false
} else {
# No error occurred
$refOutput.Value = $output
return $true
}
}
function Get-SystemProcessorArchitectureEnvironmentVariableFromWindowsRegistry {
#region FunctionHeader #########################################################
# Attempts to retrieve the system-context PROCESS_ARCHITECTURE environment variable
# from the registry
#
# One positional arguments is required:
#
# The first argument is a reference to a string that will be used to store the
# value of the system-context PROCESSOR_ARCHITECTURE environment variable
#
# The function returns $true if the process completed successfully; $false
# otherwise
#
# # Example usage:
# $strSystemPROCESSORARCHITECTURE = $null
# $boolResult = Get-SystemProcessorArchitectureEnvironmentVariableFromWindowsRegistry ([ref]$strSystemPROCESSORARCHITECTURE)
# # If $boolResult is $true, then $strSystemPROCESSORARCHITECTURE is a string
# # containing the value of the system-context PROCESSOR_ARCHITECTURE environment
# # variable.
#
# Version: 1.0.20240924.0
#endregion FunctionHeader #########################################################
#region License ################################################################
# Copyright (c) 2024 Frank Lesniak
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
# Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#endregion License ################################################################
function Get-ReferenceToLastError {
#region FunctionHeader #####################################################
# Function returns $null if no errors on on the $error stack;
# Otherwise, function returns a reference (memory pointer) to the last error
# that occurred.
#
# Version: 1.0.20240127.0
#endregion FunctionHeader #####################################################
#region License ############################################################
# Copyright (c) 2024 Frank Lesniak
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#endregion License ############################################################
#region DownloadLocationNotice #############################################
# The most up-to-date version of this script can be found on the author's
# GitHub repository at https://github.com/franklesniak/PowerShell_Resources
#endregion DownloadLocationNotice #############################################
if ($error.Count -gt 0) {
[ref]($error[0])
} else {
$null
}
}
function Test-ErrorOccurred {
#region FunctionHeader #####################################################
# Function accepts two positional arguments:
#
# The first argument is a reference (memory pointer) to the last error that had
# occurred prior to calling the command in question - that is, the command that
# we want to test to see if an error occurred.
#
# The second argument is a reference to the last error that had occurred as-of
# the completion of the command in question.
#
# Function returns $true if it appears that an error occurred; $false otherwise
#
# Version: 1.0.20240127.0
#endregion FunctionHeader #####################################################
#region License ############################################################
# Copyright (c) 2024 Frank Lesniak
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#endregion License ############################################################
#region DownloadLocationNotice #############################################
# The most up-to-date version of this script can be found on the author's
# GitHub repository at https://github.com/franklesniak/PowerShell_Resources
#endregion DownloadLocationNotice #############################################
# TO-DO: Validate input
$boolErrorOccurred = $false
if (($null -ne ($args[0])) -and ($null -ne ($args[1]))) {
# Both not $null
if ((($args[0]).Value) -ne (($args[1]).Value)) {
$boolErrorOccurred = $true
}
} else {
# One is $null, or both are $null
# NOTE: ($args[0]) could be non-null, while ($args[1])
# could be null if $error was cleared; this does not indicate an error.
# So:
# If both are null, no error
# If ($args[0]) is null and ($args[1]) is non-null, error
# If ($args[0]) is non-null and ($args[1]) is null, no error
if (($null -eq ($args[0])) -and ($null -ne ($args[1]))) {
$boolErrorOccurred
}
}
$boolErrorOccurred
}
trap {
# Intentionally left empty to prevent terminating errors from halting
# processing
}
$refOutput = $args[0]
# Retrieve the newest error on the stack prior to doing work
$refLastKnownError = Get-ReferenceToLastError
# Store current error preference; we will restore it after we do the work of this
# function
$actionPreferenceFormerErrorPreference = $global:ErrorActionPreference
# Set ErrorActionPreference to SilentlyContinue; this will suppress error output.
# Terminating errors will not output anything, kick to the empty trap statement and
# then continue on. Likewise, non-terminating errors will also not output anything,
# but they do not kick to the trap statement; they simply continue on.
$global:ErrorActionPreference = [System.Management.Automation.ActionPreference]::SilentlyContinue
$regKey = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
# Attempt to retrieve the system-context PROCESSOR_ARCHITECTURE environment
# variable from the registry. This has to be done in one line for effective error
# handling
$output = (Get-ItemProperty $regKey).PROCESSOR_ARCHITECTURE
# Restore the former error preference
$global:ErrorActionPreference = $actionPreferenceFormerErrorPreference
# Retrieve the newest error on the error stack
$refNewestCurrentError = Get-ReferenceToLastError
if (Test-ErrorOccurred $refLastKnownError $refNewestCurrentError) {
# Error occurred
return $false
} else {
# No error occurred
$refOutput.Value = $output
return $true
}
}
$strNewestARM32Release = '7.3.12'
$versionARM64MSI = [version]('7.4.3') # First ARM64 MSI release
$boolPreferZIP = $false
if ($null -ne $PreferZIP) {
if ($PreferZIP.IsPresent) {
$boolPreferZIP = $true
}
}
$versionPS = Get-PSVersion
#region Determine which OS type was specified, fall back to the one we're on #######
$boolWindows = $null
$boolLinux = $null
$boolMacOS = $null
if ($null -ne $Windows) {
if ($Windows.IsPresent) {
$boolWindows = $true
$boolLinux = $false
$boolMacOS = $false
} else {
$boolWindows = Test-Windows
if ($boolWindows) {
$boolLinux = $false
$boolMacOS = $false
}
}
} else {
$boolWindows = Test-Windows
if ($boolWindows) {
$boolLinux = $false
$boolMacOS = $false
}
}
if ($null -ne $Linux) {
if ($Linux.IsPresent) {
$boolWindows = $false
$boolLinux = $true
$boolMacOS = $false
} else {
if ($null -eq $boolLinux) {
$boolLinux = $IsLinux
}
}
} else {
if ($null -eq $boolLinux) {
$boolLinux = $IsLinux
}
}
if ($null -ne $macOS) {
if ($macOS.IsPresent) {
$boolWindows = $false
$boolLinux = $false
$boolMacOS = $true
} else {
if ($null -eq $boolMacOS) {
$boolMacOS = $IsMacOS
}
}
} else {
if ($null -eq $boolMacOS) {
$boolMacOS = $IsMacOS
}
}
$strMessage = '$boolWindows = ' + [string]$boolWindows
Write-Debug $strMessage
$strMessage = '$boolLinux = ' + [string]$boolLinux
Write-Debug $strMessage
$strMessage = '$boolMacOS = ' + [string]$boolMacOS
Write-Debug $strMessage
#endregion Determine which OS type was specified, fall back to the one we're on #######
$boolDownloadSuccessful = $false
if ($boolWindows) {
# Need to download PowerShell v7
#region Determine which processor architecture was specified, fall back to the one we're on
$strOSProcessorArchitecture = ''
if ([string]::IsNullOrEmpty($strOSProcessorArchitecture)) {
if ($null -ne $ARM64) {
if ($ARM64.IsPresent) {
$strOSProcessorArchitecture = 'ARM64'
}
}
}
if ([string]::IsNullOrEmpty($strOSProcessorArchitecture)) {
if ($null -ne $ARM) {
if ($ARM.IsPresent) {
$strOSProcessorArchitecture = 'ARM'
}
}
}
if ([string]::IsNullOrEmpty($strOSProcessorArchitecture)) {
if ($null -ne $x86) {
if ($x86.IsPresent) {
$strOSProcessorArchitecture = 'x86'
}
}
}
if ([string]::IsNullOrEmpty($strOSProcessorArchitecture)) {
if ($null -ne $x8664) {
if ($x8664.IsPresent) {
$strOSProcessorArchitecture = 'AMD64'
}
}
}
if ([string]::IsNullOrEmpty($strOSProcessorArchitecture)) {
if ($null -ne $x64) {
if ($x64.IsPresent) {
$strOSProcessorArchitecture = 'AMD64'
}
}
}
if ([string]::IsNullOrEmpty($strOSProcessorArchitecture)) {
if ($null -ne $AMD64) {
if ($AMD64.IsPresent) {
$strOSProcessorArchitecture = 'AMD64'
}
}
}
if ([string]::IsNullOrEmpty($strOSProcessorArchitecture)) {
# Methodology adopted from sysadmin-accelerator project
# See: GetOperatingSystemProcessorArchitectureUsingOperatingSystemVersion.vbs
$objWScriptShell = $null
$boolResult = Get-WScriptShellCOMObject ([ref]$objWScriptShell)
if ($boolResult) {
# Success! Use the WScript.Shell object
$objEnvironment = $objWSHShell.Environment('System')
$strOSProcessorArchitecture = $objEnvironment.Item('PROCESSOR_ARCHITECTURE')
} else {
# Could not create a WScript.Shell object; fall back to other method(s)
$strOSProcessorArchitecture = $null
$boolResult = Get-SystemProcessorArchitectureEnvironmentVariableFromWindowsRegistry ([ref]$strOSProcessorArchitecture)
if (-not $boolResult) {
# TODO: Code more alternatives
Write-Warning 'Could not retrieve the OS processor architecture!'
}
}
}
$strMessage = '$strOSProcessorArchitecture = ' + $strOSProcessorArchitecture
Write-Debug $strMessage
#endregion Determine which processor architecture was specified, fall back to the one we're on
switch ($strOSProcessorArchitecture) {
'x86' {
$strPowerShellProcessorArchitecture = 'win-x86'
$strPowerShellReleaseMetadata = 'https://raw.githubusercontent.com/PowerShell/PowerShell/master/tools/metadata.json'
$strPowerShellVersion = (Invoke-RestMethod -Uri $strPowerShellReleaseMetadata).StableReleaseTag -replace '^v'
if ($boolPreferZIP) {
$boolUseMSI = $false
} else {
$boolUseMSI = $true
}
}
'AMD64' {
$strPowerShellProcessorArchitecture = 'win-x64'
$strPowerShellReleaseMetadata = 'https://raw.githubusercontent.com/PowerShell/PowerShell/master/tools/metadata.json'
$strPowerShellVersion = (Invoke-RestMethod -Uri $strPowerShellReleaseMetadata).StableReleaseTag -replace '^v'
if ($boolPreferZIP) {
$boolUseMSI = $false
} else {
$boolUseMSI = $true
}
}
'ARM64' {
$strPowerShellProcessorArchitecture = 'win-arm64'
$strPowerShellReleaseMetadata = 'https://raw.githubusercontent.com/PowerShell/PowerShell/master/tools/metadata.json'
$strPowerShellVersion = (Invoke-RestMethod -Uri $strPowerShellReleaseMetadata).StableReleaseTag -replace '^v'
if ([version]$strPowerShellVersion -ge $versionARM64MSI) {
if ($boolPreferZIP) {
$boolUseMSI = $false
} else {
$boolUseMSI = $true
}
} else {
$boolUseMSI = $false
}
}
'ARM' {
$strPowerShellProcessorArchitecture = 'win-arm32'
$strPowerShellVersion = $strNewestARM32Release
$boolUseMSI = $false
}
default {
#TODO: Confirm PowerShell 7 doesn't work on IA64 Windows for funzies
Write-Error ('Unknown processor architecture: ' + $strOSProcessorArchitecture)
$strPowerShellProcessorArchitecture = ''
$strPowerShellVersion = ''
}
}
if ($strPowerShellProcessorArchitecture -ne '') {
$strPowerShellReleaseWithoutExtension = 'PowerShell-' + $strPowerShellVersion + '-' + $strPowerShellProcessorArchitecture
if ($boolUseMSI) {
$strPowerShellRelease = $strPowerShellReleaseWithoutExtension + '.msi'
$strPowerShellReleaseType = 'MSI'
} else {
$strPowerShellRelease = $strPowerShellReleaseWithoutExtension + '.zip'
$strPowerShellReleaseType = 'ZIP'
}
$strDownloadURL = 'https://github.com/PowerShell/PowerShell/releases/download/v' + $strPowerShellVersion + '/' + $strPowerShellRelease
$strTargetFolder = Get-DownloadFolder
if ($null -ne $strTargetFolder) {
$strTargetPath = Join-Path $strTargetFolder $strPowerShellRelease
if ((Test-Path $strTargetPath) -eq $false) {
$strMessage = 'Downloading PowerShell ' + $strPowerShellVersion + ' for ' + $strPowerShellProcessorArchitecture + ' to ' + $strTargetPath + ' using URL: ' + $strDownloadURL
if ($versionPS.Major -ge 5) {
Write-Information $strMessage
} else {
Write-Host $strMessage
}
$actionPreferencePreviousProgress = $ProgressPreference
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest -Uri $strDownloadURL -OutFile $strTargetPath
$ProgressPreference = $actionPreferencePreviousProgress
if (Test-Path $strTargetPath) {
$boolDownloadSuccessful = $true
$strMessage = 'Finished downloading ' + $strPowerShellVersion + ' for ' + $strPowerShellProcessorArchitecture + ' to ' + $strTargetPath
if ($versionPS.Major -ge 5) {
Write-Information $strMessage
} else {
Write-Host $strMessage
}
} else {
$strMessage = 'Download of ' + $strDownloadURL + ' to ' + $strTargetPath + ' failed! The file did not exist after the download was attempted'
Write-Warning $strMessage
}
} else {
$boolDownloadSuccessful = $true
$strMessage = 'PowerShell ' + $strPowerShellVersion + ' for ' + $strPowerShellProcessorArchitecture + ' already downloaded to ' + $strTargetPath
if ($versionPS.Major -ge 5) {
Write-Information $strMessage
} else {
Write-Host $strMessage
}
}
} else {
Write-Warning 'Unable to locate suitable folder path for downloads. PowerShell download aborted.'
}
}
} else {
# Not Windows
#region Determine which processor architecture was specified, fall back to the one we're on
$strDotNetOSArchitecture = ''
if ([string]::IsNullOrEmpty($strDotNetOSArchitecture)) {
if ($null -ne $ARM64) {
if ($ARM64.IsPresent) {
$strDotNetOSArchitecture = 'Arm64'
}
}
}
if ([string]::IsNullOrEmpty($strDotNetOSArchitecture)) {
if ($null -ne $ARM) {
if ($ARM.IsPresent) {
$strDotNetOSArchitecture = 'Arm'
}
}
}
if ([string]::IsNullOrEmpty($strDotNetOSArchitecture)) {
if ($null -ne $x86) {
if ($x86.IsPresent) {
$strDotNetOSArchitecture = 'X86'
}
}
}
if ([string]::IsNullOrEmpty($strDotNetOSArchitecture)) {
if ($null -ne $x8664) {
if ($x8664.IsPresent) {
$strDotNetOSArchitecture = 'X64'
}
}
}
if ([string]::IsNullOrEmpty($strDotNetOSArchitecture)) {
if ($null -ne $AMD64) {
if ($AMD64.IsPresent) {
$strDotNetOSArchitecture = 'X64'
}
}
}
if ([string]::IsNullOrEmpty($strDotNetOSArchitecture)) {
$strDotNetOSArchitecture = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture
}
$strMessage = '$strDotNetOSArchitecture = ' + $strDotNetOSArchitecture
Write-Debug $strDotNetOSArchitecture
#endregion Determine which processor architecture was specified, fall back to the one we're on
$strPowerShellReleaseMetadata = 'https://raw.githubusercontent.com/PowerShell/PowerShell/master/tools/metadata.json'
$strPowerShellVersion = (Invoke-RestMethod -Uri $strPowerShellReleaseMetadata).StableReleaseTag -replace '^v'
if ($IsLinux) {
switch ($strDotNetOSArchitecture) {
'X64' {
$strPowerShellProcessorArchitecture = 'linux-x64'
}
'X86' {
$strPowerShellProcessorArchitecture = 'linux-x86'
}
'Arm' {
$strPowerShellProcessorArchitecture = 'linux-arm32'
}
'Arm64' {
$strPowerShellProcessorArchitecture = 'linux-arm64'
}
}
# TODO: Determine distribution of Linux and generate the file to download accordingly, store it in $strPowerShellRelease
# *** THIS IS NOT COMPLETE!!! ***
$strPowerShellReleaseType = 'TBD'
$strPowerShellReleaseWithoutExtension = 'TBD'
$strPowerShellRelease = $strPowerShellReleaseWithoutExtension + '.tbd'
$strDownloadURL = 'https://github.com/PowerShell/PowerShell/releases/download/v' + $strPowerShellVersion + '/' + $strPowerShellRelease
} elseif ($IsMacOS) {
switch ($strDotNetOSArchitecture) {
'X64' {
$strPowerShellProcessorArchitecture = 'osx-x64'
}
'Arm64' {
$strPowerShellProcessorArchitecture = 'osx-arm64'
}
}
# TODO: Generate the file to download programmatically, store it in $strPowerShellRelease
# *** THIS IS NOT COMPLETE!!! ***
$strPowerShellReleaseType = 'TBD'
$strPowerShellReleaseWithoutExtension = 'TBD'
$strPowerShellRelease = $strPowerShellReleaseWithoutExtension + '.tbd'
$strDownloadURL = 'https://github.com/PowerShell/PowerShell/releases/download/v' + $strPowerShellVersion + '/' + $strPowerShellRelease
}
$strTargetFolder = Get-DownloadFolder
if ($null -ne $strTargetFolder) {
$strTargetPath = Join-Path $strTargetFolder $strPowerShellRelease
if ((Test-Path $strTargetPath) -eq $false) {
$strMessage = 'Downloading PowerShell ' + $strPowerShellVersion + ' for ' + $strPowerShellProcessorArchitecture + ' to ' + $strTargetPath
if ($versionPS.Major -ge 5) {
Write-Information $strMessage
} else {
Write-Host $strMessage
}
$actionPreferencePreviousProgress = $ProgressPreference
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest -Uri $strDownloadURL -OutFile $strTargetPath
$ProgressPreference = $actionPreferencePreviousProgress
if (Test-Path $strTargetPath) {
$boolDownloadSuccessful = $true
$strMessage = 'Finished downloading ' + $strPowerShellVersion + ' for ' + $strPowerShellProcessorArchitecture + ' to ' + $strTargetPath
if ($versionPS.Major -ge 5) {
Write-Information $strMessage
} else {
Write-Host $strMessage
}
} else {
$strMessage = 'Download of ' + $strDownloadURL + ' to ' + $strTargetPath + ' failed! The file did not exist after the download was attempted'
Write-Warning $strMessage
}
} else {
$boolDownloadSuccessful = $true
$strMessage = 'PowerShell ' + $strPowerShellVersion + ' for ' + $strPowerShellProcessorArchitecture + ' already downloaded to ' + $strTargetPath
if ($versionPS.Major -ge 5) {
Write-Information $strMessage
} else {
Write-Host $strMessage
}
}
} else {
Write-Warning 'Unable to locate suitable folder path for downloads. PowerShell download aborted.'
}
}