-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
YamlCreate.ps1
3407 lines (3129 loc) · 165 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
<#
.SYNOPSIS
WinGet Manifest creation helper script
.DESCRIPTION
This file intends 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 into
a set of .YAML files.
.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
#>
#Requires -Version 5
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Justification = 'This script is not intended to have any outputs piped')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', 'Preserve', Justification = 'The variable is used in a conditional but ScriptAnalyser does not recognize the scope')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Scope = 'Function', Target = 'Read-AppsAndFeaturesEntries',
Justification = 'Ths function is a wrapper which calls the singular Read-AppsAndFeaturesEntry as many times as necessary. It corresponds exactly to a pluralized manifest field')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Scope = 'Function', Target = '*Metadata',
Justification = 'Metadata is used as a mass noun and is therefore singular in the cases used in this script')]
Param
(
[switch] $Settings,
[switch] $AutoUpgrade,
[switch] $help,
[switch] $SkipPRCheck,
[switch] $Preserve,
[Parameter(Mandatory = $false)]
[string] $PackageIdentifier,
[Parameter(Mandatory = $false)]
[string] $PackageVersion,
[Parameter(Mandatory = $false)]
[string] $Mode
)
$ProgressPreference = 'SilentlyContinue'
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
}
# Custom menu prompt that listens for key presses. 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,
[Parameter(Mandatory = $false)]
[string[]] $AllowedCharacters
)
if (!$PSBoundParameters.ContainsKey('AllowedCharacters')) {
$AllowedCharacters = @($Entries.TrimStart('*').Chars(1))
}
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)
if ($keyInfo.KeyChar -notin $AllowedCharacters -and $ScriptSettings.ExplicitMenuOptions -eq $true -and $AllowedCharacters.Length -gt 0) {
if ($keyInfo.Key -eq 'Enter') { Write-Host }
$keyInfo = $null
}
} until ($keyInfo.Key)
return $keyInfo.Key
}
#If the user has git installed, make sure it is a patched version
if (Get-Command 'git' -ErrorAction SilentlyContinue) {
$GitMinimumVersion = [System.Version]::Parse('2.39.1')
$gitVersionString = ((git version) | Select-String '([0-9]{1,}\.?){3,}').Matches.Value.Trim(' ', '.')
$gitVersion = [System.Version]::Parse($gitVersionString)
if ($gitVersion -lt $GitMinimumVersion) {
# Prompt user to install git
if (Get-Command 'winget' -ErrorAction SilentlyContinue) {
$_menu = @{
entries = @('[Y] Upgrade Git'; '*[N] Do not upgrade')
Prompt = 'The version of git installed on your machine does not satisfy the requirement of version >= 2.39.1; Would you like to upgrade?'
HelpText = "Upgrading will attempt to upgrade git using winget`n"
DefaultString = ''
}
switch (Invoke-KeypressMenu -Prompt $_menu['Prompt'] -Entries $_menu['Entries'] -DefaultString $_menu['DefaultString'] -HelpText $_menu['HelpText']) {
'Y' {
Write-Host
try {
winget upgrade --id Git.Git --exact
} catch {
throw [UnmetDependencyException]::new('Git could not be upgraded sucessfully', $_)
} finally {
$gitVersionString = ((git version) | Select-String '([0-9]{1,}\.?){3,}').Matches.Value.Trim(' ', '.')
$gitVersion = [System.Version]::Parse($gitVersionString)
if ($gitVersion -lt $GitMinimumVersion) {
throw [UnmetDependencyException]::new('Git could not be upgraded sucessfully')
}
}
}
default { Write-Host; throw [UnmetDependencyException]::new('The version of git installed on your machine does not satisfy the requirement of version >= 2.39.1') }
}
} else {
throw [UnmetDependencyException]::new('The version of git installed on your machine does not satisfy the requirement of version >= 2.39.1')
}
}
# 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.4.1'
$ManifestVersion = '1.6.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'
if (-not ([System.Environment]::OSVersion.Platform -match 'Win')) { $env:TEMP = '/tmp/' }
$wingetUpstream = 'https://github.com/microsoft/winget-pkgs.git'
$RunHash = $(Get-FileHash -InputStream $([IO.MemoryStream]::new([byte[]][char[]]$(Get-Date).Ticks.ToString()))).Hash.Substring(0, 8)
$script:UserAgent = 'Microsoft-Delivery-Optimization/10.1'
$_wingetVersion = 1.0.0
$_appInstallerVersion = (Get-AppxPackage Microsoft.DesktopAppInstaller).version
if (Get-Command 'winget' -ErrorAction SilentlyContinue) { $_wingetVersion = (winget -v).TrimStart('v')}
$script:backupUserAgent = "winget-cli WindowsPackageManager/$_wingetVersion DesktopAppInstaller/Microsoft.DesktopAppInstaller v$_appInstallerVersion"
if ($ScriptSettings.EnableDeveloperOptions -eq $true -and $null -ne $ScriptSettings.OverrideManifestVersion) {
$script:UsesPrerelease = $ScriptSettings.OverrideManifestVersion -gt $ManifestVersion
$ManifestVersion = $ScriptSettings.OverrideManifestVersion
}
$useDirectSchemaLink = if ($env:GITHUB_ACTIONS -eq $true) {
$true
} else {
(Invoke-WebRequest "https://aka.ms/winget-manifest.version.$ManifestVersion.schema.json" -UseBasicParsing).Content -match '<!doctype html>'
}
$SchemaUrls = @{
version = if ($useDirectSchemaLink) { "https://raw.githubusercontent.com/microsoft/winget-cli/master/schemas/JSON/manifests/v$ManifestVersion/manifest.version.$ManifestVersion.json" } else { "https://aka.ms/winget-manifest.version.$ManifestVersion.schema.json" }
defaultLocale = if ($useDirectSchemaLink) { "https://raw.githubusercontent.com/microsoft/winget-cli/master/schemas/JSON/manifests/v$ManifestVersion/manifest.defaultLocale.$ManifestVersion.json" } else { "https://aka.ms/winget-manifest.defaultLocale.$ManifestVersion.schema.json" }
locale = if ($useDirectSchemaLink) { "https://raw.githubusercontent.com/microsoft/winget-cli/master/schemas/JSON/manifests/v$ManifestVersion/manifest.locale.$ManifestVersion.json" } else { "https://aka.ms/winget-manifest.locale.$ManifestVersion.schema.json" }
installer = if ($useDirectSchemaLink) { "https://raw.githubusercontent.com/microsoft/winget-cli/master/schemas/JSON/manifests/v$ManifestVersion/manifest.installer.$ManifestVersion.json" } else { "https://aka.ms/winget-manifest.installer.$ManifestVersion.schema.json" }
}
# Fetch Schema data from github for entry validation, key ordering, and automatic commenting
try {
$LocaleSchema = @(Invoke-WebRequest $SchemaUrls.defaultLocale -UseBasicParsing | ConvertFrom-Json)
$LocaleProperties = (ConvertTo-Yaml $LocaleSchema.properties | ConvertFrom-Yaml -Ordered).Keys
$VersionSchema = @(Invoke-WebRequest $SchemaUrls.version -UseBasicParsing | ConvertFrom-Json)
$VersionProperties = (ConvertTo-Yaml $VersionSchema.properties | ConvertFrom-Yaml -Ordered).Keys
$InstallerSchema = @(Invoke-WebRequest $SchemaUrls.installer -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
$AppsAndFeaturesEntryProperties = (ConvertTo-Yaml $InstallerSchema.definitions.AppsAndFeaturesEntry.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 RightTrimString {
$_.TrimEnd()
}
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.Architecture.enum
ValidInstallerTypes = $InstallerSchema.definitions.InstallerType.enum
ValidNestedInstallerTypes = $InstallerSchema.definitions.NestedInstallerType.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
RelativeFilePathMinLength = $InstallerSchema.Definitions.NestedInstallerFiles.items.properties.RelativeFilePath.minLength
RelativeFilePathMaxLength = $InstallerSchema.Definitions.NestedInstallerFiles.items.properties.RelativeFilePath.maxLength
PortableCommandAliasMinLength = $InstallerSchema.Definitions.NestedInstallerFiles.items.properties.PortableCommandAlias.minLength
PortableCommandAliasMaxLength = $InstallerSchema.Definitions.NestedInstallerFiles.items.properties.PortableCommandAlias.maxLength
ArchiveInstallerTypes = @('zip')
ARP_DisplayNameMinLength = $InstallerSchema.Definitions.AppsAndFeaturesEntry.properties.DisplayName.minLength
ARP_DisplayNameMaxLength = $InstallerSchema.Definitions.AppsAndFeaturesEntry.properties.DisplayName.maxLength
ARP_PublisherMinLength = $InstallerSchema.Definitions.AppsAndFeaturesEntry.properties.Publisher.minLength
ARP_PublisherMaxLength = $InstallerSchema.Definitions.AppsAndFeaturesEntry.properties.Publisher.maxLength
ARP_DisplayVersionMinLength = $InstallerSchema.Definitions.AppsAndFeaturesEntry.properties.DisplayVersion.minLength
ARP_DisplayVersionMaxLength = $InstallerSchema.Definitions.AppsAndFeaturesEntry.properties.DisplayVersion.maxLength
}
# check if upstream exists
($remoteUpstreamUrl = $(git remote get-url upstream)) *> $null
if ($remoteUpstreamUrl -and $remoteUpstreamUrl -ne $wingetUpstream) {
git remote set-url upstream $wingetUpstream
} elseif (!$remoteUpstreamUrl) {
Write-Host -ForegroundColor 'Yellow' 'Upstream does not exist. Permanently adding https://github.com/microsoft/winget-pkgs as remote upstream'
git remote add upstream $wingetUpstream
}
# Since this script changes the UI Calling Culture, a clean exit should set it back to the user preference
# If the remote upstream was changed, that should also be set back
Function Invoke-CleanExit {
if ($remoteUpstreamUrl -and $remoteUpstreamUrl -ne $wingetUpstream) {
git remote set-url upstream $remoteUpstreamUrl
}
Write-Host
[Threading.Thread]::CurrentThread.CurrentUICulture = $callingUICulture
[Threading.Thread]::CurrentThread.CurrentCulture = $callingCulture
exit
}
# 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
}
}
# Gets the effective installer type from an installer
Function Get-EffectiveInstallerType {
Param
(
[Parameter(Mandatory = $true, Position = 0)]
[PSCustomObject] $Installer
)
if ($Installer.Keys -notcontains 'InstallerType') {
throw [System.ArgumentException]::new('Invalid Function Parameters. Installer must contain `InstallerType` key')
}
if ($Installer.InstallerType -notin $Patterns.ArchiveInstallerTypes) {
return $Installer.InstallerType
}
if ($Installer.Keys -notcontains 'NestedInstallerType') {
throw [System.ArgumentException]::new("Invalid Function Parameters. Installer type $($Installer.InstallerType) must contain `NestedInstallerType` key")
}
return $Installer.NestedInstallerType
}
# 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++
}
}
# 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 = $script:UserAgent
$HTTP_Response = $HTTP_Request.GetResponse()
$script:ResponseUri = $HTTP_Response.ResponseUri.AbsoluteUri
$HTTP_Status = [int]$HTTP_Response.StatusCode
} catch {
# Failed to download with the Delivery-Optimization User Agent, so try again with the WinINet User Agent
try {
$HTTP_Request = [System.Net.WebRequest]::Create($URL)
$HTTP_Request.UserAgent = $script:backupUserAgent
$HTTP_Response = $HTTP_Request.GetResponse()
$script:ResponseUri = $HTTP_Response.ResponseUri.AbsoluteUri
$HTTP_Status = [int]$HTTP_Response.StatusCode
} catch {
$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
}
}
}
$NewInstallerUrl = [System.Web.HttpUtility]::UrlDecode($NewInstallerUrl.Replace('+', '%2B'))
$NewInstallerUrl = $NewInstallerUrl.Replace(' ', '%20')
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 $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', $script:UserAgent)
# 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
try {
$_WebClient.DownloadFile($URI, $_OutFile)
} catch {
# Failed to download with the Delivery-Optimization User Agent, so try again with the WinINet User Agent
$_WebClient.Headers.Clear()
$_WebClient.Headers.Add('User-Agent', $script:backupUserAgent)
$_WebClient.DownloadFile($URI, $_OutFile)
} finally {
# 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 -Object $_Table -PropertyName StringData -ArgumentList 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 -Object $_Item -PropertyName StringData -ArgumentList 1
if ($_Table -eq 'Property') { $_ItemValue = Get-Property -Object $_Item -PropertyName StringData -ArgumentList 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-ExeType {
Param
(
[Parameter(Mandatory = $true)]
[String] $Path
)
$nsis = @(
77; 90; -112; 0; 3; 0; 0; 0; 4; 0; 0; 0; -1; -1; 0; 0;
-72; 0; 0; 0; 0; 0; 0; 0; 64; 0; 0; 0; 0; 0; 0; 0; 0; 0;
0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0;
0; 0; 0; 0; 0; 0; -40; 0; 0; 0; 14; 31; -70; 14; 0; -76;
9; -51; 33; -72; 1; 76; -51; 33; 84; 104; 105; 115;
32; 112; 114; 111; 103; 114; 97; 109; 32; 99; 97;
110; 110; 111; 116; 32; 98; 101; 32; 114; 117; 110;
32; 105; 110; 32; 68; 79; 83; 32; 109; 111; 100;
101; 46; 13; 13; 10; 36; 0; 0; 0; 0; 0; 0; 0; -83; 49;
8; -127; -23; 80; 102; -46; -23; 80; 102; -46; -23;
80; 102; -46; 42; 95; 57; -46; -21; 80; 102; -46;
-23; 80; 103; -46; 76; 80; 102; -46; 42; 95; 59; -46;
-26; 80; 102; -46; -67; 115; 86; -46; -29; 80; 102;
-46; 46; 86; 96; -46; -24; 80; 102; -46; 82; 105; 99;
104; -23; 80; 102; -46; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0;
0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 80; 69; 0; 0; 76;
1; 5; 0
)
$inno = @(
77; 90; 80; 0; 2; 0; 0; 0; 4; 0; 15; 0; 255; 255; 0; 0;
184; 0; 0; 0; 0; 0; 0; 0; 64; 0; 26; 0; 0; 0; 0; 0; 0; 0;
0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0;
0; 0; 0; 0; 0; 0; 0; 1; 0; 0; 186; 16; 0; 14; 31; 180; 9;
205; 33; 184; 1; 76; 205; 33; 144; 144; 84; 104; 105;
115; 32; 112; 114; 111; 103; 114; 97; 109; 32; 109;
117; 115; 116; 32; 98; 101; 32; 114; 117; 110; 32;
117; 110; 100; 101; 114; 32; 87; 105; 110; 51; 50;
13; 10; 36; 55; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0;
0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0;
0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0;
0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0;
0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0;
0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0;
0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0;
0; 0; 80; 69; 0; 0; 76; 1; 10; 0)
$burn = @(46; 119; 105; 120; 98; 117; 114; 110)
$exeType = $null
$fileStream = New-Object -TypeName System.IO.FileStream -ArgumentList ($Path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read)
$reader = New-Object -TypeName System.IO.BinaryReader -ArgumentList $fileStream
$bytes = $reader.ReadBytes(264)
if (($bytes[0..223] -join '') -eq ($nsis -join '')) { $exeType = 'nullsoft' }
elseif (($bytes -join '') -eq ($inno -join '')) { $exeType = 'inno' }
# The burn header can appear before a certain point in the binary. Check to see if it's present in the first 264 bytes read
elseif (($bytes -join '') -match ($burn -join '')) { $exeType = 'burn' }
# If the burn header isn't present in the first 264 bytes, scan through the rest of the binary
elseif ($ScriptSettings.IdentifyBurnInstallers -eq 'true') {
$rollingBytes = $bytes[ - $burn.Length..-1]
for ($i = 265; $i -lt ($fileStream.Length, 524280 | Measure-Object -Minimum).Minimum; $i++) {
$rollingBytes = $rollingBytes[1..$rollingBytes.Length]
$rollingBytes += $reader.ReadByte()
if (($rollingBytes -join '') -match ($burn -join '')) {
$exeType = 'burn'
break
}
}
}
$reader.Dispose()
$fileStream.Dispose()
return $exeType
}
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$') {
if ([System.Environment]::OSVersion.Platform -match 'Unix') {
$ObjectDatabase = @{}
$ObjectMetadata = @{
ProgramName = $(([string](file $script:dest) | Select-String -Pattern 'Creating Application.+,').Matches.Value)
}
} else {
$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' }
if ($Path -match '\.exe$') { return Get-ExeType($Path) }
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
}
Function Get-UriScope {
Param
(
[Parameter(Mandatory = $true, Position = 0)]
[string] $URI
)
if ($URI -match '\buser\b') { return 'user' }
if ($URI -match '\bmachine\b') { return 'machine' }
return $null
}
function Get-PublisherHash($publisherName) {
# Sourced from https://marcinotorowski.com/2021/12/19/calculating-hash-part-of-msix-package-family-name
$publisherNameAsUnicode = [System.Text.Encoding]::Unicode.GetBytes($publisherName);
$publisherSha256 = [System.Security.Cryptography.HashAlgorithm]::Create('SHA256').ComputeHash($publisherNameAsUnicode);
$publisherSha256First8Bytes = $publisherSha256 | Select-Object -First 8;
$publisherSha256AsBinary = $publisherSha256First8Bytes | ForEach-Object { [System.Convert]::ToString($_, 2).PadLeft(8, '0') };
$asBinaryStringWithPadding = [System.String]::Concat($publisherSha256AsBinary).PadRight(65, '0');
$encodingTable = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
$result = '';
for ($i = 0; $i -lt $asBinaryStringWithPadding.Length; $i += 5) {
$asIndex = [System.Convert]::ToInt32($asBinaryStringWithPadding.Substring($i, 5), 2);
$result += $encodingTable[$asIndex];
}
return $result.ToLower();
}
Function Get-PackageFamilyName {
Param
(
[Parameter(Mandatory = $true, Position = 0)]
[string] $FilePath
)
if ($FilePath -notmatch '\.(msix|appx)(bundle){0,1}$') { return $null }
# Make the downloaded installer a zip file
$_MSIX = Get-Item $FilePath
$_Zip = Join-Path $_MSIX.Directory.FullName -ChildPath 'MSIX_YamlCreate.zip'
$_ZipFolder = [System.IO.Path]::GetDirectoryName($_ZIp) + '\' + [System.IO.Path]::GetFileNameWithoutExtension($_Zip)
Copy-Item -Path $_MSIX.FullName -Destination $_Zip
# Progress preference has to be set globally for Expand-Archive
# https://github.com/PowerShell/Microsoft.PowerShell.Archive/issues/77#issuecomment-601947496
$globalPreference = $global:ProgressPreference
$global:ProgressPreference = 'SilentlyContinue'
# Expand the zip file to access the manifest inside
Expand-Archive $_Zip -DestinationPath $_ZipFolder -Force
# Restore the old progress preference
$global:ProgressPreference = $globalPreference
# Package could be a single package or a bundle, so regex search for either of them
$_AppxManifest = Get-ChildItem $_ZipFolder -Recurse -File -Filter '*.xml' | Where-Object { $_.Name -match '^Appx(Bundle)?Manifest.xml$' } | Select-Object -First 1
[XML] $_XMLContent = Get-Content $_AppxManifest.FullName -Raw
# The path to the node is different between single package and bundles, this should work to get either
$_Identity = @($_XMLContent.Bundle.Identity) + @($_XMLContent.Package.Identity)
# Cleanup the files that were created
Remove-Item $_Zip -Force
Remove-Item $_ZipFolder -Recurse -Force
# Return the PFN
return $_Identity.Name + '_' + $(Get-PublisherHash $_Identity.Publisher)
}
# Prompts the user to enter the Package Identifier if it has not been set
# Validates that the package identifier matches the schema
# Returns the package identifier
Function Read-PackageIdentifier {
Param(
[Parameter(Mandatory = $true, Position = 0)]
[AllowEmptyString()]
[string] $PackageIdentifier
)
$_EnteredIdentifier = $PackageIdentifier
do {
if ((Test-String $_EnteredIdentifier -IsNull) -or ($script:_returnValue.StatusCode -ne [ReturnValue]::Success().StatusCode)) {
Write-Host -ForegroundColor 'Red' $script:_returnValue.ErrorString()
Write-Host -ForegroundColor 'Green' -Object '[Required] Enter the Package Identifier, in the following format <Publisher shortname.Application shortname>. For example: Microsoft.Excel'
$_EnteredIdentifier = Read-Host -Prompt 'PackageIdentifier' | TrimString
}
$script:PackageIdentifierFolder = $_EnteredIdentifier.Replace('.', '\')
if (Test-String $_EnteredIdentifier -MinLength 4 -MaxLength $Patterns.IdentifierMaxLength -MatchPattern $Patterns.PackageIdentifier) {
$script:_returnValue = [ReturnValue]::Success()
} else {
if (Test-String -not $_EnteredIdentifier -MinLength 4 -MaxLength $Patterns.IdentifierMaxLength) {
$script:_returnValue = [ReturnValue]::LengthError(4, $Patterns.IdentifierMaxLength)
} elseif (Test-String -not $_EnteredIdentifier -MatchPattern $Patterns.PackageIdentifier) {
$script:_returnValue = [ReturnValue]::PatternError()
} else {
$script:_returnValue = [ReturnValue]::GenericError()
}
}
} until ($script:_returnValue.StatusCode -eq [ReturnValue]::Success().StatusCode)
return $_EnteredIdentifier
}
# Prompts the user to enter the details for an archive Installer
# Takes the installer as an input
# Returns the modified installer
Function Read-NestedInstaller {
Param(
[Parameter(Mandatory = $true, Position = 0)]
[PSCustomObject] $_Installer
)
if ($_Installer['InstallerType'] -CIn @($Patterns.ArchiveInstallerTypes)) {
# Manual Entry of Nested Installer Type with validation
if ($_Installer['NestedInstallerType'] -CNotIn @($Patterns.ValidInstallerTypes)) {
do {
Write-Host -ForegroundColor 'Red' $script:_returnValue.ErrorString()
Write-Host -ForegroundColor 'Green' -Object '[Required] Enter the NestedInstallerType. Options:' , @($Patterns.ValidNestedInstallerTypes -join ', ' )
$_Installer['NestedInstallerType'] = Read-Host -Prompt 'NestedInstallerType' | TrimString
if ($_Installer['NestedInstallerType'] -Cin @($Patterns.ValidNestedInstallerTypes)) {
$script:_returnValue = [ReturnValue]::Success()
} else {
$script:_returnValue = [ReturnValue]::new(400, 'Invalid Installer Type', "Value must exist in the enum - $(@($Patterns.ValidNestedInstallerTypes -join ', '))", 2)
}
} until ($script:_returnValue.StatusCode -eq [ReturnValue]::Success().StatusCode)
}
$_EffectiveType = Get-EffectiveInstallerType $_Installer
$_NestedInstallerFiles = @()
do {
$_InstallerFile = [ordered] @{}
$AnotherNestedInstaller = $false
$_RelativePath = $null
$_Alias = $null
do {
Write-Host -ForegroundColor 'Red' $script:_returnValue.ErrorString()
Write-Host -ForegroundColor 'Green' -Object '[Required] Enter the relative path to the installer file'
if (Test-String -not $_RelativePath -IsNull) { Write-Host -ForegroundColor 'DarkGray' "Old Variable: $_RelativePath" }
$_RelativePath = Read-Host -Prompt 'RelativeFilePath' | TrimString
if (Test-String -not $_RelativePath -IsNull) { $_InstallerFile['RelativeFilePath'] = $_RelativePath }
if (Test-String $_RelativePath -MinLength $Patterns.RelativeFilePathMinLength -MaxLength $Patterns.RelativeFilePathMaxLength) {
$script:_returnValue = [ReturnValue]::Success()
} else {
$script:_returnValue = [ReturnValue]::LengthError($Patterns.RelativeFilePathMinLength, $Patterns.RelativeFilePathMaxLength)
}
if ($_RelativePath -in @($_NestedInstallerFiles.RelativeFilePath)) {
$script:_returnValue = [ReturnValue]::new(400, 'Path Collision', 'Relative file path must be unique', 2)
}
} until ($script:_returnValue.StatusCode -eq [ReturnValue]::Success().StatusCode)
if ($_EffectiveType -eq 'portable') {
do {
Write-Host -ForegroundColor 'Red' $script:_returnValue.ErrorString()
Write-Host -ForegroundColor 'Yellow' -Object '[Optional] Enter the portable command alias'
if (Test-String -not "$($_InstallerFile['PortableCommandAlias'])" -IsNull) { Write-Host -ForegroundColor 'DarkGray' "Old Variable: $($_InstallerFile['PortableCommandAlias'])" }
$_Alias = Read-Host -Prompt 'PortableCommandAlias' | TrimString
if (Test-String -not $_Alias -IsNull) { $_InstallerFile['PortableCommandAlias'] = $_Alias }
if (Test-String $_InstallerFile['PortableCommandAlias'] -MinLength $Patterns.PortableCommandAliasMinLength -MaxLength $Patterns.PortableCommandAliasMaxLength -AllowNull) {
$script:_returnValue = [ReturnValue]::Success()
} else {
$script:_returnValue = [ReturnValue]::LengthError($Patterns.PortableCommandAliasMinLength, $Patterns.PortableCommandAliasMaxLength)
}
if ("$($_InstallerFile['PortableCommandAlias'])" -in @($_NestedInstallerFiles.PortableCommandAlias)) {
$script:_returnValue = [ReturnValue]::new(400, 'Alias Collision', 'Aliases must be unique', 2)