forked from actions/runner-images
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInstallHelpers.ps1
1014 lines (817 loc) · 36.1 KB
/
InstallHelpers.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
function Install-Binary {
<#
.SYNOPSIS
A function to install binaries from either a URL or a local path.
.DESCRIPTION
This function downloads and installs .exe or .msi binaries from a specified URL or a local path. It also supports checking the binary's signature and SHA256/SHA512 sum before installation.
.PARAMETER Url
The URL from which the binary will be downloaded. This parameter is required if LocalPath is not specified.
.PARAMETER LocalPath
The local path of the binary to be installed. This parameter is required if Url is not specified.
.PARAMETER Type
The type of the binary to be installed. Valid values are "MSI" and "EXE". If not specified, the type is inferred from the file extension.
.PARAMETER InstallArgs
The list of arguments that will be passed to the installer. Cannot be used together with ExtraInstallArgs.
.PARAMETER ExtraInstallArgs
Additional arguments that will be passed to the installer. Cannot be used together with InstallArgs.
.PARAMETER ExpectedSignature
The expected signature of the binary. If specified, the binary's signature is checked before installation.
.PARAMETER ExpectedSHA256Sum
The expected SHA256 sum of the binary. If specified, the binary's SHA256 sum is checked before installation.
.PARAMETER ExpectedSHA512Sum
The expected SHA512 sum of the binary. If specified, the binary's SHA512 sum is checked before installation.
.EXAMPLE
Install-Binary -Url "https://go.microsoft.com/fwlink/p/?linkid=2083338" -Type EXE -InstallArgs ("/features", "+", "/quiet") -ExpectedSignature "A5C7D5B7C838D5F89DDBEDB85B2C566B4CDA881F"
#>
Param
(
[Parameter(Mandatory, ParameterSetName = "Url")]
[String] $Url,
[Parameter(Mandatory, ParameterSetName = "LocalPath")]
[String] $LocalPath,
[ValidateSet("MSI", "EXE")]
[String] $Type,
[String[]] $InstallArgs,
[String[]] $ExtraInstallArgs,
[String[]] $ExpectedSignature,
[String] $ExpectedSHA256Sum,
[String] $ExpectedSHA512Sum
)
if ($PSCmdlet.ParameterSetName -eq "LocalPath") {
if (-not (Test-Path -Path $LocalPath)) {
throw "LocalPath parameter is specified, but the file does not exist."
}
if (-not $Type) {
$Type = ([System.IO.Path]::GetExtension($LocalPath)).Replace(".", "").ToUpper()
if ($Type -ne "MSI" -and $Type -ne "EXE") {
throw "LocalPath parameter is specified, but the file extension is not .msi or .exe. Please specify the Type parameter."
}
}
$filePath = $LocalPath
} else {
if (-not $Type) {
$Type = ([System.IO.Path]::GetExtension($Url)).Replace(".", "").ToUpper()
if ($Type -ne "MSI" -and $Type -ne "EXE") {
throw "Cannot determine the file type from the URL. Please specify the Type parameter."
}
$fileName = [System.IO.Path]::GetFileName($Url)
} else {
$fileName = [System.IO.Path]::GetFileNameWithoutExtension([System.IO.Path]::GetRandomFileName()) + ".$Type".ToLower()
}
$filePath = Invoke-DownloadWithRetry -Url $Url -Path "${env:TEMP_DIR}\$fileName"
}
if ($PSBoundParameters.ContainsKey('ExpectedSignature')) {
if ($ExpectedSignature) {
Test-FileSignature -Path $filePath -ExpectedThumbprint $ExpectedSignature
} else {
throw "ExpectedSignature parameter is specified, but no signature is provided."
}
}
if ($ExpectedSHA256Sum) {
Test-FileChecksum $filePath -ExpectedSHA256Sum $ExpectedSHA256Sum
}
if ($ExpectedSHA512Sum) {
Test-FileChecksum $filePath -ExpectedSHA512Sum $ExpectedSHA512Sum
}
if ($ExtraInstallArgs -and $InstallArgs) {
throw "InstallArgs and ExtraInstallArgs parameters cannot be used together."
}
if ($Type -eq "MSI") {
# MSI binaries should be installed via msiexec.exe
if ($ExtraInstallArgs) {
$InstallArgs = @('/i', $filePath, '/qn', '/norestart') + $ExtraInstallArgs
} elseif (-not $InstallArgs) {
Write-Host "No arguments provided for MSI binary. Using default arguments: /i, /qn, /norestart"
$InstallArgs = @('/i', $filePath, '/qn', '/norestart')
}
$filePath = "msiexec.exe"
} else {
# EXE binaries should be started directly
if ($ExtraInstallArgs) {
$InstallArgs = $ExtraInstallArgs
}
}
$installStartTime = Get-Date
Write-Host "Starting Install $Name..."
try {
$process = Start-Process -FilePath $filePath -ArgumentList $InstallArgs -Wait -PassThru
$exitCode = $process.ExitCode
$installCompleteTime = [math]::Round(($(Get-Date) - $installStartTime).TotalSeconds, 2)
if ($exitCode -eq 0) {
Write-Host "Installation successful in $installCompleteTime seconds"
} elseif ($exitCode -eq 3010) {
Write-Host "Installation successful in $installCompleteTime seconds. Reboot is required."
} else {
Write-Host "Installation process returned unexpected exit code: $exitCode"
Write-Host "Standard Output:"
Write-Host $process.StandardOutput.ReadToEnd()
Write-Host "Standard Error:"
Write-Host $process.StandardError.ReadToEnd()
Write-Host "Time elapsed: $installCompleteTime seconds"
exit $exitCode
}
} catch {
$installCompleteTime = [math]::Round(($(Get-Date) - $installStartTime).TotalSeconds, 2)
Write-Host "Installation failed in $installCompleteTime seconds"
}
}
function Invoke-DownloadWithRetry {
<#
.SYNOPSIS
Downloads a file from a given URL with retry functionality.
.DESCRIPTION
The Invoke-DownloadWithRetry function downloads a file from the specified URL
to the specified path. It includes retry functionality in case the download fails.
.PARAMETER Url
The URL of the file to download.
.PARAMETER Path
The path where the downloaded file will be saved. If not provided, a temporary path
will be used.
.EXAMPLE
Invoke-DownloadWithRetry -Url "https://example.com/file.zip" -Path "C:\Downloads\file.zip"
Downloads the file from the specified URL and saves it to the specified path.
.EXAMPLE
Invoke-DownloadWithRetry -Url "https://example.com/file.zip"
Downloads the file from the specified URL and saves it to a temporary path.
.OUTPUTS
The path where the downloaded file is saved.
#>
Param
(
[Parameter(Mandatory)]
[string] $Url,
[Alias("Destination")]
[string] $Path
)
if (-not $Path) {
$invalidChars = [IO.Path]::GetInvalidFileNameChars() -join ''
$re = "[{0}]" -f [RegEx]::Escape($invalidChars)
$fileName = [IO.Path]::GetFileName($Url) -replace $re
if ([String]::IsNullOrEmpty($fileName)) {
$fileName = [System.IO.Path]::GetRandomFileName()
}
$Path = Join-Path -Path "${env:TEMP_DIR}" -ChildPath $fileName
}
Write-Host "Downloading package from $Url to $Path..."
$interval = 30
$downloadStartTime = Get-Date
for ($retries = 20; $retries -gt 0; $retries--) {
try {
$attemptStartTime = Get-Date
(New-Object System.Net.WebClient).DownloadFile($Url, $Path)
$attemptSeconds = [math]::Round(($(Get-Date) - $attemptStartTime).TotalSeconds, 2)
Write-Host "Package downloaded in $attemptSeconds seconds"
break
} catch {
$attemptSeconds = [math]::Round(($(Get-Date) - $attemptStartTime).TotalSeconds, 2)
Write-Warning "Package download failed in $attemptSeconds seconds"
Write-Warning $_.Exception.Message
if ($_.Exception.InnerException.Response.StatusCode -eq [System.Net.HttpStatusCode]::NotFound) {
Write-Warning "Request returned 404 Not Found. Aborting download."
$retries = 0
}
}
if ($retries -eq 0) {
$totalSeconds = [math]::Round(($(Get-Date) - $downloadStartTime).TotalSeconds, 2)
throw "Package download failed after $totalSeconds seconds"
}
Write-Warning "Waiting $interval seconds before retrying (retries left: $retries)..."
Start-Sleep -Seconds $interval
}
return $Path
}
function Get-ToolsetContent {
<#
.SYNOPSIS
Retrieves the content of the toolset.json file.
.DESCRIPTION
This function reads the toolset.json file in path provided by IMAGE_FOLDER
environment variable and returns the content as a PowerShell object.
#>
$toolsetPath = Join-Path $env:IMAGE_FOLDER "toolset.json"
$toolsetJson = Get-Content -Path $toolsetPath -Raw
ConvertFrom-Json -InputObject $toolsetJson
}
function Get-TCToolPath {
<#
.SYNOPSIS
This function returns the full path of a tool in the tool cache.
.DESCRIPTION
The Get-TCToolPath function takes a tool name as a parameter and returns the full path of the tool in the tool cache.
It uses the AGENT_TOOLSDIRECTORY environment variable to determine the root path of the tool cache.
.PARAMETER ToolName
The name of the tool for which the path is to be returned.
.EXAMPLE
Get-TCToolPath -ToolName "Tool1"
This command returns the full path of "Tool1" in the tool cache.
#>
Param
(
[string] $ToolName
)
$toolcacheRootPath = Resolve-Path $env:AGENT_TOOLSDIRECTORY
return Join-Path $toolcacheRootPath $ToolName
}
function Get-TCToolVersionPath {
<#
.SYNOPSIS
This function returns the full path of a specific version of a tool in the tool cache.
.DESCRIPTION
The Get-TCToolVersionPath function takes a tool name, version, and architecture as parameters and returns the full path of the specified version of the tool in the tool cache.
It uses the Get-TCToolPath function to get the root path of the tool.
.PARAMETER Name
The name of the tool for which the path is to be returned.
.PARAMETER Version
The version of the tool for which the path is to be returned. If the version number is less than 3 parts, a wildcard is added.
.PARAMETER Arch
The architecture of the tool for which the path is to be returned. Defaults to "x64".
.EXAMPLE
Get-TCToolVersionPath -Name "Tool1" -Version "1.0" -Arch "x86"
This command returns the full path of version "1.0" of "Tool1" for "x86" architecture in the tool cache.
#>
Param
(
[Parameter(Mandatory = $true)]
[string] $Name,
[Parameter(Mandatory = $true)]
[string] $Version,
[string] $Arch = "x64"
)
$toolPath = Get-TCToolPath -ToolName $Name
# Add wildcard if missing
if ($Version.Split(".").Length -lt 3) {
$Version += ".*"
}
$versionPath = Join-Path $toolPath $Version
# Take latest installed version in case if toolset version contains wildcards
$foundVersion = Get-Item $versionPath `
| Sort-Object -Property { [version] $_.name } -Descending `
| Select-Object -First 1
if (-not $foundVersion) {
return $null
}
return Join-Path $foundVersion $Arch
}
function Test-IsWin22 {
<#
.SYNOPSIS
Checks if the current Windows operating system is Windows Server 2022.
.DESCRIPTION
This function uses the Get-CimInstance cmdlet to retrieve information
about the current Windows operating system. It then checks if the Caption
property of the Win32_OperatingSystem class contains the string "2022",
indicating that the operating system is Windows Server 2022.
.OUTPUTS
Returns $true if the current Windows operating system is Windows Server 2022.
Otherwise, returns $false.
#>
(Get-CimInstance -ClassName Win32_OperatingSystem).Caption -match "2022"
}
function Test-IsWin19 {
<#
.SYNOPSIS
Checks if the current Windows operating system is Windows Server 2019.
.DESCRIPTION
This function uses the Get-CimInstance cmdlet to retrieve information
about the current Windows operating system. It then checks if the Caption
property of the Win32_OperatingSystem class contains the string "2019",
indicating that the operating system is Windows Server 2019.
.OUTPUTS
Returns $true if the current Windows operating system is Windows Server 2019.
Otherwise, returns $false.
#>
(Get-CimInstance -ClassName Win32_OperatingSystem).Caption -match "2019"
}
function Expand-7ZipArchive {
<#
.SYNOPSIS
Extracts files from a 7-Zip archive.
.DESCRIPTION
This function uses the 7z.exe command-line tool to extract files from an archive.
The archive path, destination path, and extract method are specified as parameters.
.PARAMETER Path
The path to the archive.
.PARAMETER DestinationPath
The path to the directory where the files will be extracted.
.PARAMETER ExtractMethod
The method used to extract the files.
Valid values are "x" (extract with full paths) and "e" (extract without paths).
.EXAMPLE
Expand-7ZipArchive -Path "C:\archive.7z" -DestinationPath "C:\extracted" -ExtractMethod "x"
Extracts files from the "C:\archive.7z" archive to the "C:\extracted" directory keeping the full paths.
#>
Param
(
[Parameter(Mandatory = $true)]
[string] $Path,
[Parameter(Mandatory = $true)]
[string] $DestinationPath,
[ValidateSet("x", "e")]
[char] $ExtractMethod = "x"
)
Write-Host "Expand archive '$PATH' to '$DestinationPath' directory"
7z.exe $ExtractMethod "$Path" -o"$DestinationPath" -y | Out-Null
if ($LASTEXITCODE -ne 0) {
Write-Host "There is an error during expanding '$Path' to '$DestinationPath' directory"
exit 1
}
}
function Get-WindowsUpdateStates {
<#
.SYNOPSIS
Retrieves the status of Windows updates.
.DESCRIPTION
The Get-WindowsUpdateStates function checks the Windows Event Log for specific event IDs related to Windows updates and returns a custom PowerShell object with the state and title of each update.
.PARAMETER None
This function does not take any parameters.
.OUTPUTS
PSCustomObject. This function returns a collection of custom PowerShell objects. Each object has two properties:
- State: A string that represents the state of the update. Possible values are "Installed", "Failed", and "Running".
- Title: A string that represents the title of the update.
.NOTES
Event IDs used:
- 19: Installation Successful: Windows successfully installed the following update
- 20: Installation Failure: Windows failed to install the following update with error
- 43: Installation Started: Windows has started installing the following update
#>
$completedUpdates = @{}
$filter = @{
LogName = "System"
Id = 19, 20, 43
ProviderName = "Microsoft-Windows-WindowsUpdateClient"
}
$events = Get-WinEvent -FilterHashtable $filter -ErrorAction SilentlyContinue | Sort-Object Id
foreach ( $event in $events ) {
switch ( $event.Id ) {
19 {
$state = "Installed"
$title = $event.Properties[0].Value
$completedUpdates[$title] = ""
break
}
20 {
$state = "Failed"
$title = $event.Properties[1].Value
$completedUpdates[$title] = ""
break
}
43 {
$state = "Running"
$title = $event.Properties[0].Value
break
}
}
# Skip update started event if it was already completed
if ( $state -eq "Running" -and $completedUpdates.ContainsKey($title) ) {
continue
}
[PSCustomObject]@{
State = $state
Title = $title
}
}
}
function Invoke-ScriptBlockWithRetry {
<#
.SYNOPSIS
Executes a script block with retry logic.
.DESCRIPTION
The Invoke-ScriptBlockWithRetry function executes a specified script block with retry logic. It allows you to specify the number of retries and the interval between retries.
.PARAMETER Command
The script block to be executed.
.PARAMETER RetryCount
The number of times to retry executing the script block. The default value is 10.
.PARAMETER RetryIntervalSeconds
The interval in seconds between each retry. The default value is 5.
.EXAMPLE
Invoke-ScriptBlockWithRetry -Command { Get-Process } -RetryCount 3 -RetryIntervalSeconds 10
This example executes the script block { Get-Process } with 3 retries and a 10-second interval between each retry.
#>
param (
[scriptblock] $Command,
[int] $RetryCount = 10,
[int] $RetryIntervalSeconds = 5
)
while ($RetryCount -gt 0) {
try {
& $Command
return
} catch {
Write-Host "There is an error encountered:`n $_"
$RetryCount--
if ($RetryCount -eq 0) {
exit 1
}
Write-Host "Waiting $RetryIntervalSeconds seconds before retrying. Retries left: $RetryCount"
Start-Sleep -Seconds $RetryIntervalSeconds
}
}
}
function Get-GithubReleasesByVersion {
<#
.SYNOPSIS
Retrieves GitHub releases for a specified repository based on version.
.DESCRIPTION
The function retrieves GitHub releases for a specified repository based on the
version provided. It supports filtering by version, allowing for the retrieval
of specific releases or the latest release. The function utilizes the GitHub REST API
to fetch the releases and caches the results to improve performance and reduce
the number of API calls.
.PARAMETER Repository
The name of the GitHub repository in the format "owner/repo".
.PARAMETER Version
The version of the release to retrieve. It can be a specific version number,
"latest" to retrieve the latest release, or a wildcard pattern to match multiple versions.
.PARAMETER AllowPrerelease
Specifies whether to include prerelease versions in the results. By default,
prerelease versions are excluded.
.PARAMETER WithAssetsOnly
Specifies whether to exclude releases without assets. By default, releases without
assets are included.
.EXAMPLE
Get-GithubReleasesByVersion -Repository "Microsoft/PowerShell" -Version "7.2.0"
Retrieves the GitHub releases for the "Microsoft/PowerShell" repository with the version "7.2.0".
.EXAMPLE
Get-GithubReleasesByVersion -Repository "Microsoft/PowerShell" -Version "latest"
Retrieves the latest GitHub release for the "Microsoft/PowerShell" repository.
.EXAMPLE
Get-GithubReleasesByVersion -Repository "Microsoft/PowerShell" -Version "7.*"
Retrieves all GitHub releases for the "Microsoft/PowerShell" repository with versions starting with "7.".
#>
param (
[Parameter(Mandatory = $true)]
[Alias("Repo")]
[string] $Repository,
[string] $Version = "*",
[switch] $AllowPrerelease,
[switch] $WithAssetsOnly
)
$localCacheFile = Join-Path ${env:TEMP_DIR} "github-releases_$($Repository -replace "/", "_").json"
if (Test-Path $localCacheFile) {
$releases = Get-Content $localCacheFile | ConvertFrom-Json
Write-Debug "Found cached releases for ${Repository} in local file"
Write-Debug "Release count: $($releases.Count)"
} else {
$releases = @()
$page = 1
$pageSize = 100
do {
$releasesPage = Invoke-RestMethod -Uri "https://api.github.com/repos/${Repository}/releases?per_page=${pageSize}&page=${page}"
$releases += $releasesPage
$page++
} while ($releasesPage.Count -eq $pageSize)
Write-Debug "Found $($releases.Count) releases for ${Repository}"
Write-Debug "Caching releases for ${Repository} in local file"
$releases | ConvertTo-Json -Depth 10 | Set-Content $localCacheFile
}
if (-not $releases) {
throw "Failed to get releases from ${Repository}"
}
if ($WithAssetsOnly) {
$releases = $releases.Where{ $_.assets }
}
if (-not $AllowPrerelease) {
$releases = $releases.Where{ $_.prerelease -eq $false }
}
Write-Debug "Found $($releases.Count) releases with assets for ${Repository}"
# Parse version from tag name and put it to parameter Version
foreach ($release in $releases) {
$release | Add-Member -MemberType NoteProperty -Name version -Value (
$release.tag_name | Select-String -Pattern "\d+.\d+.\d+" | ForEach-Object { $_.Matches.Value }
)
}
# Sort releases by version
$releases = $releases | Sort-Object -Descending { [version] $_.version }
# Select releases matching version
if ($Version -eq "latest") {
$matchingReleases = $releases | Select-Object -First 1
} elseif ($Version.Contains("*")) {
$matchingReleases = $releases | Where-Object { $_.version -like "$Version" }
} else {
$matchingReleases = $releases | Where-Object { $_.version -eq "$Version" }
}
if (-not $matchingReleases) {
throw "Failed to get releases from ${Repository} matching version `"${Version}`".`nAvailable versions: $($availableVersions -join ", ")"
}
Write-Debug "Found $($matchingReleases.Count) releases matching version ${Version} for ${Repository}"
return $matchingReleases
}
function Resolve-GithubReleaseAssetUrl {
<#
.SYNOPSIS
Resolves the download URL for a specific asset in a GitHub release.
.DESCRIPTION
This function retrieves the download URL for a specific asset in a GitHub release.
It takes the repository name, version, and a URL match pattern as input parameters.
It searches for releases that match the specified version and then looks
for a download URL that matches the provided pattern. If a matching URL is found,
it returns the URL. If no matching URL is found, an exception is thrown.
.PARAMETER Repository
The name of the GitHub repository in the format "owner/repo".
.PARAMETER Version
The version of the release to retrieve. It can be a specific version number,
"latest" to retrieve the latest release, or a wildcard pattern to match multiple versions.
.PARAMETER AllowPrerelease
Specifies whether to include prerelease versions in the results. By default,
prerelease versions are excluded.
.PARAMETER UrlMatchPattern
The pattern to match against the download URLs of the release assets.
Wildcards (*) can be used to match any characters.
.PARAMETER AllowMultipleMatches
Specifies whether to choose one of multiple assets matching the pattern or consider this behavior to be erroneous.
By default, multiple matches are not considered normal behavior and result in an error.
.EXAMPLE
Resolve-GithubReleaseAssetUrl -Repository "myrepo" -Version "1.0" -UrlMatchPattern "*.zip"
Retrieves the download URL for the asset in the "myrepo" repository with version "1.0" and a file extension of ".zip".
#>
param (
[Parameter(Mandatory = $true)]
[Alias("Repo")]
[string] $Repository,
[string] $Version = "*",
[switch] $AllowPrerelease,
[Parameter(Mandatory = $true)]
[Alias("Pattern", "File", "Asset")]
[string] $UrlMatchPattern,
[switch] $AllowMultipleMatches = $false
)
$matchingReleases = Get-GithubReleasesByVersion `
-Repository $Repository `
-AllowPrerelease:$AllowPrerelease `
-Version $Version `
-WithAssetsOnly
# Add wildcard to the beginning of the pattern if it's not there
if ($UrlMatchPattern.Substring(0, 2) -ne "*/") {
$UrlMatchPattern = "*/$UrlMatchPattern"
}
# Loop over releases until we find a download url matching the pattern
foreach ($release in $matchingReleases) {
$matchedVersion = $release.version
$matchedUrl = ([string[]] $release.assets.browser_download_url) -like $UrlMatchPattern
if ($matchedUrl) {
break
}
}
if (-not $matchedUrl) {
Write-Debug "Found no download urls matching pattern ${UrlMatchPattern}"
Write-Debug "Available download urls:`n$($matchingReleases.assets.browser_download_url -join "`n")"
throw "No assets found in ${Repository} matching version `"${Version}`" and pattern `"${UrlMatchPattern}`""
}
# If multiple urls match the pattern, sort them and take the last one
# Will only work with simple number series of no more than nine in a row.
if ($matchedUrl.Count -gt 1) {
if ($AllowMultipleMatches) {
Write-Debug "Found multiple download urls matching pattern ${UrlMatchPattern}:`n$($matchedUrl -join "`n")"
Write-Host "Performing sorting of urls to find the most recent version matching the pattern"
$matchedUrl = $matchedUrl | Sort-Object -Descending
$matchedUrl = $matchedUrl[0]
} else {
throw "Found multiple assets in ${Repository} matching version `"${Version}`" and pattern `"${UrlMatchPattern}`".`nAvailable assets:`n$($matchedUrl -join "`n")"
}
}
Write-Host "Found download url for ${Repository} version ${matchedVersion}: ${matchedUrl}"
return ($matchedUrl -as [string])
}
function Get-ChecksumFromGithubRelease {
<#
.SYNOPSIS
Retrieves the hash value of a specific file from a GitHub release body.
.DESCRIPTION
The Get-ChecksumFromGithubRelease function retrieves the hash value (SHA256 or SHA512)
of a specific file from a GitHub release. It searches for the file in the release body
and returns the hash value if found.
.PARAMETER Repository
The name of the GitHub repository in the format "owner/repo".
.PARAMETER Version
The version of the release to inspect. It can be a specific version number,
"latest" to retrieve the latest release, or a wildcard pattern to match multiple versions.
.PARAMETER AllowPrerelease
Specifies whether to include prerelease versions in the results. By default,
prerelease versions are excluded.
.PARAMETER FileName
The name of the file to retrieve the hash value for.
.PARAMETER HashType
The type of hash value to retrieve. Valid values are "SHA256" and "SHA512".
.EXAMPLE
Get-ChecksumFromGithubRelease -Repository "MyRepo" -FileName "myfile.txt" -HashType "SHA256"
Retrieves the SHA256 hash value of "myfile.txt" from the latest release of the "MyRepo" repository.
.EXAMPLE
Get-ChecksumFromGithubRelease -Repository "MyRepo" -Version "1.0" -FileName "myfile.txt" -HashType "SHA512"
Retrieves the SHA512 hash value of "myfile.txt" from the release version "1.0" of the "MyRepo" repository.
#>
param (
[Parameter(Mandatory = $true)]
[Alias("Repo")]
[string] $Repository,
[string] $Version = "*",
[switch] $AllowPrerelease,
[Parameter(Mandatory = $true)]
[Alias("File", "Asset")]
[string] $FileName,
[Parameter(Mandatory = $true)]
[ValidateSet("SHA256", "SHA512")]
[string] $HashType
)
$matchingReleases = Get-GithubReleasesByVersion `
-Repository $Repository `
-AllowPrerelease:$AllowPrerelease `
-Version $Version `
-WithAssetsOnly
foreach ($release in $matchingReleases) {
$matchedVersion = $release.version
$matchedBody = $release.body
$matchedLine = $matchedBody.Split("`n") | Where-Object { $_ -like "*$FileName*" }
if ($matchedLine.Count -gt 1) {
throw "Found multiple lines matching file name '${FileName}' in body of release ${matchedVersion}."
} elseif ($matchedLine.Count -ne 0) {
break
}
}
if (-not $matchedLine) {
throw "File name '${FileName}' not found in release body."
}
Write-Debug "Found line matching file name '${FileName}' in body of release ${matchedVersion}:`n${matchedLine}"
if ($HashType -eq "SHA256") {
$pattern = "[A-Fa-f0-9]{64}"
} elseif ($HashType -eq "SHA512") {
$pattern = "[A-Fa-f0-9]{128}"
} else {
throw "Unknown hash type: ${HashType}"
}
$hash = $matchedLine | Select-String -Pattern $pattern | ForEach-Object { $_.Matches.Value }
if ([string]::IsNullOrEmpty($hash)) {
throw "Found '${FileName}' in body of release ${matchedVersion}, but failed to get hash from it.`nLine: ${matchedLine}"
}
Write-Host "Found hash for ${FileName} in release ${matchedVersion}: $hash"
return $hash
}
function Get-ChecksumFromUrl {
<#
.SYNOPSIS
Retrieves the checksum hash for a file from a given URL.
.DESCRIPTION
The Get-ChecksumFromUrl function retrieves the checksum hash for a specified file
from a given URL. It supports SHA256 and SHA512 hash types.
.PARAMETER Url
The URL of the checksum file.
.PARAMETER FileName
The name of the file to retrieve the checksum hash for.
.PARAMETER HashType
The type of hash to retrieve. Valid values are "SHA256" and "SHA512".
.EXAMPLE
Get-ChecksumFromUrl -Url "https://example.com/checksums.txt" -FileName "file.txt" -HashType "SHA256"
Retrieves the SHA256 checksum hash for the file "file.txt" from the URL "https://example.com/checksums.txt".
#>
param (
[Parameter(Mandatory = $true)]
[string] $Url,
[Parameter(Mandatory = $true)]
[Alias("File", "Asset")]
[string] $FileName,
[Parameter(Mandatory = $true)]
[ValidateSet("SHA256", "SHA512")]
[Alias("Type")]
[string] $HashType
)
$tempFile = Join-Path -Path $env:TEMP_DIR -ChildPath ([System.IO.Path]::GetRandomFileName())
$checksums = (Invoke-DownloadWithRetry -Url $Url -Path $tempFile | Get-Item | Get-Content) -as [string[]]
Remove-Item -Path $tempFile
$matchedLine = $checksums | Where-Object { $_ -like "*$FileName*" }
if ($matchedLine.Count -gt 1) {
throw "Found multiple lines matching file name '${FileName}' in checksum file."
} elseif ($matchedLine.Count -eq 0) {
throw "File name '${FileName}' not found in checksum file."
}
if ($HashType -eq "SHA256") {
$pattern = "[A-Fa-f0-9]{64}"
} elseif ($HashType -eq "SHA512") {
$pattern = "[A-Fa-f0-9]{128}"
} else {
throw "Unknown hash type: ${HashType}"
}
Write-Debug "Found line matching file name '${FileName}' in checksum file:`n${matchedLine}"
$hash = $matchedLine | Select-String -Pattern $pattern | ForEach-Object { $_.Matches.Value }
if ([string]::IsNullOrEmpty($hash)) {
throw "Found '${FileName}' in checksum file, but failed to get hash from it.`nLine: ${matchedLine}"
}
Write-Host "Found hash for ${FileName} in checksum file: $hash"
return $hash
}
function Test-FileChecksum {
<#
.SYNOPSIS
Verifies the checksum of a file.
.DESCRIPTION
The Test-FileChecksum function verifies the SHA256 or SHA512 checksum of a file against an expected value.
If the checksum does not match the expected value, the function throws an error.
.PARAMETER Path
The path to the file for which to verify the checksum.
.PARAMETER ExpectedSHA256Sum
The expected SHA256 checksum. If this parameter is provided, the function will calculate the SHA256 checksum of the file and compare it to this value.
.PARAMETER ExpectedSHA512Sum
The expected SHA512 checksum. If this parameter is provided, the function will calculate the SHA512 checksum of the file and compare it to this value.
.EXAMPLE
Test-FileChecksum -Path "C:\temp\file.txt" -ExpectedSHA256Sum "ABC123"
Verifies that the SHA256 checksum of the file at C:\temp\file.txt is ABC123.
.EXAMPLE
Test-FileChecksum -Path "C:\temp\file.txt" -ExpectedSHA512Sum "DEF456"
Verifies that the SHA512 checksum of the file at C:\temp\file.txt is DEF456.
#>
param (
[Parameter(Mandatory = $true, Position = 0)]
[string] $Path,
[Parameter(Mandatory = $false)]
[String] $ExpectedSHA256Sum,
[Parameter(Mandatory = $false)]
[String] $ExpectedSHA512Sum
)
Write-Verbose "Performing checksum verification"
if ($ExpectedSHA256Sum -and $ExpectedSHA512Sum) {
throw "Only one of the ExpectedSHA256Sum and ExpectedSHA512Sum parameters can be provided"
}
if (-not (Test-Path $Path)) {
throw "File not found: $Path"
}
if ($ExpectedSHA256Sum) {
$fileHash = (Get-FileHash -Path $Path -Algorithm SHA256).Hash
$expectedHash = $ExpectedSHA256Sum
}
if ($ExpectedSHA512Sum) {
$fileHash = (Get-FileHash -Path $Path -Algorithm SHA512).Hash
$expectedHash = $ExpectedSHA512Sum
}
if ($fileHash -ne $expectedHash) {
throw "Checksum verification failed: expected $expectedHash, got $fileHash"
} else {
Write-Verbose "Checksum verification passed"
}
}
function Test-FileSignature {
<#
.SYNOPSIS
Tests the file signature of a given file.
.DESCRIPTION
The Test-FileSignature function checks the signature of a file against the expected thumbprints.
It uses the Get-AuthenticodeSignature cmdlet to retrieve the signature information of the file.
If the signature status is not valid or the thumbprint does not match the expected thumbprints, an exception is thrown.
.PARAMETER Path
Specifies the path of the file to test.
.PARAMETER ExpectedThumbprint
Specifies the expected thumbprints to match against the file's signature.
.EXAMPLE
Test-FileSignature -Path "C:\Path\To\File.exe" -ExpectedThumbprint "A1B2C3D4E5F6G7H8I9J0K1L2M3N4O5P6Q7R8S9T0"
This example tests the signature of the file "C:\Path\To\File.exe" against the expected thumbprint "A1B2C3D4E5F6G7H8I9J0K1L2M3N4O5P6Q7R8S9T0".
#>
param(
[Parameter(Mandatory = $true, Position = 0)]
[string] $Path,
[Parameter(Mandatory = $true)]
[string[]] $ExpectedThumbprint
)
$signature = Get-AuthenticodeSignature $Path
if ($signature.Status -ne "Valid") {
throw "Signature status is not valid. Status: $($signature.Status)"
}
foreach ($thumbprint in $ExpectedThumbprint) {
if ($signature.SignerCertificate.Thumbprint.Contains($thumbprint)) {
Write-Output "Signature for $Path is valid"
$signatureMatched = $true
return
}
}
if ($signatureMatched) {
Write-Output "Signature for $Path is valid"
} else {
throw "Signature thumbprint do not match expected."
}
}
function Update-Environment {
<#
.SYNOPSIS
Updates the environment variables by reading values from the registry.
.DESCRIPTION
This function updates current environment by reading values from the registry.
It is useful when you need to update the environment variables without restarting the current session.
.NOTES
The function requires administrative privileges to modify the system registry.
#>
$locations = @(
'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment',
'HKCU:\Environment'
)
# Update PATH variable
$pathItems = $locations | ForEach-Object {
(Get-Item $_).GetValue('PATH').Split(';')