-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHelpers.psm1
More file actions
1165 lines (997 loc) · 38.8 KB
/
Copy pathHelpers.psm1
File metadata and controls
1165 lines (997 loc) · 38.8 KB
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
[CmdletBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSAvoidUsingWriteHost', '',
Justification = 'Want to just write to the console, not the pipeline.'
)]
param()
function Convert-VersionSpec {
<#
.SYNOPSIS
Converts legacy version parameters into a NuGet version range string.
.DESCRIPTION
This function takes minimum, maximum, or required version parameters
and constructs a NuGet-compatible version range string.
- If `RequiredVersion` is specified, the output is an exact match range.
- If both `MinimumVersion` and `MaximumVersion` are provided,
an inclusive range is returned.
- If only `MinimumVersion` is provided, it returns a minimum-inclusive range.
- If only `MaximumVersion` is provided, it returns an upper-bound range.
- If no parameters are provided, `$null` is returned.
.EXAMPLE
Convert-VersionSpec -MinimumVersion "1.0.0" -MaximumVersion "2.0.0"
Output:
```powershell
[1.0.0,2.0.0]
```
Returns an inclusive version range from 1.0.0 to 2.0.0.
.EXAMPLE
Convert-VersionSpec -RequiredVersion "1.5.0"
Output:
```powershell
[1.5.0]
```
Returns an exact match for version 1.5.0.
.EXAMPLE
Convert-VersionSpec -MinimumVersion "1.0.0"
Output:
```powershell
[1.0.0, ]
```
Returns a minimum-inclusive version range starting at 1.0.0.
.EXAMPLE
Convert-VersionSpec -MaximumVersion "2.0.0"
Output:
```powershell
(, 2.0.0]
```
Returns an upper-bound range up to version 2.0.0.
.OUTPUTS
string
.NOTES
The NuGet version range string based on the provided parameters.
The returned string follows NuGet versioning syntax.
.LINK
https://psmodule.io/Convert/Functions/Convert-VersionSpec
#>
[OutputType([string])]
[CmdletBinding()]
param(
# The minimum version for the range. If specified alone, the range is open-ended upwards.
[Parameter()]
[string] $MinimumVersion,
# The maximum version for the range. If specified alone, the range is open-ended downwards.
[Parameter()]
[string] $MaximumVersion,
# Specifies an exact required version. If set, an exact version range is returned.
[Parameter()]
[string] $RequiredVersion
)
if ($RequiredVersion) {
# Use exact match in bracket notation.
return "[$RequiredVersion]"
} elseif ($MinimumVersion -and $MaximumVersion) {
# Both bounds provided; both are inclusive.
return "[$MinimumVersion,$MaximumVersion]"
} elseif ($MinimumVersion) {
# Only a minimum is provided. Use a minimum-inclusive range.
return "[$MinimumVersion, ]"
} elseif ($MaximumVersion) {
# Only a maximum is provided; lower bound open.
return "(, $MaximumVersion]"
} else {
return $null
}
}
function Import-PSModule {
<#
.SYNOPSIS
Imports a build PS module.
.DESCRIPTION
Imports a build PS module.
.EXAMPLE
Import-PSModule -SourceFolderPath $ModuleFolderPath -ModuleName $moduleName
Imports a module located at $ModuleFolderPath with the name $moduleName.
#>
[CmdletBinding()]
param(
# Path to the folder where the module source code is located.
[Parameter(Mandatory)]
[string] $Path
)
$moduleName = Split-Path -Path $Path -Leaf
$manifestFilePath = Join-Path -Path $Path "$moduleName.psd1"
Write-Host " - Manifest file path: [$manifestFilePath]"
Resolve-PSModuleDependency -ManifestFilePath $manifestFilePath
Write-Host ' - List installed modules'
Get-InstalledPSResource | Format-Table -AutoSize | Out-String
Write-Host " - Importing module [$moduleName] v999"
Import-Module $Path
Write-Host ' - List loaded modules'
$availableModules = Get-Module -ListAvailable -Refresh -Verbose:$false
$availableModules | Select-Object Name, Version, Path | Sort-Object Name | Format-Table -AutoSize | Out-String
Write-Host ' - List commands'
$commands = Get-Command -Module $moduleName -ListImported
Get-Command -Module $moduleName -ListImported | Format-Table -AutoSize | Out-String
if ($moduleName -notin $commands.Source) {
throw 'Module not found'
}
}
function Resolve-PSModuleDependency {
<#
.SYNOPSIS
Resolves module dependencies from a manifest file using Install-PSResource.
.DESCRIPTION
Reads a module manifest (PSD1) and for each required module converts the old
Install-Module parameters (MinimumVersion, MaximumVersion, RequiredVersion)
into a single NuGet version range string for Install-PSResource's –Version parameter.
(Note: If RequiredVersion is set, that value takes precedence.)
.EXAMPLE
Resolve-PSModuleDependency -ManifestFilePath 'C:\MyModule\MyModule.psd1'
Installs all modules defined in the manifest file, following PSModuleInfo structure.
.NOTES
Should later be adapted to support both pre-reqs, and dependencies.
Should later be adapted to take 4 parameters sets: specific version ("requiredVersion" | "GUID"), latest version ModuleVersion,
and latest version within a range MinimumVersion - MaximumVersion.
#>
[CmdletBinding()]
param(
# The path to the manifest file.
[Parameter(Mandatory)]
[string] $ManifestFilePath
)
Write-Host 'Resolving dependencies'
$manifest = Import-PowerShellDataFile -Path $ManifestFilePath
Write-Host " - Reading [$ManifestFilePath]"
Write-Host " - Found [$($manifest.RequiredModules.Count)] module(s) to install"
foreach ($requiredModule in $manifest.RequiredModules) {
# Build parameters for Install-PSResource (new version spec).
$psResourceParams = @{
TrustRepository = $true
}
# Build parameters for Import-Module (legacy version spec).
$importParams = @{
Force = $true
Verbose = $false
}
if ($requiredModule -is [string]) {
$psResourceParams.Name = $requiredModule
$importParams.Name = $requiredModule
} else {
$psResourceParams.Name = $requiredModule.ModuleName
$importParams.Name = $requiredModule.ModuleName
# Convert legacy version info for Install-PSResource.
$versionSpec = Convert-VersionSpec `
-MinimumVersion $requiredModule.ModuleVersion `
-MaximumVersion $requiredModule.MaximumVersion `
-RequiredVersion $requiredModule.RequiredVersion
if ($versionSpec) {
$psResourceParams.Version = $versionSpec
}
# For Import-Module, keep the original version parameters.
if ($requiredModule.ModuleVersion) {
$importParams.MinimumVersion = $requiredModule.ModuleVersion
}
if ($requiredModule.RequiredVersion) {
$importParams.RequiredVersion = $requiredModule.RequiredVersion
}
if ($requiredModule.MaximumVersion) {
$importParams.MaximumVersion = $requiredModule.MaximumVersion
}
}
Write-Host " - [$($psResourceParams.Name)] - Installing module with Install-PSResource using version spec: $($psResourceParams.Version)"
$VerbosePreferenceOriginal = $VerbosePreference
$VerbosePreference = 'SilentlyContinue'
$retryCount = 5
$retryDelay = 10
for ($i = 0; $i -lt $retryCount; $i++) {
try {
Install-PSResource @psResourceParams
break
} catch {
Write-Warning "Installation of $($psResourceParams.Name) failed with error: $_"
if ($i -eq $retryCount - 1) {
throw
}
Write-Warning "Retrying in $retryDelay seconds..."
Start-Sleep -Seconds $retryDelay
}
}
$VerbosePreference = $VerbosePreferenceOriginal
Write-Host " - [$($importParams.Name)] - Importing module with legacy version spec"
$VerbosePreferenceOriginal = $VerbosePreference
$VerbosePreference = 'SilentlyContinue'
Import-Module @importParams
$VerbosePreference = $VerbosePreferenceOriginal
Write-Host " - [$($importParams.Name)] - Done"
}
Write-Host ' - Resolving dependencies - Done'
}
function Show-FileContent {
<#
.SYNOPSIS
Prints the content of a file with line numbers in front of each line.
.DESCRIPTION
Prints the content of a file with line numbers in front of each line.
.EXAMPLE
$Path = 'C:\Utilities\Show-FileContent.ps1'
Show-FileContent -Path $Path
Shows the content of the file with line numbers in front of each line.
#>
[CmdletBinding()]
param (
# The path to the file to show the content of.
[Parameter(Mandatory)]
[string] $Path
)
$content = Get-Content -Path $Path
$lineNumber = 1
$columnSize = $content.Count.ToString().Length
# Foreach line print the line number in front of the line with [ ] around it.
# The linenumber should dynamically adjust to the number of digits with the length of the file.
foreach ($line in $content) {
$lineNumberFormatted = $lineNumber.ToString().PadLeft($columnSize)
Write-Host "[$lineNumberFormatted] $line"
$lineNumber++
}
}
function Install-PSModule {
<#
.SYNOPSIS
Installs a build PS module.
.DESCRIPTION
Installs a build PS module.
.EXAMPLE
Install-PSModule -SourceFolderPath $ModuleFolderPath -ModuleName $moduleName
Installs a module located at $ModuleFolderPath with the name $moduleName.
#>
[CmdletBinding()]
param(
# Path to the folder where the module source code is located.
[Parameter(Mandatory)]
[string] $Path,
# Return the path of the installed module
[Parameter()]
[switch] $PassThru
)
$moduleName = Split-Path -Path $Path -Leaf
$manifestFilePath = Join-Path -Path $Path "$moduleName.psd1"
Write-Verbose " - Manifest file path: [$manifestFilePath]" -Verbose
Write-Host '::group::Resolving dependencies'
Resolve-PSModuleDependency -ManifestFilePath $manifestFilePath
Write-Host '::endgroup::'
$PSModulePath = $env:PSModulePath -split [System.IO.Path]::PathSeparator | Select-Object -First 1
$codePath = New-Item -Path "$PSModulePath/$moduleName/999.0.0" -ItemType Directory -Force | Select-Object -ExpandProperty FullName
Copy-Item -Path "$Path/*" -Destination $codePath -Recurse -Force
Write-Host '::group::Importing module'
Import-Module -Name $moduleName -Verbose
Write-Host '::endgroup::'
if ($PassThru) {
return $codePath
}
}
function Get-ModuleManifest {
<#
.SYNOPSIS
Get the module manifest.
.DESCRIPTION
Get the module manifest as a path, file info, content, or hashtable.
.EXAMPLE
Get-PSModuleManifest -Path 'src/PSModule/PSModule.psd1' -As Hashtable
#>
[OutputType([string], [System.IO.FileInfo], [System.Collections.Hashtable], [System.Collections.Specialized.OrderedDictionary])]
[CmdletBinding()]
param(
# Path to the module manifest file.
[Parameter(Mandatory)]
[string] $Path,
# The format of the output.
[Parameter()]
[ValidateSet('FileInfo', 'Content', 'Hashtable')]
[string] $As = 'Hashtable'
)
if (-not (Test-Path -Path $Path)) {
Write-Warning 'No manifest file found.'
return $null
}
Write-Verbose "Found manifest file [$Path]"
switch ($As) {
'FileInfo' {
return Get-Item -Path $Path
}
'Content' {
return Get-Content -Path $Path
}
'Hashtable' {
$manifest = [System.Collections.Specialized.OrderedDictionary]@{}
$psData = [System.Collections.Specialized.OrderedDictionary]@{}
$privateData = [System.Collections.Specialized.OrderedDictionary]@{}
$tempManifest = Import-PowerShellDataFile -Path $Path
if ($tempManifest.ContainsKey('PrivateData')) {
$tempPrivateData = $tempManifest.PrivateData
if ($tempPrivateData.ContainsKey('PSData')) {
$tempPSData = $tempPrivateData.PSData
$tempPrivateData.Remove('PSData')
}
}
$psdataOrder = @(
'Tags'
'LicenseUri'
'ProjectUri'
'IconUri'
'ReleaseNotes'
'Prerelease'
'RequireLicenseAcceptance'
'ExternalModuleDependencies'
)
foreach ($key in $psdataOrder) {
if (($null -ne $tempPSData) -and ($tempPSData.ContainsKey($key))) {
$psData.$key = $tempPSData.$key
}
}
if ($psData.Count -gt 0) {
$privateData.PSData = $psData
} else {
$privateData.Remove('PSData')
}
foreach ($key in $tempPrivateData.Keys) {
$privateData.$key = $tempPrivateData.$key
}
$manifestOrder = @(
'RootModule'
'ModuleVersion'
'CompatiblePSEditions'
'GUID'
'Author'
'CompanyName'
'Copyright'
'Description'
'PowerShellVersion'
'PowerShellHostName'
'PowerShellHostVersion'
'DotNetFrameworkVersion'
'ClrVersion'
'ProcessorArchitecture'
'RequiredModules'
'RequiredAssemblies'
'ScriptsToProcess'
'TypesToProcess'
'FormatsToProcess'
'NestedModules'
'FunctionsToExport'
'CmdletsToExport'
'VariablesToExport'
'AliasesToExport'
'DscResourcesToExport'
'ModuleList'
'FileList'
'HelpInfoURI'
'DefaultCommandPrefix'
'PrivateData'
)
foreach ($key in $manifestOrder) {
if ($tempManifest.ContainsKey($key)) {
$manifest.$key = $tempManifest.$key
}
}
if ($privateData.Count -gt 0) {
$manifest.PrivateData = $privateData
} else {
$manifest.Remove('PrivateData')
}
return $manifest
}
}
}
filter Set-ModuleManifest {
<#
.SYNOPSIS
Sets the values of a module manifest file.
.DESCRIPTION
This function sets the values of a module manifest file.
Very much like the Update-ModuleManifest function, but allows values to be missing.
.EXAMPLE
Set-ModuleManifest -Path 'C:\MyModule\MyModule.psd1' -ModuleVersion '1.0.0'
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSUseShouldProcessForStateChangingFunctions', '',
Justification = 'Function does not change state.'
)]
[CmdletBinding()]
param(
# Path to the module manifest file.
[Parameter(
Mandatory,
ValueFromPipeline,
ValueFromPipelineByPropertyName
)]
[string] $Path,
#Script module or binary module file associated with this manifest.
[Parameter()]
[AllowNull()]
[string] $RootModule,
#Version number of this module.
[Parameter()]
[AllowNull()]
[Version] $ModuleVersion,
# Supported PSEditions.
[Parameter()]
[AllowNull()]
[string[]] $CompatiblePSEditions,
# ID used to uniquely identify this module.
[Parameter()]
[AllowNull()]
[guid] $GUID,
# Author of this module.
[Parameter()]
[AllowNull()]
[string] $Author,
# Company or vendor of this module.
[Parameter()]
[AllowNull()]
[string] $CompanyName,
# Copyright statement for this module.
[Parameter()]
[AllowNull()]
[string] $Copyright,
# Description of the functionality provided by this module.
[Parameter()]
[AllowNull()]
[string] $Description,
# Minimum version of the PowerShell engine required by this module.
[Parameter()]
[AllowNull()]
[Version] $PowerShellVersion,
# Name of the PowerShell host required by this module.
[Parameter()]
[AllowNull()]
[string] $PowerShellHostName,
# Minimum version of the PowerShell host required by this module.
[Parameter()]
[AllowNull()]
[version] $PowerShellHostVersion,
# Minimum version of Microsoft .NET Framework required by this module.
# This prerequisite is valid for the PowerShell Desktop edition only.
[Parameter()]
[AllowNull()]
[Version] $DotNetFrameworkVersion,
# Minimum version of the common language runtime (CLR) required by this module.
# This prerequisite is valid for the PowerShell Desktop edition only.
[Parameter()]
[AllowNull()]
[Version] $ClrVersion,
# Processor architecture (None,X86, Amd64) required by this module
[Parameter()]
[AllowNull()]
[System.Reflection.ProcessorArchitecture] $ProcessorArchitecture,
# Modules that must be imported into the global environment prior to importing this module.
[Parameter()]
[AllowNull()]
[Object[]] $RequiredModules,
# Assemblies that must be loaded prior to importing this module.
[Parameter()]
[AllowNull()]
[string[]] $RequiredAssemblies,
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
[Parameter()]
[AllowNull()]
[string[]] $ScriptsToProcess,
# Type files (.ps1xml) to be loaded when importing this module.
[Parameter()]
[AllowNull()]
[string[]] $TypesToProcess,
# Format files (.ps1xml) to be loaded when importing this module.
[Parameter()]
[AllowNull()]
[string[]] $FormatsToProcess,
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess.
[Parameter()]
[AllowNull()]
[Object[]] $NestedModules,
# Functions to export from this module, for best performance, do not use wildcards and do not
# delete the entry, use an empty array if there are no functions to export.
[Parameter()]
[AllowNull()]
[string[]] $FunctionsToExport,
# Cmdlets to export from this module, for best performance, do not use wildcards and do not
# delete the entry, use an empty array if there are no cmdlets to export.
[Parameter()]
[AllowNull()]
[string[]] $CmdletsToExport,
# Variables to export from this module.
[Parameter()]
[AllowNull()]
[string[]] $VariablesToExport,
# Aliases to export from this module, for best performance, do not use wildcards and do not
# delete the entry, use an empty array if there are no aliases to export.
[Parameter()]
[AllowNull()]
[string[]] $AliasesToExport,
# DSC resources to export from this module.
[Parameter()]
[AllowNull()]
[string[]] $DscResourcesToExport,
# List of all modules packaged with this module.
[Parameter()]
[AllowNull()]
[Object[]] $ModuleList,
# List of all files packaged with this module.
[Parameter()]
[AllowNull()]
[string[]] $FileList,
# Tags applied to this module. These help with module discovery in online galleries.
[Parameter()]
[AllowNull()]
[string[]] $Tags,
# A URL to the license for this module.
[Parameter()]
[AllowNull()]
[uri] $LicenseUri,
# A URL to the main site for this project.
[Parameter()]
[AllowNull()]
[uri] $ProjectUri,
# A URL to an icon representing this module.
[Parameter()]
[AllowNull()]
[uri] $IconUri,
# ReleaseNotes of this module.
[Parameter()]
[AllowNull()]
[string] $ReleaseNotes,
# Prerelease string of this module.
[Parameter()]
[AllowNull()]
[string] $Prerelease,
# Flag to indicate whether the module requires explicit user acceptance for install/update/save.
[Parameter()]
[AllowNull()]
[bool] $RequireLicenseAcceptance,
# External dependent modules of this module.
[Parameter()]
[AllowNull()]
[string[]] $ExternalModuleDependencies,
# HelpInfo URI of this module.
[Parameter()]
[AllowNull()]
[String] $HelpInfoURI,
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
[Parameter()]
[AllowNull()]
[string] $DefaultCommandPrefix,
# Private data to pass to the module specified in RootModule/ModuleToProcess.
# This may also contain a PSData hashtable with additional module metadata used by PowerShell.
[Parameter()]
[AllowNull()]
[object] $PrivateData
)
$outManifest = [ordered]@{}
$outPSData = [ordered]@{}
$outPrivateData = [ordered]@{}
$tempManifest = Get-ModuleManifest -Path $Path
if ($tempManifest.Keys.Contains('PrivateData')) {
$tempPrivateData = $tempManifest.PrivateData
if ($tempPrivateData.Keys.Contains('PSData')) {
$tempPSData = $tempPrivateData.PSData
$tempPrivateData.Remove('PSData')
}
}
$psdataOrder = @(
'Tags'
'LicenseUri'
'ProjectUri'
'IconUri'
'ReleaseNotes'
'Prerelease'
'RequireLicenseAcceptance'
'ExternalModuleDependencies'
)
foreach ($key in $psdataOrder) {
if (($null -ne $tempPSData) -and $tempPSData.Keys.Contains($key)) {
$outPSData[$key] = $tempPSData[$key]
}
if ($PSBoundParameters.Keys.Contains($key)) {
if ($null -eq $PSBoundParameters[$key]) {
$outPSData.Remove($key)
} else {
$outPSData[$key] = $PSBoundParameters[$key]
}
}
}
if ($outPSData.Count -gt 0) {
$outPrivateData.PSData = $outPSData
} else {
$outPrivateData.Remove('PSData')
}
foreach ($key in $tempPrivateData.Keys) {
$outPrivateData[$key] = $tempPrivateData[$key]
}
foreach ($key in $PrivateData.Keys) {
$outPrivateData[$key] = $PrivateData[$key]
}
$manifestOrder = @(
'RootModule'
'ModuleVersion'
'CompatiblePSEditions'
'GUID'
'Author'
'CompanyName'
'Copyright'
'Description'
'PowerShellVersion'
'PowerShellHostName'
'PowerShellHostVersion'
'DotNetFrameworkVersion'
'ClrVersion'
'ProcessorArchitecture'
'RequiredModules'
'RequiredAssemblies'
'ScriptsToProcess'
'TypesToProcess'
'FormatsToProcess'
'NestedModules'
'FunctionsToExport'
'CmdletsToExport'
'VariablesToExport'
'AliasesToExport'
'DscResourcesToExport'
'ModuleList'
'FileList'
'HelpInfoURI'
'DefaultCommandPrefix'
'PrivateData'
)
foreach ($key in $manifestOrder) {
if ($tempManifest.Keys.Contains($key)) {
$outManifest[$key] = $tempManifest[$key]
}
if ($PSBoundParameters.Keys.Contains($key)) {
if ($null -eq $PSBoundParameters[$key]) {
$outManifest.Remove($key)
} else {
$outManifest[$key] = $PSBoundParameters[$key]
}
}
}
if ($outPrivateData.Count -gt 0) {
$outManifest['PrivateData'] = $outPrivateData
} else {
$outManifest.Remove('PrivateData')
}
$sectionsToSort = @(
'CompatiblePSEditions',
'RequiredAssemblies',
'ScriptsToProcess',
'TypesToProcess',
'FormatsToProcess',
'FunctionsToExport',
'CmdletsToExport',
'VariablesToExport',
'AliasesToExport',
'DscResourcesToExport',
'ModuleList',
'FileList'
)
foreach ($section in $sectionsToSort) {
if ($outManifest.Contains($section) -and $null -ne $outManifest[$section]) {
$outManifest[$section] = @($outManifest[$section] | Sort-Object)
}
}
$objectSectionsToSort = @('RequiredModules', 'NestedModules')
foreach ($section in $objectSectionsToSort) {
if ($outManifest.Contains($section) -and $null -ne $outManifest[$section]) {
$sortedObjects = $outManifest[$section] | Sort-Object -Property {
if ($_ -is [hashtable]) {
$_['ModuleName']
} elseif ($_ -is [Microsoft.PowerShell.Commands.ModuleSpecification]) {
$_.Name
} elseif ($_ -is [string]) {
$_
} else {
throw "Unsupported type '$($_.GetType().Name)' in module manifest."
}
}
$formattedModules = foreach ($item in $sortedObjects) {
if ($item -is [Microsoft.PowerShell.Commands.ModuleSpecification]) {
$hash = [ordered]@{}
$hash['ModuleName'] = $item.Name
if ($item.RequiredVersion) {
$hash['RequiredVersion'] = $item.RequiredVersion.ToString()
} elseif ($item.Version) {
$hash['ModuleVersion'] = $item.Version.ToString()
} elseif ($item.MaximumVersion) {
$hash['MaximumVersion'] = $item.MaximumVersion.ToString()
}
if ($hash.Count -eq 1) {
# Simplify if only ModuleName
$hash.ModuleName
} else {
$hash
}
} elseif ($item -is [hashtable]) {
# Recreate as ordered hashtable explicitly
$orderedItem = [ordered]@{}
if ($item.ContainsKey('ModuleName')) {
$orderedItem['ModuleName'] = $item['ModuleName']
}
if ($item.RequiredVersion) {
$orderedItem['RequiredVersion'] = $item.RequiredVersion
}
if ($item.ModuleVersion) {
$orderedItem['ModuleVersion'] = $item.ModuleVersion
}
if ($item.MaximumVersion) {
$orderedItem['MaximumVersion'] = $item.MaximumVersion
}
$orderedItem
} elseif ($item -is [string]) {
$item
}
}
$outManifest[$section] = @($formattedModules)
}
}
if ($outPrivateData.Contains('PSData')) {
if ($outPrivateData.PSData.Contains('ExternalModuleDependencies') -and $null -ne $outPrivateData.PSData.ExternalModuleDependencies) {
$outPrivateData.PSData.ExternalModuleDependencies = @($outPrivateData.PSData.ExternalModuleDependencies | Sort-Object)
}
if ($outPrivateData.PSData.Contains('Tags') -and $null -ne $outPrivateData.PSData.Tags) {
$outPrivateData.PSData.Tags = @($outPrivateData.PSData.Tags | Sort-Object)
}
}
Remove-Item -Path $Path -Force
Export-PowerShellDataFile -Hashtable $outManifest -Path $Path
}
function Export-PowerShellDataFile {
<#
.SYNOPSIS
Export a hashtable to a .psd1 file.
.DESCRIPTION
This function exports a hashtable to a .psd1 file. It also formats the .psd1 file using the Format-ModuleManifest cmdlet.
.EXAMPLE
Export-PowerShellDataFile -Hashtable @{ Name = 'MyModule'; ModuleVersion = '1.0.0' } -Path 'MyModule.psd1'
#>
[CmdletBinding()]
param (
# The hashtable to export to a .psd1 file.
[Parameter(Mandatory)]
[object] $Hashtable,
# The path of the .psd1 file to export.
[Parameter(Mandatory)]
[string] $Path,
# Force the export, even if the file already exists.
[Parameter()]
[switch] $Force
)
$content = Format-Hashtable -Hashtable $Hashtable
$content | Out-File -FilePath $Path -Force:$Force
Format-ModuleManifest -Path $Path
}
function Format-ModuleManifest {
<#
.SYNOPSIS
Formats a module manifest file.
.DESCRIPTION
This function formats a module manifest file, by removing comments and empty lines,
and then formatting the file using the `Invoke-Formatter` function.
.EXAMPLE
Format-ModuleManifest -Path 'C:\MyModule\MyModule.psd1'
#>
[CmdletBinding()]
param(
# Path to the module manifest file.
[Parameter(Mandatory)]
[string] $Path
)
$Utf8BomEncoding = New-Object System.Text.UTF8Encoding $true
$manifestContent = Get-Content -Path $Path
$manifestContent = $manifestContent | ForEach-Object { $_ -replace '#.*' }
$manifestContent = $manifestContent | ForEach-Object { $_.TrimEnd() }
$manifestContent = $manifestContent | Where-Object { -not [string]::IsNullOrEmpty($_) }
[System.IO.File]::WriteAllLines($Path, $manifestContent, $Utf8BomEncoding)
$manifestContent = Get-Content -Path $Path -Raw
$content = Invoke-Formatter -ScriptDefinition $manifestContent
# Ensure exactly one empty line at the end
$content = $content.TrimEnd([System.Environment]::NewLine) + [System.Environment]::NewLine
[System.IO.File]::WriteAllText($Path, $content, $Utf8BomEncoding)
}
filter Format-Hashtable {
<#
.SYNOPSIS
Converts a hashtable to its PowerShell code representation.
.DESCRIPTION
Recursively converts a hashtable to its PowerShell code representation.
This function is useful for exporting hashtables to `.psd1` files,
making it easier to store and retrieve structured data.
.EXAMPLE
$hashtable = @{
Key1 = 'Value1'
Key2 = @{
NestedKey1 = 'NestedValue1'
NestedKey2 = 'NestedValue2'
}
Key3 = @(1, 2, 3)
Key4 = $true
}
Format-Hashtable -Hashtable $hashtable
Output:
```powershell
@{
Key1 = 'Value1'
Key2 = @{
NestedKey1 = 'NestedValue1'
NestedKey2 = 'NestedValue2'
}
Key3 = @(
1
2
3
)
Key4 = $true
}
```
.OUTPUTS
string
.NOTES
A string representation of the given hashtable.
Useful for serialization and exporting hashtables to files.
.LINK
https://psmodule.io/Hashtable/Functions/Format-Hashtable
#>
[OutputType([string])]
[CmdletBinding()]
param (
# The hashtable to convert to a PowerShell code representation.
[Parameter(
Mandatory,
ValueFromPipeline,
ValueFromPipelineByPropertyName
)]
[System.Collections.IDictionary] $Hashtable,
# The indentation level for formatting nested structures.
[Parameter()]
[int] $IndentLevel = 1
)
# If the hashtable is empty, return '@{}' immediately.
if ($Hashtable.Count -eq 0) {
return '@{}'
}