-
Notifications
You must be signed in to change notification settings - Fork 7.1k
/
ModuleCmdletBase.cs
7595 lines (6746 loc) · 352 KB
/
ModuleCmdletBase.cs
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Configuration;
using System.Management.Automation.Internal;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Security;
using System.Reflection;
using System.Text;
using System.Xml;
using Microsoft.PowerShell.Cmdletization;
using System.Management.Automation.Language;
using Dbg = System.Management.Automation.Diagnostics;
//
// Now define the set of commands for manipulating modules.
//
namespace Microsoft.PowerShell.Commands
{
#region ModuleCmdletBase class
/// <summary>
/// This is the base class for some of the module cmdlets. It contains a number of
/// utility functions for these classes.
/// </summary>
public class ModuleCmdletBase : PSCmdlet
{
/// <summary>
/// Flags defining how a module manifest should be processed.
/// </summary>
[Flags]
internal enum ManifestProcessingFlags
{
/// <summary>
/// Write errors (otherwise no non-terminating-errors are written)
/// </summary>
WriteErrors = 0x1,
/// <summary>
/// Return null on first error (otherwise we try to process other elements of the manifest)
/// </summary>
NullOnFirstError = 0x2,
/// <summary>
/// Load elements of the manifest (i.e. types/format.ps1xml, nested modules, etc.)
/// </summary>
LoadElements = 0x4,
/// <summary>
/// Write warnings.
/// </summary>
WriteWarnings = 0x8,
/// <summary>
/// Force full module manifest processing.
/// </summary>
Force = 0x10,
/// <summary>
/// Ignore PowerShellHostName and PowerShellHostVersion while
/// processing Manifest fields.
/// This is used for GetModule where loading elements does not happen.
/// </summary>
IgnoreHostNameAndHostVersion = 0x20,
}
/// <summary>
/// Options set during module import.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")]
protected internal struct ImportModuleOptions
{
/// <summary>
/// Holds the value of NoClobber parameter in Import-Module
/// This is used when importing modules.
/// </summary>
internal bool NoClobber;
/// <summary>
/// If Scope parameter is Local, this is true.
/// </summary>
internal bool Local;
/// <summary>
/// Lets nested module import to export all of its functions, regardless of language boundaries.
/// This will be allowed when the manifest explicitly exports functions which will limit all visible module functions.
/// </summary>
internal bool AllowNestedModuleFunctionsToExport;
}
/// <summary>
/// This parameter specified a prefix used to modify names of imported commands.
/// </summary>
internal string BasePrefix { set; get; } = string.Empty;
/// <summary>
/// Flags -force operations.
/// </summary>
internal bool BaseForce { get; set; }
/// <summary>
/// Flags -global operations (affects what gets returned by TargetSessionState)
/// </summary>
internal bool BaseGlobal { get; set; }
/// <summary>
/// If set, CompatiblePSEditions checking will be disabled for modules on the System32 path.
/// </summary>
internal bool BaseSkipEditionCheck { get; set; }
internal SessionState TargetSessionState
{
get
{
if (BaseGlobal)
{
return this.Context.TopLevelSessionState.PublicSessionState;
}
else
{
return this.Context.SessionState;
}
}
}
/// <summary>
/// Flags -passthru operations.
/// </summary>
internal bool BasePassThru { get; set; }
/// <summary>
/// Flags -passthru operations.
/// </summary>
internal bool BaseAsCustomObject { get; set; }
/// <summary>
/// Wildcard patterns for the function to import.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Cmdlet parameters.")]
internal List<WildcardPattern> BaseFunctionPatterns { get; set; }
/// <summary>
/// Wildcard patterns for the cmdlets to import.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Cmdlet parameters.")]
internal List<WildcardPattern> BaseCmdletPatterns { get; set; }
/// <summary>
/// Wildcard patterns for the variables to import.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Cmdlet parameters.")]
internal List<WildcardPattern> BaseVariablePatterns { get; set; }
/// <summary>
/// Wildcard patterns for the aliases to import.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Cmdlet parameters.")]
internal List<WildcardPattern> BaseAliasPatterns { get; set; }
/// <summary>
/// The minimum version number to check the module against. Used the underlying property
/// for derived cmdlet parameters.
/// </summary>
internal Version BaseMinimumVersion { get; set; }
/// <summary>
/// The maximum version number to check the module against. Used the underlying property
/// for derived cmdlet parameters.
/// </summary>
internal Version BaseMaximumVersion { get; set; }
/// <summary>
/// The version number to check the module against. Used the underlying property
/// for derived cmdlet parameters.
/// </summary>
internal Version BaseRequiredVersion { get; set; }
/// <summary>
/// The Guid to check the module against. Used the underlying property
/// for derived cmdlet parameters.
/// </summary>
internal Guid? BaseGuid { get; set; }
/// <summary>
/// The arguments to pass to the scriptblock used to create the module.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
protected object[] BaseArgumentList { get; set; }
/// <summary>
/// Disable warnings on cmdlet and function names that have non-standard verbs
/// or non-standard characters in the noun.
/// </summary>
protected bool BaseDisableNameChecking { get; set; } = true;
/// <summary>
/// Add module path to app domain level module path cache if name is not rooted.
/// </summary>
protected bool AddToAppDomainLevelCache { get; set; } = false;
/// <summary>
/// A handy match all pattern used to initialize various import and export lists...
/// </summary>
internal List<WildcardPattern> MatchAll
{
get
{
if (_matchAll == null)
{
_matchAll = new List<WildcardPattern>();
_matchAll.Add(WildcardPattern.Get("*", WildcardOptions.IgnoreCase));
}
return _matchAll;
}
}
private List<WildcardPattern> _matchAll;
// The list of commands permitted in a module manifest
internal static string[] PermittedCmdlets = new string[] {
"Import-LocalizedData", "ConvertFrom-StringData", "Write-Host", "Out-Host", "Join-Path" };
internal static string[] ModuleManifestMembers = new string[] {
"ModuleToProcess",
"NestedModules",
"GUID",
"Author",
"CompanyName",
"Copyright",
"ModuleVersion",
"Description",
"PowerShellVersion",
"PowerShellHostName",
"PowerShellHostVersion",
"CLRVersion",
"DotNetFrameworkVersion",
"ProcessorArchitecture",
"RequiredModules",
"TypesToProcess",
"FormatsToProcess",
"ScriptsToProcess",
"PrivateData",
"RequiredAssemblies",
"ModuleList",
"FileList",
"FunctionsToExport",
"VariablesToExport",
"AliasesToExport",
"CmdletsToExport",
"DscResourcesToExport",
"CompatiblePSEditions",
"HelpInfoURI",
"RootModule",
"DefaultCommandPrefix"
};
private static string[] s_moduleVersionMembers = new string[] {
"ModuleName",
"GUID",
"ModuleVersion"
};
/// <summary>
/// When module manifests lack a CompatiblePSEditions field,
/// they will be treated as if they have this value.
/// The PSModuleInfo will still reflect the lack of value.
/// </summary>
internal static IReadOnlyList<string> DefaultCompatiblePSEditions { get; } = new string[]
{
"Desktop"
};
private Dictionary<string, PSModuleInfo> _currentlyProcessingModules = new Dictionary<string, PSModuleInfo>();
internal bool LoadUsingModulePath(bool found, IEnumerable<string> modulePath, string name, SessionState ss,
ImportModuleOptions options, ManifestProcessingFlags manifestProcessingFlags, out PSModuleInfo module)
{
return LoadUsingModulePath(null, found, modulePath, name, ss, options, manifestProcessingFlags, out module);
}
internal bool LoadUsingModulePath(PSModuleInfo parentModule, bool found, IEnumerable<string> modulePath, string name, SessionState ss,
ImportModuleOptions options, ManifestProcessingFlags manifestProcessingFlags, out PSModuleInfo module)
{
string extension = Path.GetExtension(name);
string fileBaseName;
module = null;
if (string.IsNullOrEmpty(extension) || !ModuleIntrinsics.IsPowerShellModuleExtension(extension))
{
fileBaseName = name;
extension = null;
}
else
fileBaseName = name.Substring(0, name.Length - extension.Length);
// Now search using the module path...
foreach (string path in modulePath)
{
#if UNIX
foreach (string folder in Directory.EnumerateDirectories(path))
{
string moduleName = Path.GetFileName(folder);
if (string.Compare(moduleName, fileBaseName, StringComparison.OrdinalIgnoreCase) == 0)
{
fileBaseName = moduleName;
#endif
string qualifiedPath = Path.Combine(path, fileBaseName);
module = LoadUsingMultiVersionModuleBase(qualifiedPath, manifestProcessingFlags, options, out found);
if (!found)
{
if (name.IndexOfAny(Utils.Separators.Directory) == -1)
{
qualifiedPath = Path.Combine(qualifiedPath, fileBaseName);
}
else if (Directory.Exists(qualifiedPath))
{
// if it points to a directory, add the basename back onto the path...
qualifiedPath = Path.Combine(qualifiedPath, Path.GetFileName(fileBaseName));
}
module = LoadUsingExtensions(parentModule, name, qualifiedPath, extension, null, this.BasePrefix, ss, options, manifestProcessingFlags, out found);
}
if (found)
{
break;
}
#if UNIX
}
}
if (found)
{
break;
}
#endif
}
if (found)
{
// Cache the module's exported commands after importing it, or if the -Refresh flag is used on "Get-Module -List"
if ((module != null) && !module.HadErrorsLoading)
{
AnalysisCache.CacheModuleExports(module, Context);
}
}
return found;
}
/// <summary>
/// Loads the latest valid version if moduleBase is a multi-versioned module directory.
/// </summary>
/// <param name="moduleBase">Module directory path.</param>
/// <param name="manifestProcessingFlags">The flag that indicate manifest processing option.</param>
/// <param name="importModuleOptions">The set of options that are used while importing a module.</param>
/// <param name="found">True if a module was found.</param>
/// <returns></returns>
internal PSModuleInfo LoadUsingMultiVersionModuleBase(string moduleBase, ManifestProcessingFlags manifestProcessingFlags, ImportModuleOptions importModuleOptions, out bool found)
{
PSModuleInfo foundModule = null;
found = false;
foreach (var version in ModuleUtils.GetModuleVersionSubfolders(moduleBase))
{
// Skip the version folder if it is not equal to the required version or does not satisfy the minimum/maximum version criteria
if (!ModuleIntrinsics.IsVersionMatchingConstraints(version, BaseRequiredVersion, BaseMinimumVersion, BaseMaximumVersion))
{
continue;
}
var qualifiedPathWithVersion = Path.Combine(moduleBase,
Path.Combine(version.ToString(), Path.GetFileName(moduleBase)));
string manifestPath = qualifiedPathWithVersion + StringLiterals.PowerShellDataFileExtension;
var isValidModuleVersion = false;
if (File.Exists(manifestPath))
{
isValidModuleVersion = version.Equals(ModuleIntrinsics.GetManifestModuleVersion(manifestPath));
if (isValidModuleVersion)
{
foundModule = LoadUsingExtensions(null, moduleBase, qualifiedPathWithVersion,
StringLiterals.PowerShellDataFileExtension,
null,
this.BasePrefix, /*SessionState*/ null,
importModuleOptions,
manifestProcessingFlags,
out found);
if (found)
{
break;
}
}
}
if (!isValidModuleVersion)
{
WriteVerbose(string.Format(CultureInfo.InvariantCulture, Modules.SkippingInvalidModuleVersionFolder,
version.ToString(), moduleBase));
}
}
return foundModule;
}
/// <summary>
/// Load and execute the manifest psd1 file or a localized manifest psd1 file.
/// </summary>
private Hashtable LoadModuleManifestData(
ExternalScriptInfo scriptInfo,
string[] validMembers,
ManifestProcessingFlags manifestProcessingFlags,
ref bool containedErrors)
{
try
{
return LoadModuleManifestData(scriptInfo.Path, scriptInfo.ScriptBlock, validMembers, manifestProcessingFlags, ref containedErrors);
}
catch (RuntimeException pe)
{
if (0 != (manifestProcessingFlags & ManifestProcessingFlags.WriteErrors))
{
string message = StringUtil.Format(Modules.InvalidModuleManifest, scriptInfo.Path, pe.Message);
MissingMemberException mm = new MissingMemberException(message);
ErrorRecord er = new ErrorRecord(mm, "Modules_InvalidManifest",
ErrorCategory.ResourceUnavailable, scriptInfo.Path);
WriteError(er);
}
containedErrors = true;
return null;
}
}
/// <summary>
/// Extra variables that are allowed to be referenced in module manifest file.
/// </summary>
private static readonly string[] s_extraAllowedVariables = new string[] { SpecialVariables.PSScriptRoot, SpecialVariables.PSEdition, SpecialVariables.EnabledExperimentalFeatures };
/// <summary>
/// Load and execute the manifest psd1 file or a localized manifest psd1 file.
/// </summary>
internal Hashtable LoadModuleManifestData(
string moduleManifestPath,
ScriptBlock scriptBlock,
string[] validMembers,
ManifestProcessingFlags manifestProcessingFlags,
ref bool containedErrors)
{
string message;
var importingModule = 0 != (manifestProcessingFlags & ManifestProcessingFlags.LoadElements);
var writingErrors = 0 != (manifestProcessingFlags & ManifestProcessingFlags.WriteErrors);
// Load the data file(s) to get the module info...
try
{
scriptBlock.CheckRestrictedLanguage(PermittedCmdlets, s_extraAllowedVariables, true);
}
catch (RuntimeException pe)
{
if (writingErrors)
{
message = StringUtil.Format(Modules.InvalidModuleManifest, moduleManifestPath, pe.Message);
MissingMemberException mm = new MissingMemberException(message);
ErrorRecord er = new ErrorRecord(mm, "Modules_InvalidManifest",
ErrorCategory.ResourceUnavailable, moduleManifestPath);
WriteError(er);
}
containedErrors = true;
return null;
}
object result;
object oldPSScriptRoot = Context.GetVariableValue(SpecialVariables.PSScriptRootVarPath);
object oldPSCommandPath = Context.GetVariableValue(SpecialVariables.PSCommandPathVarPath);
ArrayList errors = (ArrayList)Context.GetVariableValue(SpecialVariables.ErrorVarPath);
int oldErrorCount = errors.Count;
try
{
// Set the PSScriptRoot variable in the modules session state
Context.SetVariable(SpecialVariables.PSScriptRootVarPath, Path.GetDirectoryName(moduleManifestPath));
Context.SetVariable(SpecialVariables.PSCommandPathVarPath, moduleManifestPath);
result = PSObject.Base(scriptBlock.InvokeReturnAsIs());
}
finally
{
Context.SetVariable(SpecialVariables.PSScriptRootVarPath, oldPSScriptRoot);
Context.SetVariable(SpecialVariables.PSCommandPathVarPath, oldPSCommandPath);
// We do not want any exceptions to show up in user's session state. So, we are removing errors in the finally block.
// If we're not loading the manifest (and are examining it), prevent errors from showing up in
// the user's session.
if (!importingModule)
{
while (errors.Count > oldErrorCount) { errors.RemoveAt(0); }
}
}
Hashtable data = result as Hashtable;
if (data == null)
{
if (writingErrors)
{
message = StringUtil.Format(Modules.EmptyModuleManifest, moduleManifestPath);
ArgumentException ae = new ArgumentException(message);
ErrorRecord er = new ErrorRecord(ae, "Modules_InvalidManifest",
ErrorCategory.ResourceUnavailable, moduleManifestPath);
WriteError(er);
}
containedErrors = true;
return null;
}
// MSFT:873446 Create a case insensitive comparer based hashtable to help
// with case-insensitive comparison of keys.
data = new Hashtable(data, StringComparer.OrdinalIgnoreCase);
if (validMembers != null && !ValidateManifestHash(data, validMembers, moduleManifestPath, manifestProcessingFlags))
{
containedErrors = true;
if (0 != (manifestProcessingFlags & ManifestProcessingFlags.NullOnFirstError))
return null;
}
return data;
}
/// <summary>
/// Verify the hash contains only valid members. Write an error and return false if it is not valid.
/// </summary>
private bool ValidateManifestHash(
Hashtable data,
string[] validMembers,
string moduleManifestPath,
ManifestProcessingFlags manifestProcessingFlags)
{
bool result = true;
StringBuilder badKeys = new StringBuilder();
foreach (string s in data.Keys)
{
bool found = false;
foreach (string member in validMembers)
{
if (s.Equals(member, StringComparison.OrdinalIgnoreCase))
{
found = true;
}
}
if (!found)
{
if (badKeys.Length > 0)
badKeys.Append(", ");
badKeys.Append("'");
badKeys.Append(s);
badKeys.Append("'");
}
}
if (badKeys.Length > 0)
{
result = false;
string message = null;
if (0 != (manifestProcessingFlags & ManifestProcessingFlags.WriteErrors))
{
// Check for PowerShell Version before checking other keys
// If a PowerShellVersion exists and does not match the requirements, then the error is InsufficientPowerShellVersion
// Else, the error is InvalidManifestMember
Version powerShellVersion;
Version currentPowerShellVersion = PSVersionInfo.PSVersion;
if (GetScalarFromData<Version>(data, moduleManifestPath, "PowerShellVersion", manifestProcessingFlags, out powerShellVersion) &&
currentPowerShellVersion < powerShellVersion)
{
message = StringUtil.Format(Modules.ModuleManifestInsufficientPowerShellVersion,
currentPowerShellVersion,
moduleManifestPath, powerShellVersion);
InvalidOperationException ioe = new InvalidOperationException(message);
ErrorRecord er = new ErrorRecord(ioe, "Modules_InsufficientPowerShellVersion",
ErrorCategory.ResourceUnavailable, moduleManifestPath);
WriteError(er);
}
else
{
StringBuilder validMembersString = new StringBuilder("'");
validMembersString.Append(validMembers[0]);
for (int i = 1; i < validMembers.Length; i++)
{
validMembersString.Append("', '");
validMembersString.Append(validMembers[i]);
}
validMembersString.Append("'");
message = StringUtil.Format(Modules.InvalidModuleManifestMember, moduleManifestPath, validMembersString, badKeys);
InvalidOperationException ioe = new InvalidOperationException(message);
ErrorRecord er = new ErrorRecord(ioe, "Modules_InvalidManifestMember",
ErrorCategory.InvalidData, moduleManifestPath);
WriteError(er);
}
}
}
return result;
}
private PSModuleInfo LoadModuleNamedInManifest(PSModuleInfo parentModule, ModuleSpecification moduleSpecification, string moduleBase, bool searchModulePath,
string prefix, SessionState ss, ImportModuleOptions options, ManifestProcessingFlags manifestProcessingFlags, bool loadTypesFiles,
bool loadFormatFiles, object privateData, out bool found, string shortModuleName, PSLanguageMode? manifestLanguageMode)
{
PSModuleInfo module = null;
PSModuleInfo tempModuleInfoFromVerification = null;
found = false;
bool moduleFileFound = false;
bool wasRooted = false;
Version savedBaseMinimumVersion = BaseMinimumVersion;
Version savedBaseMaximumVersion = BaseMaximumVersion;
Version savedBaseRequiredVersion = BaseRequiredVersion;
Guid? savedBaseGuid = BaseGuid;
var importingModule = manifestProcessingFlags.HasFlag(ManifestProcessingFlags.LoadElements);
string extension = Path.GetExtension(moduleSpecification.Name);
// First check for fully-qualified paths - either absolute or relative
string rootedPath = ResolveRootedFilePath(moduleSpecification.Name, this.Context);
if (string.IsNullOrEmpty(rootedPath))
{
rootedPath = FixupFileName(moduleBase, moduleSpecification.Name, extension, importingModule);
}
else
{
wasRooted = true;
}
try
{
this.Context.Modules.IncrementModuleNestingDepth(this, rootedPath);
BaseMinimumVersion = null;
BaseMaximumVersion = null;
BaseRequiredVersion = null;
BaseGuid = null;
// See if it's one of the powershell module extensions...
if (!ModuleIntrinsics.IsPowerShellModuleExtension(extension))
{
// If the file exits, and it does not have a powershell module extension, we know for sure that the file is not a valid module
if (File.Exists(rootedPath))
{
PSInvalidOperationException invalidOperation = PSTraceSource.NewInvalidOperationException(
Modules.ManifestMemberNotValid,
moduleSpecification.Name,
"NestedModules",
parentModule.Path,
StringUtil.Format(Modules.InvalidModuleExtension, extension, moduleSpecification.Name),
ModuleIntrinsics.GetModuleName(parentModule.Path));
invalidOperation.SetErrorId("Modules_InvalidModuleExtension");
throw invalidOperation;
}
extension = null;
}
// Now load the module from the module directory first...
if (extension == null)
{
// No extension so we'll have to search using the extensions
//
if (VerifyIfNestedModuleIsAvailable(moduleSpecification, rootedPath, /*extension*/null, out tempModuleInfoFromVerification))
{
module = LoadUsingExtensions(
parentModule,
moduleSpecification.Name,
rootedPath, // fileBaseName
/*extension*/null,
moduleBase, // not using base from tempModuleInfoFromVerification as we are looking under moduleBase directory
prefix,
ss,
options,
manifestProcessingFlags,
out found,
out moduleFileFound);
}
// Win8: 262157 - Import-Module is giving errors while loading Nested Modules. (This is a V2 bug)
// NestedModules = 'test2' ---> test2 is a directory under current module directory (e.g - Test1)
// We also need to look for Test1\Test2\Test2.(psd1/psm1/dll)
// With the call above, we are only looking at Test1\Test2.(psd1/psm1/dll)
if (found == false && moduleFileFound == false)
{
string newRootedPath = Path.Combine(rootedPath, moduleSpecification.Name);
string newModuleBase = Path.Combine(moduleBase, moduleSpecification.Name);
if (VerifyIfNestedModuleIsAvailable(moduleSpecification, newRootedPath, /*extension*/null, out tempModuleInfoFromVerification))
{
module = LoadUsingExtensions(
parentModule,
moduleSpecification.Name,
fileBaseName: newRootedPath,
extension: null,
newModuleBase, // not using base from tempModuleInfoFromVerification as we are looking under moduleBase directory
prefix,
ss,
options,
manifestProcessingFlags,
out found,
out moduleFileFound);
}
}
}
else
{
// Ok - we have a complete file name so load that...
if (VerifyIfNestedModuleIsAvailable(moduleSpecification, rootedPath, extension, out tempModuleInfoFromVerification))
{
module = LoadModule(
parentModule,
rootedPath, // fileName
moduleBase, // not using base from tempModuleInfoFromVerification as we have a complete file name
prefix,
ss,
privateData,
ref options,
manifestProcessingFlags,
out found,
out moduleFileFound);
}
// Win8: 262157 - Import-Module is giving errors while loading Nested Modules. (This is a V2 bug)
// Only look for the file if the file was not found with the previous search
if (found == false && moduleFileFound == false)
{
string newRootedPath = Path.Combine(rootedPath, moduleSpecification.Name);
string newModuleBase = Path.Combine(moduleBase, moduleSpecification.Name);
if (VerifyIfNestedModuleIsAvailable(moduleSpecification, newRootedPath, extension, out tempModuleInfoFromVerification))
{
module = LoadModule(
parentModule,
newRootedPath, // fileName
newModuleBase, // not using base from tempModuleInfoFromVerification as we are looking under moduleBase directory
prefix,
ss,
privateData,
ref options,
manifestProcessingFlags,
out found,
out moduleFileFound);
}
}
}
// The rooted files wasn't found, so don't search anymore...
if (found == false && wasRooted == true)
return null;
if (searchModulePath && found == false && moduleFileFound == false)
{
if (VerifyIfNestedModuleIsAvailable(moduleSpecification, null, null, out tempModuleInfoFromVerification))
{
IEnumerable<string> modulePath = null;
if (tempModuleInfoFromVerification != null)
{
var subdirName = Path.GetFileName(tempModuleInfoFromVerification.ModuleBase);
Version version;
if (Version.TryParse(subdirName, out version))
{
var moduleBaseWithoutVersion = Path.GetDirectoryName(tempModuleInfoFromVerification.ModuleBase);
modulePath = new string[]
{
Path.GetDirectoryName(moduleBaseWithoutVersion),
moduleBaseWithoutVersion
};
}
else
{
modulePath = new string[]
{
Path.GetDirectoryName(tempModuleInfoFromVerification.ModuleBase),
tempModuleInfoFromVerification.ModuleBase
};
}
}
else
{
modulePath = ModuleIntrinsics.GetModulePath(false, this.Context);
}
// Otherwise try the module path
found = LoadUsingModulePath(parentModule, found, modulePath,
moduleSpecification.Name, ss,
options, manifestProcessingFlags, out module);
}
}
if (manifestLanguageMode.HasValue && found && (module != null) && module.LanguageMode.HasValue)
{
// Check for script module language mode consistency. All loaded script modules must have the same language mode as the manifest.
// If not then this indicates a malformed module and a possible exploit to make trusted private functions visible in a
// Constrained Language session.
if (module.LanguageMode != manifestLanguageMode)
{
var languageModeError = PSTraceSource.NewInvalidOperationException(
Modules.MismatchedLanguageModes,
module.Name, manifestLanguageMode, module.LanguageMode);
languageModeError.SetErrorId("Modules_MismatchedLanguageModes");
throw languageModeError;
}
}
// At this point, we haven't found an actual module, so try loading it as a
// PSSnapIn and then finally as an assembly in the GAC...
if ((found == false) && (moduleSpecification.Guid == null) && (moduleSpecification.Version == null) && (moduleSpecification.RequiredVersion == null) && (moduleSpecification.MaximumVersion == null))
{
// If we are in module analysis and the parent module declares non-wildcarded ExportedCmdlets, then we don't need to
// actually process the binary module.
bool shouldLoadModule = true;
if ((parentModule != null) && !importingModule)
{
if ((parentModule.ExportedCmdlets != null) && (parentModule.ExportedCmdlets.Count > 0))
{
shouldLoadModule = false;
foreach (string exportedCmdlet in parentModule.ExportedCmdlets.Keys)
{
if (WildcardPattern.ContainsWildcardCharacters(exportedCmdlet))
{
shouldLoadModule = true;
break;
}
}
found = true;
}
}
if (shouldLoadModule)
{
try
{
// At this point, we are already exhaust all possible ways to load the nested module. The last option is to load it as a binary module/snapin.
module = LoadBinaryModule(
parentModule,
true, // trySnapInName
moduleSpecification.Name,
null, // fileName
null, // assemblyToLoad
moduleBase,
ss,
options,
manifestProcessingFlags,
prefix,
loadTypesFiles,
loadFormatFiles,
out found,
shortModuleName, false);
}
catch (FileNotFoundException)
{
// Loading the nested module as a pssnapin or assembly is our last attempt to resolve the nested module.
// If we catch 'FileNotFoundException', it simply means that our last attempt failed because we couldn't find such a pssnapin or assembly.
// In this case, we can safely ignore this exception and throw a 'Modules_ModuleFileNotFound' error.
}
if ((module != null) && importingModule)
{
AddModuleToModuleTables(this.Context, this.TargetSessionState.Internal, module);
}
}
}
return module;
}
finally
{
BaseMinimumVersion = savedBaseMinimumVersion;
BaseMaximumVersion = savedBaseMaximumVersion;
BaseRequiredVersion = savedBaseRequiredVersion;
BaseGuid = savedBaseGuid;
this.Context.Modules.DecrementModuleNestingCount();
}
}
internal List<PSModuleInfo> GetModule(string[] names, bool all, bool refresh)
{
List<PSModuleInfo> modulesToReturn = new List<PSModuleInfo>();
// Two lists - one to hold Module Paths and one to hold Module Names
// For Module Paths, we don't do any path resolution
List<string> modulePaths = new List<string>();
List<string> moduleNames = new List<string>();
if (names != null)
{
foreach (var n in names)
{
if (n.IndexOf(StringLiterals.DefaultPathSeparator) != -1 || n.IndexOf(StringLiterals.AlternatePathSeparator) != -1)
{
modulePaths.Add(n);
}
else
{
moduleNames.Add(n);
}
}
modulesToReturn.AddRange(GetModuleForRootedPaths(modulePaths, all, refresh));
}
// If no names were passed to this function, then this API will return list of all available modules
if (names == null || moduleNames.Count > 0)
{
modulesToReturn.AddRange(GetModuleForNames(moduleNames, all, refresh));
}
return modulesToReturn;
}
private IEnumerable<PSModuleInfo> GetModuleForRootedPaths(List<string> modulePaths, bool all, bool refresh)
{
// This is to filter out duplicate modules
var modules = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string mp in modulePaths)
{
bool containsWildCards = false;
string modulePath = mp.TrimEnd(Utils.Separators.Backslash);
// If the given path contains wildcards, we won't throw error if no match module path is found.
if (WildcardPattern.ContainsWildcardCharacters(modulePath))
{
containsWildCards = true;
}
// Now we resolve the possible paths in case it is relative path/path contains wildcards
var modulePathCollection = GetResolvedPathCollection(modulePath, this.Context);
if (modulePathCollection != null)
{
foreach (string resolvedModulePath in modulePathCollection)
{
string moduleName = Path.GetFileName(resolvedModulePath);
// If the given path is a valid module file, we will load the specific file
if (!Directory.Exists(resolvedModulePath) && ModuleIntrinsics.IsPowerShellModuleExtension(Path.GetExtension(moduleName)))
{
PSModuleInfo module = CreateModuleInfoForGetModule(resolvedModulePath, refresh);
if (module != null)
{
if (!modules.Contains(resolvedModulePath))
{
modules.Add(resolvedModulePath);
yield return module;
}
}
}
else
{
// Given path is a directory, we first check if it is end with module version.
Version version;
if (Version.TryParse(moduleName, out version))
{
moduleName = Path.GetFileName(Directory.GetParent(resolvedModulePath).Name);
}
var availableModuleFiles = all
? ModuleUtils.GetAllAvailableModuleFiles(resolvedModulePath)
: ModuleUtils.GetModuleFilesFromAbsolutePath(resolvedModulePath);
bool foundModule = false;
foreach (string file in availableModuleFiles)
{
PSModuleInfo module = CreateModuleInfoForGetModule(file, refresh);
if (module != null)
{
if (string.Equals(moduleName, module.Name, StringComparison.OrdinalIgnoreCase))
{
foundModule = true;
// We need to list all versions of the module.
string subModulePath = Path.GetDirectoryName(file);
if (!modules.Contains(subModulePath))
{
modules.Add(subModulePath);
yield return module;
}