forked from mthalman/winget-pkgs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
YamlCreate.ps1
2725 lines (2515 loc) · 143 KB
/
YamlCreate.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
#Requires -Version 5
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Justification = 'This script is not intended to have any outputs piped')]
Param
(
[switch] $Settings,
[switch] $AutoUpgrade,
[switch] $help,
[switch] $SkipPRCheck,
[Parameter(Mandatory = $false)]
[string] $PackageIdentifier,
[Parameter(Mandatory = $false)]
[string] $PackageVersion,
[Parameter(Mandatory = $false)]
[string] $Mode
)
if ($help) {
Write-Host -ForegroundColor 'Green' 'For full documentation of the script, see https://github.com/microsoft/winget-pkgs/tree/master/doc/tools/YamlCreate.md'
Write-Host -ForegroundColor 'Yellow' 'Usage: ' -NoNewline
Write-Host -ForegroundColor 'White' '.\YamlCreate.ps1 [-PackageIdentifier <identifier>] [-PackageVersion <version>] [-Mode <1-5>] [-Settings] [-SkipPRCheck]'
Write-Host
exit
}
# Check whether the script is present inside a fork/clone of microsoft/winget-pkgs repository
try {
$script:gitTopLevel = (Resolve-Path $(git rev-parse --show-toplevel)).Path
} catch {
# If there was an exception, the user isn't in a git repo. Throw a custom exception and pass the original exception as an InternalException
throw [UnmetDependencyException]::new('This script must be run from inside a clone of the winget-pkgs repository', $_.Exception)
}
# Installs `powershell-yaml` as a dependency for parsing yaml content
if (-not(Get-Module -ListAvailable -Name powershell-yaml)) {
try {
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
Install-Module -Name powershell-yaml -Force -Repository PSGallery -Scope CurrentUser
} catch {
# If there was an exception while installing powershell-yaml, pass it as an InternalException for further debugging
throw [UnmetDependencyException]::new("'powershell-yaml' unable to be installed successfully", $_.Exception)
} finally {
# Double check that it was installed properly
if (-not(Get-Module -ListAvailable -Name powershell-yaml)) {
throw [UnmetDependencyException]::new("'powershell-yaml' is not found")
}
}
}
# Set settings directory on basis of Operating System
$script:SettingsPath = Join-Path $(if ([System.Environment]::OSVersion.Platform -match 'Win') { $env:LOCALAPPDATA } else { $env:HOME + '/.config' } ) -ChildPath 'YamlCreate'
# Check for settings directory and create it if none exists
if (!(Test-Path $script:SettingsPath)) { New-Item -ItemType 'Directory' -Force -Path $script:SettingsPath | Out-Null }
# Check for settings file and create it if none exists
$script:SettingsPath = $(Join-Path $script:SettingsPath -ChildPath 'Settings.yaml')
if (!(Test-Path $script:SettingsPath)) { '# See https://github.com/microsoft/winget-pkgs/tree/master/doc/tools/YamlCreate.md for a list of available settings' > $script:SettingsPath }
# Load settings from file
$ScriptSettings = ConvertFrom-Yaml -Yaml ($(Get-Content -Path $script:SettingsPath -Encoding UTF8) -join "`n")
if ($Settings) {
Invoke-Item -Path $script:SettingsPath
exit
}
$ScriptHeader = '# Created with YamlCreate.ps1 v2.1.2'
$ManifestVersion = '1.1.0'
$PSDefaultParameterValues = @{ '*:Encoding' = 'UTF8' }
$Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False
$ofs = ', '
$callingUICulture = [Threading.Thread]::CurrentThread.CurrentUICulture
$callingCulture = [Threading.Thread]::CurrentThread.CurrentCulture
[Threading.Thread]::CurrentThread.CurrentUICulture = 'en-US'
[Threading.Thread]::CurrentThread.CurrentCulture = 'en-US'
<#
.SYNOPSIS
Winget Manifest creation helper script
.DESCRIPTION
The intent of this file is to help you generate a manifest for publishing
to the Windows Package Manager repository.
It'll attempt to download an installer from the user-provided URL to calculate
a checksum. That checksum and the rest of the input data will be compiled in a
.YAML file.
.EXAMPLE
PS C:\Projects\winget-pkgs> Get-Help .\Tools\YamlCreate.ps1 -Full
Show this script's help
.EXAMPLE
PS C:\Projects\winget-pkgs> .\Tools\YamlCreate.ps1
Run the script to create a manifest file
.NOTES
Please file an issue if you run into errors with this script:
https://github.com/microsoft/winget-pkgs/issues/
.LINK
https://github.com/microsoft/winget-pkgs/blob/master/Tools/YamlCreate.ps1
#>
# Fetch Schema data from github for entry validation, key ordering, and automatic commenting
try {
$ProgressPreference = 'SilentlyContinue'
$LocaleSchema = @(Invoke-WebRequest "https://raw.githubusercontent.com/microsoft/winget-cli/master/schemas/JSON/manifests/v$ManifestVersion/manifest.defaultLocale.$ManifestVersion.json" -UseBasicParsing | ConvertFrom-Json)
$LocaleProperties = (ConvertTo-Yaml $LocaleSchema.properties | ConvertFrom-Yaml -Ordered).Keys
$VersionSchema = @(Invoke-WebRequest "https://raw.githubusercontent.com/microsoft/winget-cli/master/schemas/JSON/manifests/v$ManifestVersion/manifest.version.$ManifestVersion.json" -UseBasicParsing | ConvertFrom-Json)
$VersionProperties = (ConvertTo-Yaml $VersionSchema.properties | ConvertFrom-Yaml -Ordered).Keys
$InstallerSchema = @(Invoke-WebRequest "https://raw.githubusercontent.com/microsoft/winget-cli/master/schemas/JSON/manifests/v$ManifestVersion/manifest.installer.$ManifestVersion.json" -UseBasicParsing | ConvertFrom-Json)
$InstallerProperties = (ConvertTo-Yaml $InstallerSchema.properties | ConvertFrom-Yaml -Ordered).Keys
$InstallerSwitchProperties = (ConvertTo-Yaml $InstallerSchema.definitions.InstallerSwitches.properties | ConvertFrom-Yaml -Ordered).Keys
$InstallerEntryProperties = (ConvertTo-Yaml $InstallerSchema.definitions.Installer.properties | ConvertFrom-Yaml -Ordered).Keys
$InstallerDependencyProperties = (ConvertTo-Yaml $InstallerSchema.definitions.Dependencies.properties | ConvertFrom-Yaml -Ordered).Keys
} catch {
# Here we want to pass the exception as an inner exception for debugging if necessary
throw [System.Net.WebException]::new('Manifest schemas could not be downloaded. Try running the script again', $_.Exception)
}
filter TrimString {
$_.Trim()
}
filter UniqueItems {
[string]$($_.Split(',').Trim() | Select-Object -Unique)
}
filter ToLower {
[string]$_.ToLower()
}
filter NoWhitespace {
[string]$_ -replace '\s{1,}', '-'
}
$ToNatural = { [regex]::Replace($_, '\d+', { $args[0].Value.PadLeft(20) }) }
# Various patterns used in validation to simplify the validation logic
$Patterns = @{
PackageIdentifier = $VersionSchema.properties.PackageIdentifier.pattern
IdentifierMaxLength = $VersionSchema.properties.PackageIdentifier.maxLength
PackageVersion = $InstallerSchema.definitions.PackageVersion.pattern
VersionMaxLength = $VersionSchema.properties.PackageVersion.maxLength
InstallerSha256 = $InstallerSchema.definitions.Installer.properties.InstallerSha256.pattern
InstallerUrl = $InstallerSchema.definitions.Installer.properties.InstallerUrl.pattern
InstallerUrlMaxLength = $InstallerSchema.definitions.Installer.properties.InstallerUrl.maxLength
ValidArchitectures = $InstallerSchema.definitions.Installer.properties.Architecture.enum
ValidInstallerTypes = $InstallerSchema.definitions.InstallerType.enum
SilentSwitchMaxLength = $InstallerSchema.definitions.InstallerSwitches.properties.Silent.maxLength
ProgressSwitchMaxLength = $InstallerSchema.definitions.InstallerSwitches.properties.SilentWithProgress.maxLength
CustomSwitchMaxLength = $InstallerSchema.definitions.InstallerSwitches.properties.Custom.maxLength
SignatureSha256 = $InstallerSchema.definitions.Installer.properties.SignatureSha256.pattern
FamilyName = $InstallerSchema.definitions.PackageFamilyName.pattern
FamilyNameMaxLength = $InstallerSchema.definitions.PackageFamilyName.maxLength
PackageLocale = $LocaleSchema.properties.PackageLocale.pattern
InstallerLocaleMaxLength = $InstallerSchema.definitions.Locale.maxLength
ProductCodeMinLength = $InstallerSchema.definitions.ProductCode.minLength
ProductCodeMaxLength = $InstallerSchema.definitions.ProductCode.maxLength
MaxItemsFileExtensions = $InstallerSchema.definitions.FileExtensions.maxItems
MaxItemsProtocols = $InstallerSchema.definitions.Protocols.maxItems
MaxItemsCommands = $InstallerSchema.definitions.Commands.maxItems
MaxItemsSuccessCodes = $InstallerSchema.definitions.InstallerSuccessCodes.maxItems
MaxItemsInstallModes = $InstallerSchema.definitions.InstallModes.maxItems
PackageLocaleMaxLength = $LocaleSchema.properties.PackageLocale.maxLength
PublisherMaxLength = $LocaleSchema.properties.Publisher.maxLength
PackageNameMaxLength = $LocaleSchema.properties.PackageName.maxLength
MonikerMaxLength = $LocaleSchema.definitions.Tag.maxLength
GenericUrl = $LocaleSchema.definitions.Url.pattern
GenericUrlMaxLength = $LocaleSchema.definitions.Url.maxLength
AuthorMinLength = $LocaleSchema.properties.Author.minLength
AuthorMaxLength = $LocaleSchema.properties.Author.maxLength
LicenseMaxLength = $LocaleSchema.properties.License.maxLength
CopyrightMinLength = $LocaleSchema.properties.Copyright.minLength
CopyrightMaxLength = $LocaleSchema.properties.Copyright.maxLength
TagsMaxItems = $LocaleSchema.properties.Tags.maxItems
ShortDescriptionMaxLength = $LocaleSchema.properties.ShortDescription.maxLength
DescriptionMinLength = $LocaleSchema.properties.Description.minLength
DescriptionMaxLength = $LocaleSchema.properties.Description.maxLength
ValidInstallModes = $InstallerSchema.definitions.InstallModes.items.enum
FileExtension = $InstallerSchema.definitions.FileExtensions.items.pattern
FileExtensionMaxLength = $InstallerSchema.definitions.FileExtensions.items.maxLength
ReleaseNotesMinLength = $LocaleSchema.properties.ReleaseNotes.MinLength
ReleaseNotesMaxLength = $LocaleSchema.properties.ReleaseNotes.MaxLength
}
# This function validates whether a string matches Minimum Length, Maximum Length, and Regex pattern
# The switches can be used to specify if null values are allowed regardless of validation
Function Test-String {
Param
(
[Parameter(Mandatory = $true, Position = 0)]
[AllowEmptyString()]
[string] $InputString,
[Parameter(Mandatory = $false)]
[regex] $MatchPattern,
[Parameter(Mandatory = $false)]
[int] $MinLength,
[Parameter(Mandatory = $false)]
[int] $MaxLength,
[switch] $AllowNull,
[switch] $NotNull,
[switch] $IsNull,
[switch] $Not
)
$_isValid = $true
if ($PSBoundParameters.ContainsKey('MinLength')) {
$_isValid = $_isValid -and ($InputString.Length -ge $MinLength)
}
if ($PSBoundParameters.ContainsKey('MaxLength')) {
$_isValid = $_isValid -and ($InputString.Length -le $MaxLength)
}
if ($PSBoundParameters.ContainsKey('MatchPattern')) {
$_isValid = $_isValid -and ($InputString -match $MatchPattern)
}
if ($AllowNull -and [string]::IsNullOrWhiteSpace($InputString)) {
$_isValid = $true
} elseif ($NotNull -and [string]::IsNullOrWhiteSpace($InputString)) {
$_isValid = $false
}
if ($IsNull) {
$_isValid = [string]::IsNullOrWhiteSpace($InputString)
}
if ($Not) {
return !$_isValid
} else {
return $_isValid
}
}
# Takes an array of strings and an array of colors then writes one line of text composed of each string being its respective color
Function Write-MulticolorLine {
Param
(
[Parameter(Mandatory = $true, Position = 0)]
[string[]] $TextStrings,
[Parameter(Mandatory = $true, Position = 1)]
[string[]] $Colors
)
If ($TextStrings.Count -ne $Colors.Count) {
throw [System.ArgumentException]::new('Invalid Function Parameters. Arguments must be of equal length')
}
$_index = 0
Foreach ($String in $TextStrings) {
Write-Host -ForegroundColor $Colors[$_index] -NoNewline $String
$_index++
}
}
# Custom menu prompt that listens for keypresses. Requires a prompt and array of entries at minimum. Entries preceeded with `*` are shown in green
# Returns a console key value
Function Invoke-KeypressMenu {
Param
(
[Parameter(Mandatory = $true, Position = 0)]
[string] $Prompt,
[Parameter(Mandatory = $true, Position = 1)]
[string[]] $Entries,
[Parameter(Mandatory = $false)]
[string] $HelpText,
[Parameter(Mandatory = $false)]
[string] $HelpTextColor,
[Parameter(Mandatory = $false)]
[string] $DefaultString
)
Write-Host "`n"
Write-Host -ForegroundColor 'Yellow' "$Prompt"
if ($PSBoundParameters.ContainsKey('HelpText') -and (![string]::IsNullOrWhiteSpace($HelpText))) {
if ($PSBoundParameters.ContainsKey('HelpTextColor') -and (![string]::IsNullOrWhiteSpace($HelpTextColor))) {
Write-Host -ForegroundColor $HelpTextColor $HelpText
} else {
Write-Host -ForegroundColor 'Blue' $HelpText
}
}
foreach ($entry in $Entries) {
$_isDefault = $entry.StartsWith('*')
if ($_isDefault) {
$_entry = ' ' + $entry.Substring(1)
$_color = 'Green'
} else {
$_entry = ' ' + $entry
$_color = 'White'
}
Write-Host -ForegroundColor $_color $_entry
}
Write-Host
if ($PSBoundParameters.ContainsKey('DefaultString') -and (![string]::IsNullOrWhiteSpace($DefaultString))) {
Write-Host -NoNewline "Enter Choice (default is '$DefaultString'): "
} else {
Write-Host -NoNewline 'Enter Choice ('
Write-Host -NoNewline -ForegroundColor 'Green' 'Green'
Write-Host -NoNewline ' is default): '
}
do {
$keyInfo = [Console]::ReadKey($false)
} until ($keyInfo.Key)
return $keyInfo.Key
}
# Checks a URL and returns the status code received from the URL
Function Test-Url {
Param
(
[Parameter(Mandatory = $true, Position = 0)]
[string] $URL
)
try {
$HTTP_Request = [System.Net.WebRequest]::Create($URL)
$HTTP_Request.UserAgent = 'Microsoft-Delivery-Optimization/10.1'
$HTTP_Response = $HTTP_Request.GetResponse()
$script:ResponseUri = $HTTP_Response.ResponseUri.AbsoluteUri
$HTTP_Status = [int]$HTTP_Response.StatusCode
} catch {
# Take no action here; If there is an exception, we will treat it like a 404
$HTTP_Status = 404
}
If ($null -eq $HTTP_Response) { $HTTP_Status = 404 }
Else { $HTTP_Response.Close() }
return $HTTP_Status
}
# Checks a file name for validity and returns a boolean value
Function Test-ValidFileName {
param([string]$FileName)
$IndexOfInvalidChar = $FileName.IndexOfAny([System.IO.Path]::GetInvalidFileNameChars())
# IndexOfAny() returns the value -1 to indicate no such character was found
return $IndexOfInvalidChar -eq -1
}
# Prompts user to enter an Installer URL, Tests the URL to ensure it results in a response code of 200, validates it against the manifest schema
# Returns the validated URL which was entered
Function Request-InstallerUrl {
do {
Write-Host -ForegroundColor $(if ($script:_returnValue.Severity -gt 1) { 'red' } else { 'yellow' }) $script:_returnValue.ErrorString()
if ($script:_returnValue.StatusCode -ne 409) {
Write-Host -ForegroundColor 'Green' -Object '[Required] Enter the download url to the installer.'
$NewInstallerUrl = Read-Host -Prompt 'Url' | TrimString
}
$script:_returnValue = [ReturnValue]::GenericError()
if ((Test-Url $NewInstallerUrl) -ne 200) {
$script:_returnValue = [ReturnValue]::new(502, 'Invalid URL Response', 'The URL did not return a successful response from the server', 2)
} else {
if (($script:ResponseUri -ne $NewInstallerUrl) -and ($ScriptSettings.UseRedirectedURL -ne 'never') -and ($NewInstallerUrl -notmatch 'github')) {
#If urls don't match, ask to update; If they do update, set custom error and check for validity;
$_menu = @{
entries = @('*[Y] Use detected URL'; '[N] Use original URL')
Prompt = 'The URL provided appears to be redirected. Would you like to use the destination URL instead?'
HelpText = "Discovered URL: $($script:ResponseUri)"
DefaultString = 'Y'
}
switch ($(if ($ScriptSettings.UseRedirectedURL -eq 'always') { 'Y' } else { Invoke-KeypressMenu -Prompt $_menu['Prompt'] -Entries $_menu['Entries'] -DefaultString $_menu['DefaultString'] -HelpText $_menu['HelpText'] })) {
'N' { Write-Host -ForegroundColor 'Green' "`nOriginal URL Retained - Proceeding with $NewInstallerUrl`n" } #Continue without replacing URL
default {
$NewInstallerUrl = $script:ResponseUri
$script:_returnValue = [ReturnValue]::new(409, 'URL Changed', 'The URL was changed during processing and will be re-validated', 1)
Write-Host
}
}
}
if ($script:_returnValue.StatusCode -ne 409) {
if (Test-String $NewInstallerUrl -MaxLength $Patterns.InstallerUrlMaxLength -MatchPattern $Patterns.InstallerUrl -NotNull) {
$script:_returnValue = [ReturnValue]::Success()
} else {
if (Test-String -not $NewInstallerUrl -MaxLength $Patterns.InstallerUrlMaxLength -NotNull) {
$script:_returnValue = [ReturnValue]::LengthError(1, $Patterns.InstallerUrlMaxLength)
} elseif (Test-String -not $NewInstallerUrl -MatchPattern $Patterns.InstallerUrl) {
$script:_returnValue = [ReturnValue]::PatternError()
} else {
$script:_returnValue = [ReturnValue]::GenericError()
}
}
}
}
} until ($script:_returnValue.StatusCode -eq [ReturnValue]::Success().StatusCode)
return $NewInstallerUrl
}
Function Get-InstallerFile {
Param
(
[Parameter(Mandatory = $true, Position = 0)]
[string] $URI,
[Parameter(Mandatory = $true, Position = 1)]
[string] $PackageIdentifier,
[Parameter(Mandatory = $true, Position = 2)]
[string] $PackageVersion
)
# Create a filename based on the Package Identifier and Version; Try to get the extension from the URL
# If the extension isn't found, use a custom one
$_URIPath = $URI.Split('?')[0]
$_Filename = "$PackageIdentifier v$PackageVersion - $(Get-Date -f 'yyyy.MM.dd-hh.mm.ss')" + $(if ([System.IO.Path]::HasExtension($_URIPath)) { [System.IO.Path]::GetExtension($_URIPath) } else { '.winget-tmp' })
if (Test-ValidFileName $_Filename) { $_OutFile = Join-Path -Path $env:TEMP -ChildPath $_Filename }
else { $_OutFile = (New-TemporaryFile).FullName }
# Create a new web client for downloading the file
$_WebClient = [System.Net.WebClient]::new()
$_WebClient.Headers.Add('User-Agent', 'Microsoft-Delivery-Optimization/10.1')
# If the system has a default proxy set, use it
# Powershell Core will automatically use this, so it's only necessary for PS5
if ($PSVersionTable.PSVersion.Major -lt 6) { $_WebClient.Proxy = [System.Net.WebProxy]::GetDefaultProxy() }
# Download the file
$_WebClient.DownloadFile($URI, $_OutFile)
# Dispose of the web client to release the resources it uses
$_WebClient.Dispose()
return $_OutFile
}
Function Get-MSIProperty {
Param
(
[Parameter(Mandatory = $true)]
[string] $MSIPath,
[Parameter(Mandatory = $true)]
[string] $Parameter
)
try {
$windowsInstaller = New-Object -com WindowsInstaller.Installer
$database = $windowsInstaller.GetType().InvokeMember('OpenDatabase', 'InvokeMethod', $null, $windowsInstaller, @($MSIPath, 0))
$view = $database.GetType().InvokeMember('OpenView', 'InvokeMethod', $null, $database, ("SELECT Value FROM Property WHERE Property = '$Parameter'"))
$view.GetType().InvokeMember('Execute', 'InvokeMethod', $null, $view, $null)
$record = $view.GetType().InvokeMember('Fetch', 'InvokeMethod', $null, $view, $null)
$outputObject = $($record.GetType().InvokeMember('StringData', 'GetProperty', $null, $record, 1))
$view.GetType().InvokeMember('Close', 'InvokeMethod', $null, $view, $null)
[System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($view)
[System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($database)
[System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($windowsInstaller)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
return $outputObject
} catch {
Write-Error -Message $_.ToString()
break
}
}
Function Get-ItemMetadata {
Param
(
[Parameter(Mandatory = $true)]
[string] $FilePath
)
try {
$MetaDataObject = [ordered] @{}
$FileInformation = (Get-Item $FilePath)
$ShellApplication = New-Object -ComObject Shell.Application
$ShellFolder = $ShellApplication.Namespace($FileInformation.Directory.FullName)
$ShellFile = $ShellFolder.ParseName($FileInformation.Name)
$MetaDataProperties = [ordered] @{}
0..400 | ForEach-Object -Process {
$DataValue = $ShellFolder.GetDetailsOf($null, $_)
$PropertyValue = (Get-Culture).TextInfo.ToTitleCase($DataValue.Trim()).Replace(' ', '')
if ($PropertyValue -ne '') {
$MetaDataProperties["$_"] = $PropertyValue
}
}
foreach ($Key in $MetaDataProperties.Keys) {
$Property = $MetaDataProperties[$Key]
$Value = $ShellFolder.GetDetailsOf($ShellFile, [int] $Key)
if ($Property -in 'Attributes', 'Folder', 'Type', 'SpaceFree', 'TotalSize', 'SpaceUsed') {
continue
}
If (($null -ne $Value) -and ($Value -ne '')) {
$MetaDataObject["$Property"] = $Value
}
}
[void][System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($ShellFile)
[void][System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($ShellFolder)
[void][System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($ShellApplication)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
return $MetaDataObject
} catch {
Write-Error -Message $_.ToString()
break
}
}
function Get-Property ($Object, $PropertyName, [object[]]$ArgumentList) {
return $Object.GetType().InvokeMember($PropertyName, 'Public, Instance, GetProperty', $null, $Object, $ArgumentList)
}
Function Get-MsiDatabase {
Param
(
[Parameter(Mandatory = $true)]
[string] $FilePath
)
Write-Host -ForegroundColor 'Yellow' 'Reading Installer Database. This may take some time. . .'
$windowsInstaller = New-Object -com WindowsInstaller.Installer
$MSI = $windowsInstaller.OpenDatabase($FilePath, 0)
$_TablesView = $MSI.OpenView('select * from _Tables')
$_TablesView.Execute()
$_Database = @{}
do {
$_Table = $_TablesView.Fetch()
if ($_Table) {
$_TableName = Get-Property $_Table StringData 1
$_Database["$_TableName"] = @{}
}
} while ($_Table)
[void][System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($_TablesView)
foreach ($_Table in $_Database.Keys) {
# Write-Host $_Table
$_ItemView = $MSI.OpenView("select * from $_Table")
$_ItemView.Execute()
do {
$_Item = $_ItemView.Fetch()
if ($_Item) {
$_ItemValue = $null
$_ItemName = Get-Property $_Item StringData 1
if ($_Table -eq 'Property') { $_ItemValue = Get-Property $_Item StringData 2 -ErrorAction SilentlyContinue }
$_Database.$_Table["$_ItemName"] = $_ItemValue
}
} while ($_Item)
[void][System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($_ItemView)
}
[void][System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($MSI)
[void][System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($windowsInstaller)
Write-Host -ForegroundColor 'Yellow' 'Closing Installer Database. . .'
return $_Database
}
Function Test-IsWix {
Param
(
[Parameter(Mandatory = $true)]
[object] $Database,
[Parameter(Mandatory = $true)]
[object] $MetaDataObject
)
# If any of the table names match wix
if ($Database.Keys -match 'wix') { return $true }
# If any of the keys in the property table match wix
if ($Database.Property.Keys.Where({ $_ -match 'wix' })) { return $true }
# If the CreatedBy value matches wix
if ($MetaDataObject.ProgramName -match 'wix') { return $true }
# If the CreatedBy value matches xml
if ($MetaDataObject.ProgramName -match 'xml') { return $true }
return $false
}
Function Get-UserSavePreference {
switch ($ScriptSettings.SaveToTemporaryFolder) {
'always' { $_Preference = '0' }
'never' { $_Preference = '1' }
'manual' { $_Preference = '2' }
default {
$_menu = @{
entries = @('[Y] Yes'; '*[N] No'; '[M] Manually Enter SHA256')
Prompt = 'Do you want to save the files to the Temp folder?'
DefaultString = 'N'
}
switch ( Invoke-KeypressMenu -Prompt $_menu['Prompt'] -Entries $_menu['Entries'] -DefaultString $_menu['DefaultString']) {
'Y' { $_Preference = '0' }
'N' { $_Preference = '1' }
'M' { $_Preference = '2' }
default { $_Preference = '1' }
}
}
}
return $_Preference
}
Function Get-PathInstallerType {
Param
(
[Parameter(Mandatory = $true, Position = 0)]
[string] $Path
)
if ($Path -match '\.msix(bundle){0,1}$') { return 'msix' }
if ($Path -match '\.msi$') {
$ObjectMetadata = Get-ItemMetadata $Path
$ObjectDatabase = Get-MsiDatabase $Path
if (Test-IsWix -Database $ObjectDatabase -MetaDataObject $ObjectMetadata ) {
return 'wix'
}
return 'msi'
}
if ($Path -match '\.appx(bundle){0,1}$') { return 'appx' }
if ($Path -match '\.zip$') { return 'zip' }
return $null
}
Function Get-UriArchitecture {
Param
(
[Parameter(Mandatory = $true, Position = 0)]
[string] $URI
)
if ($URI -match '\b(x|win){0,1}64\b') { return 'x64' }
if ($URI -match '\b((win|ia)32)|(x{0,1}86)\b') { return 'x86' }
if ($URI -match '\b(arm|aarch)64\b') { return 'arm64' }
if ($URI -match '\barm\b') { return 'arm' }
return $null
}
# Prompts the user to enter installer values
# Sets the $script:Installers value as an output
# Returns void
Function Read-InstallerEntry {
$_Installer = [ordered] @{}
# Request user enter Installer URL
$_Installer['InstallerUrl'] = Request-InstallerUrl
if ($_Installer.InstallerUrl -in ($script:Installers).InstallerUrl) {
$_MatchingInstaller = $script:Installers | Where-Object { $_.InstallerUrl -eq $_Installer.InstallerUrl } | Select-Object -First 1
if ($_MatchingInstaller.InstallerSha256) { $_Installer['InstallerSha256'] = $_MatchingInstaller.InstallerSha256 }
if ($_MatchingInstaller.InstallerType) { $_Installer['InstallerType'] = $_MatchingInstaller.InstallerType }
if ($_MatchingInstaller.ProductCode) { $_Installer['ProductCode'] = $_MatchingInstaller.ProductCode }
if ($_MatchingInstaller.PackageFamilyName) { $_Installer['PackageFamilyName'] = $_MatchingInstaller.PackageFamilyName }
if ($_MatchingInstaller.SignatureSha256) { $_Installer['SignatureSha256'] = $_MatchingInstaller.SignatureSha256 }
}
# Get or request Installer Sha256
# Check the settings to see if we need to display this menu
if ($_Installer.Keys -notcontains 'InstallerSha256') {
$script:SaveOption = Get-UserSavePreference
# If user did not select manual entry for Sha256, download file and calculate hash
# Also attempt to detect installer type and architecture
if ($script:SaveOption -ne '2') {
Write-Host
$start_time = Get-Date
Write-Host $NewLine
Write-Host 'Downloading URL. This will take a while...' -ForegroundColor Blue
try {
$script:dest = Get-InstallerFile -URI $_Installer['InstallerUrl'] -PackageIdentifier $PackageIdentifier -PackageVersion $PackageVersion
} catch {
# Here we also want to pass any exceptions through for potential debugging
throw [System.Net.WebException]::new('The file could not be downloaded. Try running the script again', $_.Exception)
} finally {
Write-Host "Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)" -ForegroundColor Green
$_Installer['InstallerSha256'] = (Get-FileHash -Path $script:dest -Algorithm SHA256).Hash
Get-PathInstallerType -Path $script:dest -OutVariable _ | Out-Null
if ($_) { $_Installer['InstallerType'] = $_ | Select-Object -First 1 }
Get-UriArchitecture -URI $_Installer['InstallerUrl'] -OutVariable _ | Out-Null
if ($_) { $_Installer['Architecture'] = $_ | Select-Object -First 1 }
if ([System.Environment]::OSVersion.Platform -match 'Win' -and ($script:dest).EndsWith('.msi')) {
$ProductCode = ([string](Get-MSIProperty -MSIPath $script:dest -Parameter 'ProductCode') | Select-String -Pattern '{[A-Z0-9]{8}-([A-Z0-9]{4}-){3}[A-Z0-9]{12}}').Matches.Value
}
if (Test-String -Not "$ProductCode" -IsNull) { $_Installer['ProductCode'] = "$ProductCode" }
}
}
# Manual Entry of Sha256 with validation
else {
Write-Host
do {
Write-Host -ForegroundColor 'Red' $script:_returnValue.ErrorString()
Write-Host -ForegroundColor 'Green' -Object '[Required] Enter the installer SHA256 Hash'
$_Installer['InstallerSha256'] = Read-Host -Prompt 'InstallerSha256' | TrimString
$_Installer['InstallerSha256'] = $_Installer['InstallerSha256'].toUpper()
if ($_Installer['InstallerSha256'] -match $Patterns.InstallerSha256) {
$script:_returnValue = [ReturnValue]::Success()
} else {
$script:_returnValue = [ReturnValue]::PatternError()
}
} until ($script:_returnValue.StatusCode -eq [ReturnValue]::Success().StatusCode)
}
}
# Manual Entry of Architecture with validation
do {
Write-Host -ForegroundColor 'Red' $script:_returnValue.ErrorString()
if (Test-String $_Installer['Architecture'] -IsNull) { Write-Host -ForegroundColor 'Green' -Object '[Required] Enter the architecture. Options:' , @($Patterns.ValidArchitectures -join ', ') }
else {
Write-Host -ForegroundColor 'Yellow' -Object '[Optional] Enter the architecture. Options:' , @($Patterns.ValidArchitectures -join ', ')
Write-Host -ForegroundColor 'DarkGray' -Object "Old Variable: $($_Installer['Architecture'])"
}
Read-Host -Prompt 'Architecture' -OutVariable _ | Out-Null
if (Test-String $_ -Not -IsNull) { $_Installer['Architecture'] = $_ | TrimString }
if ($_Installer['Architecture'] -Cin @($Patterns.ValidArchitectures)) {
$script:_returnValue = [ReturnValue]::Success()
} else {
$script:_returnValue = [ReturnValue]::new(400, 'Invalid Architecture', "Value must exist in the enum - $(@($Patterns.ValidArchitectures -join ', '))", 2)
}
} until ($script:_returnValue.StatusCode -eq [ReturnValue]::Success().StatusCode)
# Manual Entry of Installer Type with validation
if ($_Installer['InstallerType'] -CNotIn @($Patterns.ValidInstallerTypes)) {
do {
Write-Host -ForegroundColor 'Red' $script:_returnValue.ErrorString()
Write-Host -ForegroundColor 'Green' -Object '[Required] Enter the InstallerType. Options:' , @($Patterns.ValidInstallerTypes -join ', ' )
$_Installer['InstallerType'] = Read-Host -Prompt 'InstallerType' | TrimString
if ($_Installer['InstallerType'] -Cin @($Patterns.ValidInstallerTypes)) {
$script:_returnValue = [ReturnValue]::Success()
} else {
$script:_returnValue = [ReturnValue]::new(400, 'Invalid Installer Type', "Value must exist in the enum - $(@($Patterns.ValidInstallerTypes -join ', '))", 2)
}
} until ($script:_returnValue.StatusCode -eq [ReturnValue]::Success().StatusCode)
}
$_Switches = [ordered] @{}
# If Installer Type is `exe`, require the silent switches to be entered
do {
Write-Host -ForegroundColor 'Red' $script:_returnValue.ErrorString()
if ($_Installer['InstallerType'] -ieq 'exe') { Write-Host -ForegroundColor 'Green' -Object '[Required] Enter the silent install switch. For example: /S, -verysilent, /qn, --silent, /exenoui' }
else { Write-Host -ForegroundColor 'Yellow' -Object '[Optional] Enter the silent install switch. For example: /S, -verysilent, /qn, --silent, /exenoui' }
Read-Host -Prompt 'Silent switch' -OutVariable _ | Out-Null
if ($_) { $_Switches['Silent'] = $_ | TrimString }
if (Test-String $_Switches['Silent'] -MaxLength $Patterns.SilentSwitchMaxLength -NotNull) {
$script:_returnValue = [ReturnValue]::Success()
} elseif ($_Installer['InstallerType'] -ne 'exe' -and (Test-String $_Switches['Silent'] -MaxLength $Patterns.SilentSwitchMaxLength -AllowNull)) {
$script:_returnValue = [ReturnValue]::Success()
} else {
$script:_returnValue = [ReturnValue]::LengthError(1, $Patterns.SilentSwitchMaxLength)
}
} until ($script:_returnValue.StatusCode -eq [ReturnValue]::Success().StatusCode)
do {
Write-Host -ForegroundColor 'Red' $script:_returnValue.ErrorString()
if ($_Installer['InstallerType'] -ieq 'exe') { Write-Host -ForegroundColor 'Green' -Object '[Required] Enter the silent with progress install switch. For example: /S, -silent, /qb, /exebasicui' }
else { Write-Host -ForegroundColor 'Yellow' -Object '[Optional] Enter the silent with progress install switch. For example: /S, -silent, /qb, /exebasicui' }
Read-Host -Prompt 'Silent with progress switch' -OutVariable _ | Out-Null
if ($_) { $_Switches['SilentWithProgress'] = $_ | TrimString }
if (Test-String $_Switches['SilentWithProgress'] -MaxLength $Patterns.ProgressSwitchMaxLength -NotNull) {
$script:_returnValue = [ReturnValue]::Success()
} elseif ($_Installer['InstallerType'] -ne 'exe' -and (Test-String $_Switches['SilentWithProgress'] -MaxLength $Patterns.ProgressSwitchMaxLength -AllowNull)) {
$script:_returnValue = [ReturnValue]::Success()
} else {
$script:_returnValue = [ReturnValue]::LengthError(1, $Patterns.ProgressSwitchMaxLength)
}
} until ($script:_returnValue.StatusCode -eq [ReturnValue]::Success().StatusCode)
# Optional entry of `Custom` switches with validation for all installer types
do {
Write-Host -ForegroundColor 'Red' $script:_returnValue.ErrorString()
Write-Host -ForegroundColor 'Yellow' -Object '[Optional] Enter any custom switches for the installer. For example: /norestart, -norestart'
Read-Host -Prompt 'Custom Switch' -OutVariable _ | Out-Null
if ($_) { $_Switches['Custom'] = $_ | TrimString }
if (Test-String $_Switches['Custom'] -MaxLength $Patterns.CustomSwitchMaxLength -AllowNull) {
$script:_returnValue = [ReturnValue]::Success()
} else {
$script:_returnValue = [ReturnValue]::LengthError(1, $Patterns.CustomSwitchMaxLength)
}
} until ($script:_returnValue.StatusCode -eq [ReturnValue]::Success().StatusCode)
if ($_Switches.Keys.Count -gt 0) { $_Installer['InstallerSwitches'] = $_Switches }
# If the installer is `msix` or `appx`, prompt for or detect additional fields
if ($_Installer['InstallerType'] -in @('msix'; 'appx')) {
# Detect or prompt for Signature Sha256
if (Get-Command 'winget.exe' -ErrorAction SilentlyContinue) { $SignatureSha256 = winget hash -m $script:dest | Select-String -Pattern 'SignatureSha256:' | ConvertFrom-String; if ($SignatureSha256.P2) { $SignatureSha256 = $SignatureSha256.P2.ToUpper() } }
if ($SignatureSha256) { $_Installer['SignatureSha256'] = $SignatureSha256 }
if (Test-String $_Installer['SignatureSha256'] -IsNull) {
# Manual entry of Signature Sha256 with validation
do {
Write-Host -ForegroundColor 'Red' $script:_returnValue.ErrorString()
Write-Host -ForegroundColor 'Yellow' -Object '[Recommended] Enter the installer SignatureSha256'
Read-Host -Prompt 'SignatureSha256' -OutVariable _ | Out-Null
if ($_) { $_Installer['SignatureSha256'] = $_ | TrimString }
if (Test-String $_Installer['SignatureSha256'] -MatchPattern $Patterns.SignatureSha256 -AllowNull) {
$script:_returnValue = [ReturnValue]::Success()
} else {
$script:_returnValue = [ReturnValue]::PatternError()
}
} until ($script:_returnValue.StatusCode -eq [ReturnValue]::Success().StatusCode)
}
# Prompt user to find package name automatically, unless package was not downloaded
if ($script:SaveOption -eq '2' -or (!$(Test-Path $script:dest))) {
$ChoicePfn = '1'
} else {
$_menu = @{
entries = @('*[F] Find Automatically [Note: This will install the package to find Family Name and then removes it.]'; '[M] Manually Enter PackageFamilyName')
Prompt = 'Discover the package family name?'
DefaultString = 'F'
}
switch ( Invoke-KeypressMenu -Prompt $_menu['Prompt'] -Entries $_menu['Entries'] -DefaultString $_menu['DefaultString']) {
'M' { $ChoicePfn = '1' }
default { $ChoicePfn = '0' }
}
}
# If user selected to find automatically -
# Install package, get family name, uninstall package
if ($ChoicePfn -eq '0') {
try {
Add-AppxPackage -Path $script:dest
$InstalledPkg = Get-AppxPackage | Select-Object -Last 1 | Select-Object PackageFamilyName, PackageFullName
if ($InstalledPkg.PackageFamilyName) { $_Installer['PackageFamilyName'] = $InstalledPkg.PackageFamilyName }
Remove-AppxPackage $InstalledPkg.PackageFullName
} catch {
# Take no action here, we just want to catch the exceptions as a precaution
Out-Null
} finally {
if (Test-String $_Installer['PackageFamilyName'] -IsNull) {
$script:_returnValue = [ReturnValue]::new(500, 'Could not find PackageFamilyName', 'Value should be entered manually', 1)
}
}
}
# Validate Package Family Name if found automatically
# Allow for manual entry if selected or if validation failed
do {
if (($ChoicePfn -ne '0') -or ($script:_returnValue.StatusCode -ne [ReturnValue]::Success().StatusCode)) {
Write-Host -ForegroundColor 'Red' $script:_returnValue.ErrorString()
Write-Host -ForegroundColor 'Yellow' -Object '[Recommended] Enter the PackageFamilyName'
Read-Host -Prompt 'PackageFamilyName' -OutVariable _ | Out-Null
if ($_) { $_Installer['PackageFamilyName'] = $_ | TrimString }
}
if (Test-String $_Installer['PackageFamilyName'] -MaxLength $Patterns.FamilyNameMaxLength -MatchPattern $Patterns.FamilyName -AllowNull) {
if (Test-String $_Installer['PackageFamilyName'] -IsNull) { $_Installer['PackageFamilyName'] = "$([char]0x2370)" }
$script:_returnValue = [ReturnValue]::Success()
} else {
if (Test-String -not $_Installer['PackageFamilyName'] -MaxLength $Patterns.FamilyNameMaxLength) {
$script:_returnValue = [ReturnValue]::LengthError(1, $Patterns.FamilyNameMaxLength)
} elseif (Test-String -not $_Installer['PackageFamilyName'] -MatchPattern $Patterns.FamilyName) {
$script:_returnValue = [ReturnValue]::PatternError()
} else {
$script:_returnValue = [ReturnValue]::GenericError()
}
}
} until ($script:_returnValue.StatusCode -eq [ReturnValue]::Success().StatusCode)
}
# Request installer locale with validation as optional
do {
Write-Host -ForegroundColor 'Red' $script:_returnValue.ErrorString()
Write-Host -ForegroundColor 'Yellow' -Object '[Optional] Enter the installer locale. For example: en-US, en-CA'
Write-Host -ForegroundColor 'Blue' -Object 'https://docs.microsoft.com/openspecs/office_standards/ms-oe376/6c085406-a698-4e12-9d4d-c3b0ee3dbc4a'
Read-Host -Prompt 'InstallerLocale' -OutVariable _
if ($_) { $_Installer['InstallerLocale'] = $_ | TrimString }
# If user defined a default locale, add it
if ((Test-String $_Installer['InstallerLocale'] -IsNull) -and (Test-String -not $ScriptSettings.DefaultInstallerLocale -IsNull)) { $_Installer['InstallerLocale'] = $ScriptSettings.DefaultInstallerLocale }
if (Test-String $_Installer['InstallerLocale'] -MaxLength $Patterns.InstallerLocaleMaxLength -MatchPattern $Patterns.PackageLocale -AllowNull) {
$script:_returnValue = [ReturnValue]::Success()
} else {
if (Test-String -not $_Installer['InstallerLocale'] -MaxLength $Patterns.InstallerLocaleMaxLength -AllowNull) {
$script:_returnValue = [ReturnValue]::LengthError(0, $Patterns.InstallerLocaleMaxLength)
} elseif (Test-String -not $_Installer['InstallerLocale'] -MatchPattern $Patterns.PackageLocale) {
$script:_returnValue = [ReturnValue]::PatternError()
} else {
$script:_returnValue = [ReturnValue]::GenericError()
}
}
} until ($script:_returnValue.StatusCode -eq [ReturnValue]::Success().StatusCode)
# Request product code with validation
do {
Write-Host -ForegroundColor 'Red' $script:_returnValue.ErrorString()
Write-Host -ForegroundColor 'Yellow' -Object '[Optional] Enter the application product code. Looks like {CF8E6E00-9C03-4440-81C0-21FACB921A6B}'
Write-Host -ForegroundColor 'White' -Object "ProductCode found from installer: $($_Installer['ProductCode'])"
Write-Host -ForegroundColor 'White' -Object 'Can be found with ' -NoNewline; Write-Host -ForegroundColor 'DarkYellow' 'get-wmiobject Win32_Product | Sort-Object Name | Format-Table IdentifyingNumber, Name -AutoSize'
$NewProductCode = Read-Host -Prompt 'ProductCode' | TrimString
if (Test-String $NewProductCode -Not -IsNull) { $_Installer['ProductCode'] = $NewProductCode }
elseif (Test-String $_Installer['ProductCode'] -Not -IsNull) { $_Installer['ProductCode'] = "$($_Installer['ProductCode'])" }
if (Test-String $_Installer['ProductCode'] -MinLength $Patterns.ProductCodeMinLength -MaxLength $Patterns.ProductCodeMaxLength -AllowNull) {
$script:_returnValue = [ReturnValue]::Success()
} else {
$script:_returnValue = [ReturnValue]::LengthError($Patterns.ProductCodeMinLength, $Patterns.ProductCodeMaxLength)
}
} until ($script:_returnValue.StatusCode -eq [ReturnValue]::Success().StatusCode)
# Request installer scope
$_menu = @{
entries = @('[M] Machine'; '[U] User'; '*[N] No idea')
Prompt = '[Optional] Enter the Installer Scope'
DefaultString = 'N'
}
switch ( Invoke-KeypressMenu -Prompt $_menu['Prompt'] -Entries $_menu['Entries'] -DefaultString $_menu['DefaultString']) {
'M' { $_Installer['Scope'] = 'machine' }
'U' { $_Installer['Scope'] = 'user' }
default { }
}
# Request upgrade behavior
$_menu = @{
entries = @('*[I] Install'; '[U] Uninstall Previous')
Prompt = '[Optional] Enter the Upgrade Behavior'
DefaultString = 'I'
}
switch ( Invoke-KeypressMenu -Prompt $_menu['Prompt'] -Entries $_menu['Entries'] -DefaultString $_menu['DefaultString']) {
'U' { $_Installer['UpgradeBehavior'] = 'uninstallPrevious' }
default { $_Installer['UpgradeBehavior'] = 'install' }
}
Write-Host
# Request release date
$script:ReleaseDatePrompted = $true
do {
Write-Host -ForegroundColor 'Red' $script:_returnValue.ErrorString()
Write-Host -ForegroundColor 'Yellow' -Object '[Optional] Enter the application release date. Example: 2021-11-17'
Read-Host -Prompt 'ReleaseDate' -OutVariable ReleaseDate | Out-Null
try {
Get-Date([datetime]$($ReleaseDate | TrimString)) -f 'yyyy-MM-dd' -OutVariable _ValidDate | Out-Null
if ($_ValidDate) { $_Installer['ReleaseDate'] = $_ValidDate | TrimString }
$script:_returnValue = [ReturnValue]::Success()
} catch {
if (Test-String $ReleaseDate -IsNull) {
$script:_returnValue = [ReturnValue]::Success()
} else {
$script:_returnValue = [ReturnValue]::new(400, 'Invalid Date', 'Input could not be resolved to a date', 2)
}
}
} until ($script:_returnValue.StatusCode -eq [ReturnValue]::Success().StatusCode)
if ($script:SaveOption -eq '1' -and (Test-Path -Path $script:dest)) { Remove-Item -Path $script:dest }
# If the installers array is empty, create it
if (!$script:Installers) {
$script:Installers = @()
}
# Add the completed installer to the installers array
$_Installer = Restore-YamlKeyOrder $_Installer $InstallerEntryProperties -NoComments
$script:Installers += $_Installer
# Prompt the user for additional intaller entries
$_menu = @{
entries = @(
'[Y] Yes'
'*[N] No'
)
Prompt = 'Do you want to create another installer?'
DefaultString = 'N'
}
switch ( Invoke-KeypressMenu -Prompt $_menu['Prompt'] -Entries $_menu['Entries'] -DefaultString $_menu['DefaultString']) {
'Y' { $AnotherInstaller = '0' }
'N' { $AnotherInstaller = '1' }
default { $AnotherInstaller = '1' }
}
# If there are additional entries, run this function again to fetch the values and add them to the installers array
if ($AnotherInstaller -eq '0') {
Write-Host; Read-InstallerEntry
}
}
# Prompts user for Installer Values using the `Quick Update` Method
# Sets the $script:Installers value as an output
# Returns void
Function Read-QuickInstallerEntry {
# We know old manifests exist if we got here without error
# Fetch the old installers based on the manifest type
if ($script:OldInstallerManifest) { $_OldInstallers = $script:OldInstallerManifest['Installers'] } else {
$_OldInstallers = $script:OldVersionManifest['Installers']
}
$_iteration = 0
$_NewInstallers = @()
foreach ($_OldInstaller in $_OldInstallers) {
# Create the new installer as an exact copy of the old installer entry
# This is to ensure all previously entered and un-modified parameters are retained
$_iteration += 1
$_NewInstaller = $_OldInstaller
$_NewInstaller.Remove('InstallerSha256');
# Show the user which installer entry they should be entering information for
Write-Host -ForegroundColor 'Green' "Installer Entry #$_iteration`:`n"
if ($_OldInstaller.InstallerLocale) { Write-Host -ForegroundColor 'Yellow' "`tInstallerLocale: $($_OldInstaller.InstallerLocale)" }
if ($_OldInstaller.Architecture) { Write-Host -ForegroundColor 'Yellow' "`tArchitecture: $($_OldInstaller.Architecture)" }
if ($_OldInstaller.InstallerType) { Write-Host -ForegroundColor 'Yellow' "`tInstallerType: $($_OldInstaller.InstallerType)" }
if ($_OldInstaller.Scope) { Write-Host -ForegroundColor 'Yellow' "`tScope: $($_OldInstaller.Scope)" }
Write-Host
# Request user enter the new Installer URL
$_NewInstaller['InstallerUrl'] = Request-InstallerUrl
if ($_NewInstaller.InstallerUrl -in ($_NewInstallers).InstallerUrl) {
$_MatchingInstaller = $_NewInstallers | Where-Object { $_.InstallerUrl -eq $_NewInstaller.InstallerUrl } | Select-Object -First 1
if ($_MatchingInstaller.InstallerSha256) { $_NewInstaller['InstallerSha256'] = $_MatchingInstaller.InstallerSha256 }
if ($_MatchingInstaller.InstallerType) { $_NewInstaller['InstallerType'] = $_MatchingInstaller.InstallerType }
if ($_MatchingInstaller.ProductCode) { $_NewInstaller['ProductCode'] = $_MatchingInstaller.ProductCode }
elseif ( ($_NewInstaller.Keys -contains 'ProductCode') -and ($script:dest -notmatch '.exe$')) { $_NewInstaller.Remove('ProductCode') }
if ($_MatchingInstaller.PackageFamilyName) { $_NewInstaller['PackageFamilyName'] = $_MatchingInstaller.PackageFamilyName }
elseif ($_NewInstaller.Keys -contains 'PackageFamilyName') { $_NewInstaller.Remove('PackageFamilyName') }
if ($_MatchingInstaller.SignatureSha256) { $_NewInstaller['SignatureSha256'] = $_MatchingInstaller.SignatureSha256 }
elseif ($_NewInstaller.Keys -contains 'SignatureSha256') { $_NewInstaller.Remove('SignatureSha256') }
}
if ($_NewInstaller.Keys -notcontains 'InstallerSha256') {
try {
Write-Host -ForegroundColor 'Green' 'Downloading Installer. . .'
$script:dest = Get-InstallerFile -URI $_NewInstaller['InstallerUrl'] -PackageIdentifier $PackageIdentifier -PackageVersion $PackageVersion
} catch {
# Here we also want to pass any exceptions through for potential debugging
throw [System.Net.WebException]::new('The file could not be downloaded. Try running the script again', $_.Exception)
} finally {
# Check that MSI's aren't actually WIX
Write-Host -ForegroundColor 'Green' "Installer Downloaded!`nProcessing installer data. . . "
if ($_NewInstaller['InstallerType'] -eq 'msi') {
$DetectedType = Get-PathInstallerType $script:dest
if ($DetectedType -in @('msi'; 'wix')) { $_NewInstaller['InstallerType'] = $DetectedType }
}
# Get the Sha256
$_NewInstaller['InstallerSha256'] = (Get-FileHash -Path $script:dest -Algorithm SHA256).Hash
# Update the product code, if a new one exists
# If a new product code doesn't exist, and the installer isn't an `.exe` file, remove the product code if it exists
$MSIProductCode = $null
if ([System.Environment]::OSVersion.Platform -match 'Win' -and ($script:dest).EndsWith('.msi')) {