File size: 79,613 Bytes
8c763fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Automation.Configuration;
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Text;
using System.Threading;
using Microsoft.PowerShell.Commands;

using Dbg = System.Management.Automation.Diagnostics;

namespace System.Management.Automation
{
    internal static class Constants
    {
        public const string PSModulePathEnvVar = "PSModulePath";
    }

    /// <summary>
    /// Encapsulates the basic module operations for a PowerShell engine instance...
    /// </summary>
    public class ModuleIntrinsics
    {
        /// <summary>
        /// Tracer for module analysis.
        /// </summary>
        [TraceSource("Modules", "Module loading and analysis")]
        internal static readonly PSTraceSource Tracer = PSTraceSource.GetTracer("Modules", "Module loading and analysis");

        // The %WINDIR%\System32\WindowsPowerShell\v1.0\Modules module path,
        // to load forward compatible Windows PowerShell modules from
        private static readonly string s_windowsPowerShellPSHomeModulePath =
            Path.Combine(System.Environment.SystemDirectory, "WindowsPowerShell", "v1.0", "Modules");

        static ModuleIntrinsics()
        {
            // Initialize the module path.
            SetModulePath();
        }

        internal ModuleIntrinsics(ExecutionContext context)
        {
            _context = context;
            ModuleTable = new Dictionary<string, PSModuleInfo>(StringComparer.OrdinalIgnoreCase);
        }

        private readonly ExecutionContext _context;

        // Holds the module collection...
        internal Dictionary<string, PSModuleInfo> ModuleTable { get; }

        private const int MaxModuleNestingDepth = 10;

        internal void IncrementModuleNestingDepth(PSCmdlet cmdlet, string path)
        {
            if (++ModuleNestingDepth > MaxModuleNestingDepth)
            {
                string message = StringUtil.Format(Modules.ModuleTooDeeplyNested, path, MaxModuleNestingDepth);
                InvalidOperationException ioe = new InvalidOperationException(message);
                ErrorRecord er = new ErrorRecord(ioe, "Modules_ModuleTooDeeplyNested",
                    ErrorCategory.InvalidOperation, path);
                // NOTE: this call will throw
                cmdlet.ThrowTerminatingError(er);
            }
        }

        internal void DecrementModuleNestingCount()
        {
            --ModuleNestingDepth;
        }

        internal int ModuleNestingDepth { get; private set; }

        /// <summary>
        /// Create a new module object from a scriptblock specifying the path to set for the module.
        /// </summary>
        /// <param name="name">The name of the module.</param>
        /// <param name="path">The path where the module is rooted.</param>
        /// <param name="scriptBlock">
        /// ScriptBlock that is executed to initialize the module...
        /// </param>
        /// <param name="arguments">
        /// The arguments to pass to the scriptblock used to initialize the module
        /// </param>
        /// <param name="ss">The session state instance to use for this module - may be null.</param>
        /// <param name="results">The results produced from evaluating the scriptblock.</param>
        /// <returns>The newly created module info object.</returns>
        internal PSModuleInfo CreateModule(string name, string path, ScriptBlock scriptBlock, SessionState ss, out List<object> results, params object[] arguments)
        {
            return CreateModuleImplementation(name, path, scriptBlock, null, ss, null, out results, arguments);
        }

        /// <summary>
        /// Create a new module object from a ScriptInfo object.
        /// </summary>
        /// <param name="path">The path where the module is rooted.</param>
        /// <param name="scriptInfo">The script info to use to create the module.</param>
        /// <param name="scriptPosition">The position for the command that loaded this module.</param>
        /// <param name="arguments">Optional arguments to pass to the script while executing.</param>
        /// <param name="ss">The session state instance to use for this module - may be null.</param>
        /// <param name="privateData">The private data to use for this module - may be null.</param>
        /// <returns>The constructed module object.</returns>
        internal PSModuleInfo CreateModule(string path, ExternalScriptInfo scriptInfo, IScriptExtent scriptPosition, SessionState ss, object privateData, params object[] arguments)
        {
            List<object> result;
            return CreateModuleImplementation(ModuleIntrinsics.GetModuleName(path), path, scriptInfo, scriptPosition, ss, privateData, out result, arguments);
        }

        /// <summary>
        /// Create a new module object from code specifying the path to set for the module.
        /// </summary>
        /// <param name="name">The name of the module.</param>
        /// <param name="path">The path to use for the module root.</param>
        /// <param name="moduleCode">
        /// The code to use to create the module. This can be one of ScriptBlock, string
        /// or ExternalScriptInfo
        /// </param>
        /// <param name="arguments">
        /// Arguments to pass to the module scriptblock during evaluation.
        /// </param>
        /// <param name="result">
        /// The results of the evaluation of the scriptblock.
        /// </param>
        /// <param name="scriptPosition">
        /// The position of the caller of this function so you can tell where the call
        /// to Import-Module (or whatever) occurred. This can be null.
        /// </param>
        /// <param name="ss">The session state instance to use for this module - may be null.</param>
        /// <param name="privateData">The private data to use for this module - may be null.</param>
        /// <returns>The created module.</returns>
        private PSModuleInfo CreateModuleImplementation(string name, string path, object moduleCode, IScriptExtent scriptPosition, SessionState ss, object privateData, out List<object> result, params object[] arguments)
        {
            ScriptBlock sb;

            // By default the top-level scope in a session state object is the global scope for the instance.
            // For modules, we need to set its global scope to be another scope object and, chain the top
            // level scope for this sessionstate instance to be the parent. The top level scope for this ss is the
            // script scope for the ss.

            // Allocate the session state instance for this module.
            ss ??= new SessionState(_context, true, true);

            // Now set up the module's session state to be the current session state
            SessionStateInternal oldSessionState = _context.EngineSessionState;
            PSModuleInfo module = new PSModuleInfo(name, path, _context, ss);
            ss.Internal.Module = module;
            module.PrivateData = privateData;

            bool setExitCode = false;
            int exitCode = 0;

            try
            {
                _context.EngineSessionState = ss.Internal;

                // Build the scriptblock at this point so the references to the module
                // context are correct...
                ExternalScriptInfo scriptInfo = moduleCode as ExternalScriptInfo;
                if (scriptInfo != null)
                {
                    sb = scriptInfo.ScriptBlock;

                    _context.Debugger.RegisterScriptFile(scriptInfo);
                }
                else
                {
                    sb = moduleCode as ScriptBlock;
                    if (sb != null)
                    {
                        PSLanguageMode? moduleLanguageMode = sb.LanguageMode;
                        sb = sb.Clone();
                        sb.LanguageMode = moduleLanguageMode;

                        sb.SessionState = ss;
                    }
                    else if (moduleCode is string sbText)
                    {
                        sb = ScriptBlock.Create(_context, sbText);
                    }
                }

                if (sb == null)
                    throw PSTraceSource.NewInvalidOperationException();

                sb.SessionStateInternal = ss.Internal;
                module.LanguageMode = sb.LanguageMode;

                InvocationInfo invocationInfo = new InvocationInfo(scriptInfo, scriptPosition);

                // Save the module string
                module._definitionExtent = sb.Ast.Extent;
                var ast = sb.Ast;
                while (ast.Parent != null)
                {
                    ast = ast.Parent;
                }

                // The variables set in the interpreted case get set by InvokeWithPipe in the compiled case.
                Diagnostics.Assert(_context.SessionState.Internal.CurrentScope.LocalsTuple == null,
                                    "No locals tuple should have been created yet.");

                List<object> resultList = new List<object>();

                try
                {
                    Pipe outputPipe = new Pipe(resultList);

                    // And run the scriptblock...
                    sb.InvokeWithPipe(
                        useLocalScope: false,
                        errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe,
                        dollarUnder: AutomationNull.Value,
                        input: AutomationNull.Value,
                        scriptThis: AutomationNull.Value,
                        outputPipe: outputPipe,
                        invocationInfo: invocationInfo,
                        args: arguments ?? Array.Empty<object>());
                }
                catch (ExitException ee)
                {
                    exitCode = (int)ee.Argument;
                    setExitCode = true;
                }

                result = resultList;
            }
            finally
            {
                _context.EngineSessionState = oldSessionState;
            }

            if (setExitCode)
            {
                _context.SetVariable(SpecialVariables.LastExitCodeVarPath, exitCode);
            }

            module.ImplementingAssembly = sb.AssemblyDefiningPSTypes;
            // We force re-population of ExportedTypeDefinitions, now with the actual RuntimeTypes, created above.
            module.CreateExportedTypeDefinitions(sb.Ast as ScriptBlockAst);

            return module;
        }

        /// <summary>
        /// Allocate a new dynamic module then return a new scriptblock
        /// bound to the module instance.
        /// </summary>
        /// <param name="context">Context to use to create bounded script.</param>
        /// <param name="sb">The scriptblock to bind.</param>
        /// <param name="linkToGlobal">Whether it should be linked to the global session state or not.</param>
        /// <returns>A new scriptblock.</returns>
        internal ScriptBlock CreateBoundScriptBlock(ExecutionContext context, ScriptBlock sb, bool linkToGlobal)
        {
            PSModuleInfo module = new PSModuleInfo(context, linkToGlobal);
            return module.NewBoundScriptBlock(sb, context);
        }

        internal List<PSModuleInfo> GetModules(string[] patterns, bool all)
        {
            return GetModuleCore(patterns, all, false);
        }

        internal List<PSModuleInfo> GetExactMatchModules(string moduleName, bool all, bool exactMatch)
        {
            moduleName ??= string.Empty;

            return GetModuleCore(new string[] { moduleName }, all, exactMatch);
        }

        private List<PSModuleInfo> GetModuleCore(string[] patterns, bool all, bool exactMatch)
        {
            string targetModuleName = null;
            List<WildcardPattern> wcpList = new List<WildcardPattern>();

            if (exactMatch)
            {
                Dbg.Assert(patterns.Length == 1, "The 'patterns' should only contain one element when it is for an exact match");
                targetModuleName = patterns[0];
            }
            else
            {
                patterns ??= new string[] { "*" };

                foreach (string pattern in patterns)
                {
                    wcpList.Add(WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase));
                }
            }

            List<PSModuleInfo> modulesMatched = new List<PSModuleInfo>();

            if (all)
            {
                foreach (PSModuleInfo module in ModuleTable.Values)
                {
                    // See if this is the requested module...
                    if ((exactMatch && module.Name.Equals(targetModuleName, StringComparison.OrdinalIgnoreCase)) ||
                        (!exactMatch && SessionStateUtilities.MatchesAnyWildcardPattern(module.Name, wcpList, false)))
                    {
                        modulesMatched.Add(module);
                    }
                }
            }
            else
            {
                // Create a joint list of local and global modules. Only report a module once.
                // Local modules are reported before global modules...
                Dictionary<string, bool> found = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
                foreach (var pair in _context.EngineSessionState.ModuleTable)
                {
                    string path = pair.Key;
                    PSModuleInfo module = pair.Value;
                    // See if this is the requested module...
                    if ((exactMatch && module.Name.Equals(targetModuleName, StringComparison.OrdinalIgnoreCase)) ||
                        (!exactMatch && SessionStateUtilities.MatchesAnyWildcardPattern(module.Name, wcpList, false)))
                    {
                        modulesMatched.Add(module);
                        found[path] = true;
                    }
                }

                if (_context.EngineSessionState != _context.TopLevelSessionState)
                {
                    foreach (var pair in _context.TopLevelSessionState.ModuleTable)
                    {
                        string path = pair.Key;
                        if (!found.ContainsKey(path))
                        {
                            PSModuleInfo module = pair.Value;
                            // See if this is the requested module...
                            if ((exactMatch && module.Name.Equals(targetModuleName, StringComparison.OrdinalIgnoreCase)) ||
                                (!exactMatch && SessionStateUtilities.MatchesAnyWildcardPattern(module.Name, wcpList, false)))
                            {
                                modulesMatched.Add(module);
                            }
                        }
                    }
                }
            }

            return modulesMatched.OrderBy(static m => m.Name).ToList();
        }

        internal List<PSModuleInfo> GetModules(ModuleSpecification[] fullyQualifiedName, bool all)
        {
            List<PSModuleInfo> modulesMatched = new List<PSModuleInfo>();

            if (all)
            {
                foreach (var moduleSpec in fullyQualifiedName)
                {
                    foreach (PSModuleInfo module in ModuleTable.Values)
                    {
                        // See if this is the requested module...
                        if (IsModuleMatchingModuleSpec(module, moduleSpec))
                        {
                            modulesMatched.Add(module);
                        }
                    }
                }
            }
            else
            {
                foreach (var moduleSpec in fullyQualifiedName)
                {
                    // Create a joint list of local and global modules. Only report a module once.
                    // Local modules are reported before global modules...
                    Dictionary<string, bool> found = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
                    foreach (var pair in _context.EngineSessionState.ModuleTable)
                    {
                        string path = pair.Key;
                        PSModuleInfo module = pair.Value;
                        // See if this is the requested module...
                        if (IsModuleMatchingModuleSpec(module, moduleSpec))
                        {
                            modulesMatched.Add(module);
                            found[path] = true;
                        }
                    }

                    if (_context.EngineSessionState != _context.TopLevelSessionState)
                    {
                        foreach (var pair in _context.TopLevelSessionState.ModuleTable)
                        {
                            string path = pair.Key;
                            if (!found.ContainsKey(path))
                            {
                                PSModuleInfo module = pair.Value;
                                // See if this is the requested module...
                                if (IsModuleMatchingModuleSpec(module, moduleSpec))
                                {
                                    modulesMatched.Add(module);
                                }
                            }
                        }
                    }
                }
            }

            return modulesMatched.OrderBy(static m => m.Name).ToList();
        }

        /// <summary>
        /// Check if a given module info object matches a given module specification.
        /// </summary>
        /// <param name="moduleInfo">The module info object to check.</param>
        /// <param name="moduleSpec">The module specification to match the module info object against.</param>
        /// <param name="skipNameCheck">True if we should skip the name check on the module specification.</param>
        /// <returns>True if the module info object meets all the constraints on the module specification, false otherwise.</returns>
        internal static bool IsModuleMatchingModuleSpec(
            PSModuleInfo moduleInfo,
            ModuleSpecification moduleSpec,
            bool skipNameCheck = false)
        {
            return IsModuleMatchingModuleSpec(out ModuleMatchFailure matchFailureReason, moduleInfo, moduleSpec, skipNameCheck);
        }

        /// <summary>
        /// Check if a given module info object matches a given module specification.
        /// </summary>
        /// <param name="matchFailureReason">The constraint that caused the match failure, if any.</param>
        /// <param name="moduleInfo">The module info object to check.</param>
        /// <param name="moduleSpec">The module specification to match the module info object against.</param>
        /// <param name="skipNameCheck">True if we should skip the name check on the module specification.</param>
        /// <returns>True if the module info object meets all the constraints on the module specification, false otherwise.</returns>
        internal static bool IsModuleMatchingModuleSpec(
            out ModuleMatchFailure matchFailureReason,
            PSModuleInfo moduleInfo,
            ModuleSpecification moduleSpec,
            bool skipNameCheck = false)
        {
            if (moduleSpec == null)
            {
                matchFailureReason = ModuleMatchFailure.NullModuleSpecification;
                return false;
            }

            return IsModuleMatchingConstraints(
                out matchFailureReason,
                moduleInfo,
                skipNameCheck ? null : moduleSpec.Name,
                moduleSpec.Guid,
                moduleSpec.RequiredVersion,
                moduleSpec.Version,
                moduleSpec.MaximumVersion == null ? null : ModuleCmdletBase.GetMaximumVersion(moduleSpec.MaximumVersion));
        }

        /// <summary>
        /// Check if a given module info object matches the given constraints.
        /// Constraints given as null are ignored.
        /// </summary>
        /// <param name="moduleInfo">The module info object to check.</param>
        /// <param name="name">The name or normalized absolute path of the expected module.</param>
        /// <param name="guid">The guid of the expected module.</param>
        /// <param name="requiredVersion">The required version of the expected module.</param>
        /// <param name="minimumVersion">The minimum required version of the expected module.</param>
        /// <param name="maximumVersion">The maximum required version of the expected module.</param>
        /// <returns>True if the module info object matches all given constraints, false otherwise.</returns>
        internal static bool IsModuleMatchingConstraints(
            PSModuleInfo moduleInfo,
            string name = null,
            Guid? guid = null,
            Version requiredVersion = null,
            Version minimumVersion = null,
            Version maximumVersion = null)
        {
            return IsModuleMatchingConstraints(
                out ModuleMatchFailure matchFailureReason,
                moduleInfo,
                name,
                guid,
                requiredVersion,
                minimumVersion,
                maximumVersion);
        }

        /// <summary>
        /// Check if a given module info object matches the given constraints.
        /// Constraints given as null are ignored.
        /// </summary>
        /// <param name="matchFailureReason">The reason for the module constraint match failing.</param>
        /// <param name="moduleInfo">The module info object to check.</param>
        /// <param name="name">The name or normalized absolute path of the expected module.</param>
        /// <param name="guid">The guid of the expected module.</param>
        /// <param name="requiredVersion">The required version of the expected module.</param>
        /// <param name="minimumVersion">The minimum required version of the expected module.</param>
        /// <param name="maximumVersion">The maximum required version of the expected module.</param>
        /// <returns>True if the module info object matches all given constraints, false otherwise.</returns>
        internal static bool IsModuleMatchingConstraints(
            out ModuleMatchFailure matchFailureReason,
            PSModuleInfo moduleInfo,
            string name,
            Guid? guid,
            Version requiredVersion,
            Version minimumVersion,
            Version maximumVersion)
        {
            // Define that a null module does not meet any constraints
            if (moduleInfo == null)
            {
                matchFailureReason = ModuleMatchFailure.NullModule;
                return false;
            }

            return AreModuleFieldsMatchingConstraints(
                out matchFailureReason,
                moduleInfo.Name,
                moduleInfo.Path,
                moduleInfo.Guid,
                moduleInfo.Version,
                name,
                guid,
                requiredVersion,
                minimumVersion,
                maximumVersion
            );
        }

        /// <summary>
        /// Check that given module fields meet any given constraints.
        /// </summary>
        /// <param name="moduleName">The name of the module to check.</param>
        /// <param name="modulePath">The path of the module to check.</param>
        /// <param name="moduleGuid">The GUID of the module to check.</param>
        /// <param name="moduleVersion">The version of the module to check.</param>
        /// <param name="requiredName">The name or normalized absolute path the module must have, if any.</param>
        /// <param name="requiredGuid">The GUID the module must have, if any.</param>
        /// <param name="requiredVersion">The exact version the module must have, if any.</param>
        /// <param name="minimumRequiredVersion">The minimum version the module may have, if any.</param>
        /// <param name="maximumRequiredVersion">The maximum version the module may have, if any.</param>
        /// <returns>True if the module parameters match all given constraints, false otherwise.</returns>
        internal static bool AreModuleFieldsMatchingConstraints(
            string moduleName = null,
            string modulePath = null,
            Guid? moduleGuid = null,
            Version moduleVersion = null,
            string requiredName = null,
            Guid? requiredGuid = null,
            Version requiredVersion = null,
            Version minimumRequiredVersion = null,
            Version maximumRequiredVersion = null)
        {
            return AreModuleFieldsMatchingConstraints(
                out ModuleMatchFailure matchFailureReason,
                moduleName,
                modulePath,
                moduleGuid,
                moduleVersion,
                requiredName,
                requiredGuid,
                requiredVersion,
                minimumRequiredVersion,
                maximumRequiredVersion);
        }

        /// <summary>
        /// Check that given module fields meet any given constraints.
        /// </summary>
        /// <param name="matchFailureReason">The reason the match failed, if any.</param>
        /// <param name="moduleName">The name of the module to check.</param>
        /// <param name="modulePath">The path of the module to check.</param>
        /// <param name="moduleGuid">The GUID of the module to check.</param>
        /// <param name="moduleVersion">The version of the module to check.</param>
        /// <param name="requiredName">The name or normalized absolute path the module must have, if any.</param>
        /// <param name="requiredGuid">The GUID the module must have, if any.</param>
        /// <param name="requiredVersion">The exact version the module must have, if any.</param>
        /// <param name="minimumRequiredVersion">The minimum version the module may have, if any.</param>
        /// <param name="maximumRequiredVersion">The maximum version the module may have, if any.</param>
        /// <returns>True if the module parameters match all given constraints, false otherwise.</returns>
        internal static bool AreModuleFieldsMatchingConstraints(
            out ModuleMatchFailure matchFailureReason,
            string moduleName,
            string modulePath,
            Guid? moduleGuid,
            Version moduleVersion,
            string requiredName,
            Guid? requiredGuid,
            Version requiredVersion,
            Version minimumRequiredVersion,
            Version maximumRequiredVersion)
        {
            // If a name is required, check that it matches.
            // A required module name may also be an absolute path, so check it against the given module's path as well.
            if (requiredName != null
                && !requiredName.Equals(moduleName, StringComparison.OrdinalIgnoreCase)
                && !MatchesModulePath(modulePath, requiredName))
            {
                matchFailureReason = ModuleMatchFailure.Name;
                return false;
            }

            // If a GUID is required, check it matches
            if (requiredGuid != null && !requiredGuid.Equals(moduleGuid))
            {
                matchFailureReason = ModuleMatchFailure.Guid;
                return false;
            }

            // Check the versions
            return IsVersionMatchingConstraints(out matchFailureReason, moduleVersion, requiredVersion, minimumRequiredVersion, maximumRequiredVersion);
        }

        /// <summary>
        /// Check that a given module version matches the required or minimum/maximum version constraints.
        /// Null constraints are not checked.
        /// </summary>
        /// <param name="version">The module version to check. Must not be null.</param>
        /// <param name="requiredVersion">The version that the given version must be, if not null.</param>
        /// <param name="minimumVersion">The minimum version that the given version must be greater than or equal to, if not null.</param>
        /// <param name="maximumVersion">The maximum version that the given version must be less then or equal to, if not null.</param>
        /// <returns>
        /// True if the version matches the required version, or if it is absent, is between the minimum and maximum versions, and false otherwise.
        /// </returns>
        internal static bool IsVersionMatchingConstraints(
            Version version,
            Version requiredVersion = null,
            Version minimumVersion = null,
            Version maximumVersion = null)
        {
            return IsVersionMatchingConstraints(out ModuleMatchFailure matchFailureReason, version, requiredVersion, minimumVersion, maximumVersion);
        }

        /// <summary>
        /// Check that a given module version matches the required or minimum/maximum version constraints.
        /// Null constraints are not checked.
        /// </summary>
        /// <param name="matchFailureReason">The reason why the match failed.</param>
        /// <param name="version">The module version to check. Must not be null.</param>
        /// <param name="requiredVersion">The version that the given version must be, if not null.</param>
        /// <param name="minimumVersion">The minimum version that the given version must be greater than or equal to, if not null.</param>
        /// <param name="maximumVersion">The maximum version that the given version must be less then or equal to, if not null.</param>
        /// <returns>
        /// True if the version matches the required version, or if it is absent, is between the minimum and maximum versions, and false otherwise.
        /// </returns>
        internal static bool IsVersionMatchingConstraints(
            out ModuleMatchFailure matchFailureReason,
            Version version,
            Version requiredVersion = null,
            Version minimumVersion = null,
            Version maximumVersion = null)
        {
            Dbg.Assert(version != null, $"Caller to verify that {nameof(version)} is not null");

            // If a RequiredVersion is given it overrides other version settings
            if (requiredVersion != null)
            {
                matchFailureReason = ModuleMatchFailure.RequiredVersion;
                return requiredVersion.Equals(version);
            }

            // Check the version is at least the minimum version
            if (minimumVersion != null && version < minimumVersion)
            {
                matchFailureReason = ModuleMatchFailure.MinimumVersion;
                return false;
            }

            // Check the version is at most the maximum version
            if (maximumVersion != null && version > maximumVersion)
            {
                matchFailureReason = ModuleMatchFailure.MaximumVersion;
                return false;
            }

            matchFailureReason = ModuleMatchFailure.None;
            return true;
        }

        /// <summary>
        /// Checks whether a given module path is the same as
        /// a required path.
        /// </summary>
        /// <param name="modulePath">The path of the module whose path to check. This must be the path to the module file (.psd1, .psm1, .dll, etc).</param>
        /// <param name="requiredPath">The path of the required module. This may be the module directory path or the file path. Only normalized absolute paths will work for this.</param>
        /// <returns>True if the module path matches the required path, false otherwise.</returns>
        internal static bool MatchesModulePath(string modulePath, string requiredPath)
        {
            Dbg.Assert(requiredPath != null, $"Caller to verify that {nameof(requiredPath)} is not null");

            if (modulePath == null)
            {
                return false;
            }

#if UNIX
            const StringComparison strcmp = StringComparison.Ordinal;
#else
            const StringComparison strcmp = StringComparison.OrdinalIgnoreCase;
#endif

            // We must check modulePath (e.g. /path/to/module/module.psd1) against several possibilities:
            // 1. "/path/to/module"                 - Module dir path
            // 2. "/path/to/module/module.psd1"     - Module root file path
            // 3. "/path/to/module/2.1/module.psd1" - Versioned module path

            // If the required module just matches the module path (case 1), we are done
            if (modulePath.Equals(requiredPath, strcmp))
            {
                return true;
            }

            // At this point we are looking for the module directory (case 2 or 3).
            // We can some allocations here if module path doesn't sit under the required path
            // (the required path may still refer to some nested module though)
            if (!modulePath.StartsWith(requiredPath, strcmp))
            {
                return false;
            }

            string moduleDirPath = Path.GetDirectoryName(modulePath);

            // The module itself may be in a versioned directory (case 3)
            if (Version.TryParse(Path.GetFileName(moduleDirPath), out _))
            {
                moduleDirPath = Path.GetDirectoryName(moduleDirPath);
            }

            return moduleDirPath.Equals(requiredPath, strcmp);
        }

        /// <summary>
        /// Takes the name of a module as used in a module specification
        /// and either returns it as a simple name (if it was a simple name)
        /// or a fully qualified, PowerShell-resolved path.
        /// </summary>
        /// <param name="moduleName">The name or path of the module from the specification.</param>
        /// <param name="basePath">The path to base relative paths off.</param>
        /// <param name="executionContext">The current execution context.</param>
        /// <returns>
        /// The simple module name if the given one was simple,
        /// otherwise a fully resolved, absolute path to the module.
        /// </returns>
        /// <remarks>
        /// 2018-11-09 rjmholt:
        /// There are several, possibly inconsistent, path handling mechanisms
        /// in the module cmdlets. After looking through all of them and seeing
        /// they all make some assumptions about their caller I wrote this method.
        /// Hopefully we can find a standard path resolution API to settle on.
        /// </remarks>
        internal static string NormalizeModuleName(
            string moduleName,
            string basePath,
            ExecutionContext executionContext)
        {
            if (moduleName == null)
            {
                return null;
            }

            // Check whether the module is a path -- if not, it is a simple name and we just return it.
            if (!IsModuleNamePath(moduleName))
            {
                return moduleName;
            }

            // Standardize directory separators -- Path.IsPathRooted() will return false for "\path\here" on *nix and for "/path/there" on Windows
            moduleName = moduleName.Replace(StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator);

            // Note: Path.IsFullyQualified("\default\root") is false on Windows, but Path.IsPathRooted returns true
            if (!Path.IsPathRooted(moduleName))
            {
                moduleName = Path.Join(basePath, moduleName);
            }

            // Use the PowerShell filesystem provider to fully resolve the path
            // If there is a problem, null could be returned -- so default back to the pre-normalized path
            string normalizedPath = ModuleCmdletBase.GetResolvedPath(moduleName, executionContext)?.TrimEnd(StringLiterals.DefaultPathSeparator);

            // ModuleCmdletBase.GetResolvePath will return null in the unlikely event that it failed.
            // If it does, we return the fully qualified path generated before.
            return normalizedPath ?? Path.GetFullPath(moduleName);
        }

        /// <summary>
        /// Check if a given module name is a path to a module rather than a simple name.
        /// </summary>
        /// <param name="moduleName">The module name to check.</param>
        /// <returns>True if the module name is a path, false otherwise.</returns>
        internal static bool IsModuleNamePath(string moduleName)
        {
            return moduleName.Contains(StringLiterals.DefaultPathSeparator)
                || moduleName.Contains(StringLiterals.AlternatePathSeparator)
                || moduleName.Equals("..")
                || moduleName.Equals(".");
        }

        internal static Version GetManifestModuleVersion(string manifestPath)
        {
            try
            {
                Hashtable dataFileSetting =
                    PsUtils.GetModuleManifestProperties(
                        manifestPath,
                        PsUtils.ManifestModuleVersionPropertyName);

                object versionValue = dataFileSetting["ModuleVersion"];
                if (versionValue != null)
                {
                    Version moduleVersion;
                    if (LanguagePrimitives.TryConvertTo(versionValue, out moduleVersion))
                    {
                        return moduleVersion;
                    }
                }
            }
            catch (PSInvalidOperationException) { }

            return new Version(0, 0);
        }

        internal static Guid GetManifestGuid(string manifestPath)
        {
            try
            {
                Hashtable dataFileSetting =
                    PsUtils.GetModuleManifestProperties(
                        manifestPath,
                        PsUtils.ManifestGuidPropertyName);

                object guidValue = dataFileSetting["GUID"];
                if (guidValue != null)
                {
                    Guid guidID;
                    if (LanguagePrimitives.TryConvertTo(guidValue, out guidID))
                    {
                        return guidID;
                    }
                }
            }
            catch (PSInvalidOperationException) { }

            return new Guid();
        }

        internal static ExperimentalFeature[] GetExperimentalFeature(string manifestPath)
        {
            try
            {
                Hashtable dataFileSetting =
                    PsUtils.GetModuleManifestProperties(
                        manifestPath,
                        PsUtils.ManifestPrivateDataPropertyName);

                object privateData = dataFileSetting["PrivateData"];
                if (privateData is Hashtable hashData && hashData["PSData"] is Hashtable psData)
                {
                    object expFeatureValue = psData["ExperimentalFeatures"];
                    if (expFeatureValue != null &&
                        LanguagePrimitives.TryConvertTo(expFeatureValue, out Hashtable[] features) &&
                        features.Length > 0)
                    {
                        string moduleName = ModuleIntrinsics.GetModuleName(manifestPath);
                        var expFeatureList = new List<ExperimentalFeature>();
                        foreach (Hashtable feature in features)
                        {
                            string featureName = feature["Name"] as string;
                            if (string.IsNullOrEmpty(featureName))
                            {
                                continue;
                            }

                            if (ExperimentalFeature.IsModuleFeatureName(featureName, moduleName))
                            {
                                string featureDescription = feature["Description"] as string;
                                expFeatureList.Add(new ExperimentalFeature(featureName, featureDescription, manifestPath,
                                                                           ExperimentalFeature.IsEnabled(featureName)));
                            }
                        }

                        return expFeatureList.ToArray();
                    }
                }
            }
            catch (PSInvalidOperationException) { }

            return Array.Empty<ExperimentalFeature>();
        }

        // The extensions of all of the files that can be processed with Import-Module, put the ni.dll in front of .dll to have higher priority to be loaded.
        internal static readonly string[] PSModuleProcessableExtensions = new string[]
        {
            StringLiterals.PowerShellDataFileExtension,
            StringLiterals.PowerShellScriptFileExtension,
            StringLiterals.PowerShellModuleFileExtension,
            StringLiterals.PowerShellCmdletizationFileExtension,
            StringLiterals.PowerShellNgenAssemblyExtension,
            StringLiterals.PowerShellILAssemblyExtension,
            StringLiterals.PowerShellILExecutableExtension,
        };

        // A list of the extensions to check for implicit module loading and discovery, put the ni.dll in front of .dll to have higher priority to be loaded.
        internal static readonly string[] PSModuleExtensions = new string[]
        {
            StringLiterals.PowerShellDataFileExtension,
            StringLiterals.PowerShellModuleFileExtension,
            StringLiterals.PowerShellCmdletizationFileExtension,
            StringLiterals.PowerShellNgenAssemblyExtension,
            StringLiterals.PowerShellILAssemblyExtension,
            StringLiterals.PowerShellILExecutableExtension,
        };

        // A list of the extensions to check for required assemblies.
        internal static readonly string[] ProcessableAssemblyExtensions = new string[]
        {
            StringLiterals.PowerShellNgenAssemblyExtension,
            StringLiterals.PowerShellILAssemblyExtension,
            StringLiterals.PowerShellILExecutableExtension
        };

        /// <summary>
        /// Returns true if the extension is one of the module extensions...
        /// </summary>
        /// <param name="extension">The extension to check.</param>
        /// <returns>True if it was a module extension...</returns>
        internal static bool IsPowerShellModuleExtension(string extension)
        {
            foreach (string ext in PSModuleProcessableExtensions)
            {
                if (extension.Equals(ext, StringComparison.OrdinalIgnoreCase))
                {
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// Gets the module name from module path.
        /// </summary>
        /// <param name="path">The path to the module.</param>
        /// <returns>The module name.</returns>
        internal static string GetModuleName(string path)
        {
            string fileName = path == null ? string.Empty : Path.GetFileName(path);
            string ext;
            if (fileName.EndsWith(StringLiterals.PowerShellNgenAssemblyExtension, StringComparison.OrdinalIgnoreCase))
            {
                ext = StringLiterals.PowerShellNgenAssemblyExtension;
            }
            else
            {
                ext = Path.GetExtension(fileName);
            }

            if (!string.IsNullOrEmpty(ext) && IsPowerShellModuleExtension(ext))
            {
                return fileName.Substring(0, fileName.Length - ext.Length);
            }
            else
            {
                return fileName;
            }
        }

        /// <summary>
        /// Gets the personal module path.
        /// </summary>
        /// <returns>Personal module path.</returns>
        internal static string GetPersonalModulePath()
        {
#if UNIX
            return Platform.SelectProductNameForDirectory(Platform.XDG_Type.USER_MODULES);
#else
            string myDocumentsPath = InternalTestHooks.SetMyDocumentsSpecialFolderToBlank ? string.Empty : Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            return string.IsNullOrEmpty(myDocumentsPath) ? null : Path.Combine(myDocumentsPath, Utils.ModuleDirectory);
#endif
        }

        /// <summary>
        /// Gets the PSHome module path, as known as the "system wide module path" in windows powershell.
        /// </summary>
        /// <returns>The PSHome module path.</returns>
        internal static string GetPSHomeModulePath()
        {
            if (s_psHomeModulePath != null)
            {
                return s_psHomeModulePath;
            }

            try
            {
                string psHome = Utils.DefaultPowerShellAppBase;
#if !UNIX
                // Win8: 584267 Powershell Modules are listed twice in x86, and cannot be removed.
                // This happens because 'ModuleTable' uses Path as the key and x86 WinPS has "SysWOW64" in its $PSHOME.
                // Because of this, the module that is getting loaded during startup (through LocalRunspace) is using
                // "SysWow64" in the key. Later, when 'Import-Module' is called, it loads the module using ""System32"
                // in the key.
                // For the cross-platform PowerShell, a user can choose to install it under "C:\Windows\SysWOW64", and
                // thus it may have the same problem as described above. So we keep this line of code.
                psHome = psHome.ToLowerInvariant().Replace(@"\syswow64\", @"\system32\");
#endif
                Interlocked.CompareExchange(ref s_psHomeModulePath, Path.Combine(psHome, "Modules"), null);
            }
            catch (System.Security.SecurityException)
            {
            }

            return s_psHomeModulePath;
        }

        private static string s_psHomeModulePath;

        /// <summary>
        /// Get the module path that is shared among different users.
        /// It's known as "Program Files" module path in windows powershell.
        /// </summary>
        /// <returns></returns>
        internal static string GetSharedModulePath()
        {
#if UNIX
            return Platform.SelectProductNameForDirectory(Platform.XDG_Type.SHARED_MODULES);
#else
            string sharedModulePath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);

            if (!string.IsNullOrEmpty(sharedModulePath))
            {
                sharedModulePath = Path.Combine(sharedModulePath, Utils.ModuleDirectory);
            }

            return sharedModulePath;
#endif
        }

#if !UNIX
        /// <summary>
        /// Get the path to the Windows PowerShell module directory under the
        /// System32 directory on Windows (the Windows PowerShell $PSHOME).
        /// </summary>
        /// <returns>The path of the Windows PowerShell system module directory.</returns>
        internal static string GetWindowsPowerShellPSHomeModulePath()
        {
            if (!string.IsNullOrEmpty(InternalTestHooks.TestWindowsPowerShellPSHomeLocation))
            {
                return InternalTestHooks.TestWindowsPowerShellPSHomeLocation;
            }

            return s_windowsPowerShellPSHomeModulePath;
        }
#endif

        /// <summary>
        /// Combine the PS system-wide module path and the DSC module path
        /// to get the system module paths.
        /// </summary>
        /// <returns></returns>
        private static string CombineSystemModulePaths()
        {
            string psHomeModulePath = GetPSHomeModulePath();
            string sharedModulePath = GetSharedModulePath();

            bool isPSHomePathNullOrEmpty = string.IsNullOrEmpty(psHomeModulePath);
            bool isSharedPathNullOrEmpty = string.IsNullOrEmpty(sharedModulePath);

            if (!isPSHomePathNullOrEmpty && !isSharedPathNullOrEmpty)
            {
                return (sharedModulePath + Path.PathSeparator + psHomeModulePath);
            }

            if (!isPSHomePathNullOrEmpty || !isSharedPathNullOrEmpty)
            {
                return isPSHomePathNullOrEmpty ? sharedModulePath : psHomeModulePath;
            }

            return null;
        }

        internal static string GetExpandedEnvironmentVariable(string name, EnvironmentVariableTarget target)
        {
            string result = Environment.GetEnvironmentVariable(name, target);
            if (!string.IsNullOrEmpty(result))
            {
                result = Environment.ExpandEnvironmentVariables(result);
            }

            return result;
        }

        /// <summary>
        /// Adds paths to a 'combined path' string (like %Path% or %PSModulePath%) if they are not already there.
        /// </summary>
        /// <param name="basePath">Path string (like %Path% or %PSModulePath%).</param>
        /// <param name="pathToAdd">An individual path to add, or multiple paths separated by the path separator character.</param>
        /// <param name="insertPosition">-1 to append to the end; 0 to insert in the beginning of the string; etc...</param>
        /// <returns>Result string.</returns>
        private static string UpdatePath(string basePath, string pathToAdd, ref int insertPosition)
        {
            // we don't support if any of the args are null - parent function should ensure this; empty values are ok
            Dbg.Assert(basePath != null, "basePath should not be null according to contract of the function");
            Dbg.Assert(pathToAdd != null, "pathToAdd should not be null according to contract of the function");

            // The 'pathToAdd' could be a 'combined path' (path-separator-separated).
            string[] newPaths = pathToAdd.Split(
                Path.PathSeparator,
                StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);

            if (newPaths.Length is 0)
            {
                // The 'pathToAdd' doesn't really contain any paths to add.
                return basePath;
            }

            var result = new StringBuilder(basePath, capacity: basePath.Length + pathToAdd.Length + newPaths.Length);
            var addedPaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            string[] initialPaths = basePath.Split(
                Path.PathSeparator,
                StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);

            foreach (string p in initialPaths)
            {
                // Remove the trailing directory separators.
                // Trailing white spaces were already removed by 'StringSplitOptions.TrimEntries'.
                addedPaths.Add(Path.TrimEndingDirectorySeparator(p));
            }

            foreach (string subPathToAdd in newPaths)
            {
                // Remove the trailing directory separators.
                // Trailing white spaces were already removed by 'StringSplitOptions.TrimEntries'.
                string normalizedPath = Path.TrimEndingDirectorySeparator(subPathToAdd);
                if (addedPaths.Contains(normalizedPath))
                {
                    // The normalized sub path was already added - skip it.
                    continue;
                }

                // The normalized sub path was not found - add it.
                if (insertPosition is -1 || insertPosition >= result.Length)
                {
                    // Append the normalized sub path to the end.
                    if (result.Length > 0 && result[^1] != Path.PathSeparator)
                    {
                        result.Append(Path.PathSeparator);
                    }

                    result.Append(normalizedPath);
                    // Next insertion should happen at the end.
                    insertPosition = result.Length;
                }
                else
                {
                    // Insert at the requested location.
                    // This is used by the user-specific module path, the shared module path (<Program Files> location), and the PSHome module path.
                    string strToInsert = normalizedPath + Path.PathSeparator;
                    result.Insert(insertPosition, strToInsert);

                    // Next insertion should happen after the just inserted string.
                    insertPosition += strToInsert.Length;
                }

                // Add it to the set.
                addedPaths.Add(normalizedPath);
            }

            return result.ToString();
        }

        /// <summary>
        /// The available module path scopes.
        /// </summary>
        public enum PSModulePathScope
        {
            /// <summary>The users module path.</summary>
            User,

            /// <summary>The Builtin module path. This is where PowerShell is installed (PSHOME).</summary>
            Builtin,

            /// <summary>The machine module path. This is the shared location for all users of the system.</summary>
            Machine
        }

        /// <summary>
        /// Retrieve the current PSModulePath for the specified scope.
        /// </summary>
        /// <param name="scope">The scope of module path to retrieve. This can be User, Builtin, or Machine.</param>
        /// <returns>The string representing the requested module path type.</returns>
        public static string GetPSModulePath(PSModulePathScope scope)
        {
            if (scope == PSModulePathScope.User)
            {
                return GetPersonalModulePath();
            }
            else if (scope == PSModulePathScope.Builtin)
            {
                return GetPSHomeModulePath();
            }
            else
            {
                return GetSharedModulePath();
            }
        }

        /// <summary>
        /// Checks the various PSModulePath environment string and returns PSModulePath string as appropriate.
        /// </summary>
        public static string GetModulePath(string currentProcessModulePath, string hklmMachineModulePath, string hkcuUserModulePath)
        {
            string personalModulePath = GetPersonalModulePath();
            string sharedModulePath = GetSharedModulePath(); // aka <Program Files> location
            string psHomeModulePath = GetPSHomeModulePath(); // $PSHome\Modules location

            // If the variable isn't set, then set it to the default value
            if (string.IsNullOrEmpty(currentProcessModulePath))  // EVT.Process does Not exist - really corner case
            {
                // Handle the default case...
                if (string.IsNullOrEmpty(hkcuUserModulePath)) // EVT.User does Not exist -> set to <SpecialFolder.MyDocuments> location
                {
                    currentProcessModulePath = personalModulePath; // = SpecialFolder.MyDocuments + Utils.ProductNameForDirectory + Utils.ModuleDirectory
                }
                else // EVT.User exists -> set to EVT.User
                {
                    currentProcessModulePath = hkcuUserModulePath; // = EVT.User
                }

                if (string.IsNullOrEmpty(currentProcessModulePath))
                {
                    currentProcessModulePath ??= string.Empty;
                }
                else
                {
                    currentProcessModulePath += Path.PathSeparator;
                }

                if (string.IsNullOrEmpty(hklmMachineModulePath)) // EVT.Machine does Not exist
                {
                    currentProcessModulePath += CombineSystemModulePaths(); // += (SharedModulePath + $PSHome\Modules)
                }
                else
                {
                    currentProcessModulePath += hklmMachineModulePath; // += EVT.Machine
                }
            }
            // EVT.Process exists
            // Now handle the case where the environment variable is already set.
            else
            {
                string personalModulePathToUse = string.IsNullOrEmpty(hkcuUserModulePath) ? personalModulePath : hkcuUserModulePath;
                string systemModulePathToUse = string.IsNullOrEmpty(hklmMachineModulePath) ? psHomeModulePath : hklmMachineModulePath;

                // Maintain order of the paths, but ahead of any existing paths:
                // personalModulePath
                // sharedModulePath
                // systemModulePath

                int insertIndex = 0;

                currentProcessModulePath = UpdatePath(currentProcessModulePath, personalModulePathToUse, ref insertIndex);
                currentProcessModulePath = UpdatePath(currentProcessModulePath, sharedModulePath, ref insertIndex);
                currentProcessModulePath = UpdatePath(currentProcessModulePath, systemModulePathToUse, ref insertIndex);
            }

            return currentProcessModulePath;
        }

        /// <summary>
        /// Checks if $env:PSModulePath is not set and sets it as appropriate. Note - because these
        /// strings go through the provider, we need to escape any wildcards before passing them
        /// along.
        /// </summary>
        internal static string GetModulePath()
        {
            string currentModulePath = GetExpandedEnvironmentVariable(Constants.PSModulePathEnvVar, EnvironmentVariableTarget.Process);
            return currentModulePath;
        }

#if !UNIX
        /// <summary>
        /// Returns a PSModulePath suitable for Windows PowerShell by removing PowerShell's specific
        /// paths from current PSModulePath.
        /// </summary>
        /// <returns>
        /// Returns appropriate PSModulePath for Windows PowerShell.
        /// </returns>
        internal static string GetWindowsPowerShellModulePath()
        {
            string currentModulePath = GetModulePath();

            if (currentModulePath == null)
            {
                return null;
            }

            // PowerShell specific paths including if set in powershell.config.json file we want to exclude
            var excludeModulePaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase) {
                GetPersonalModulePath(),
                GetSharedModulePath(),
                GetPSHomeModulePath(),
                PowerShellConfig.Instance.GetModulePath(ConfigScope.AllUsers),
                PowerShellConfig.Instance.GetModulePath(ConfigScope.CurrentUser)
            };

            var modulePathList = new List<string>();
            foreach (var path in currentModulePath.Split(';', StringSplitOptions.TrimEntries))
            {
                if (!excludeModulePaths.Contains(path))
                {
                    // make sure this module path is Not part of other PS Core installation
                    var possiblePwshDir = Path.GetDirectoryName(path);

                    if (string.IsNullOrEmpty(possiblePwshDir))
                    {
                        // i.e. module dir is in the drive root
                        modulePathList.Add(path);
                    }
                    else
                    {
                        if (!File.Exists(Path.Combine(possiblePwshDir, "pwsh.dll")))
                        {
                            modulePathList.Add(path);
                        }
                    }
                }
            }

            return string.Join(Path.PathSeparator, modulePathList);
        }
#endif

        /// <summary>
        /// Checks if $env:PSModulePath is not set and sets it as appropriate. Note - because these
        /// strings go through the provider, we need to escape any wildcards before passing them
        /// along.
        /// </summary>
        private static string SetModulePath()
        {
            string currentModulePath = GetExpandedEnvironmentVariable(Constants.PSModulePathEnvVar, EnvironmentVariableTarget.Process);
#if !UNIX
            // if the current process and user env vars are the same, it means we need to append the machine one as it's incomplete.
            // Otherwise, the user modified it and we should use the process one.
            if (string.CompareOrdinal(GetExpandedEnvironmentVariable(Constants.PSModulePathEnvVar, EnvironmentVariableTarget.User), currentModulePath) == 0)
            {
                string machineScopeValue = GetExpandedEnvironmentVariable(Constants.PSModulePathEnvVar, EnvironmentVariableTarget.Machine);
                currentModulePath = string.IsNullOrEmpty(currentModulePath)
                    ? machineScopeValue
                    : string.IsNullOrEmpty(machineScopeValue)
                        ? currentModulePath
                        : string.Concat(currentModulePath, Path.PathSeparator, machineScopeValue);
            }
#endif
            string allUsersModulePath = PowerShellConfig.Instance.GetModulePath(ConfigScope.AllUsers);
            string personalModulePath = PowerShellConfig.Instance.GetModulePath(ConfigScope.CurrentUser);
            string newModulePathString = GetModulePath(currentModulePath, allUsersModulePath, personalModulePath);

            if (!string.IsNullOrEmpty(newModulePathString))
            {
                Environment.SetEnvironmentVariable(Constants.PSModulePathEnvVar, newModulePathString);
            }

            return newModulePathString;
        }

        /// <summary>
        /// Get the current module path setting.
        /// </summary>
        /// <param name="includeSystemModulePath">
        /// Include The system wide module path ($PSHOME\Modules) even if it's not in PSModulePath.
        /// In V3-V5, we prepended this path during module auto-discovery which incorrectly preferred
        /// $PSHOME\Modules over user installed modules that might have a command that overrides
        /// a product-supplied command.
        /// For 5.1, we append $PSHOME\Modules in this case to avoid the rare case where PSModulePath
        /// does not contain the path, but a script depends on previous behavior.
        /// Note that appending is still a potential breaking change, but necessary to update in-box
        /// modules long term - e.g. when open sourcing a module and installing from the gallery.
        /// </param>
        /// <param name="context"></param>
        /// <returns>The module path as an array of strings.</returns>
        internal static IEnumerable<string> GetModulePath(bool includeSystemModulePath, ExecutionContext context)
        {
            string modulePathString = Environment.GetEnvironmentVariable(Constants.PSModulePathEnvVar) ?? SetModulePath();

            HashSet<string> processedPathSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

            if (!string.IsNullOrWhiteSpace(modulePathString))
            {
                foreach (string envPath in modulePathString.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries))
                {
                    var processedPath = ProcessOneModulePath(context, envPath, processedPathSet);
                    if (processedPath != null)
                        yield return processedPath;
                }
            }

            if (includeSystemModulePath)
            {
                var processedPath = ProcessOneModulePath(context, GetPSHomeModulePath(), processedPathSet);
                if (processedPath != null)
                    yield return processedPath;
            }
        }

        private static string ProcessOneModulePath(ExecutionContext context, string envPath, HashSet<string> processedPathSet)
        {
            string trimmedenvPath = envPath.Trim();

            bool isUnc = Utils.PathIsUnc(trimmedenvPath);
            if (!isUnc)
            {
                // if the path start with "filesystem::", remove it so we can test for URI and
                // also Directory.Exists (if the file system provider isn't actually loaded.)
                if (trimmedenvPath.StartsWith("filesystem::", StringComparison.OrdinalIgnoreCase))
                {
                    trimmedenvPath = trimmedenvPath.Remove(0, 12 /*"filesystem::".Length*/);
                }

                isUnc = Utils.PathIsUnc(trimmedenvPath);
            }

            // If we have an unc, just return the value as resolving the path is expensive.
            if (isUnc)
            {
                return trimmedenvPath;
            }

            // We prefer using the file system provider to resolve paths so callers can avoid processing
            // duplicates, e.g. the following are all the same:
            //     a\b
            //     a\.\b
            //     a\b\
            // But if the file system provider isn't loaded, we will just check if the directory exists.
            if (context.EngineSessionState.IsProviderLoaded(context.ProviderNames.FileSystem))
            {
                ProviderInfo provider = null;
                IEnumerable<string> resolvedPaths = null;
                try
                {
                    resolvedPaths = context.SessionState.Path.GetResolvedProviderPathFromPSPath(
                        WildcardPattern.Escape(trimmedenvPath), out provider);
                }
                catch (ItemNotFoundException)
                {
                    // silently skip directories that are not found
                }
                catch (DriveNotFoundException)
                {
                    // silently skip drives that are not found
                }
                catch (NotSupportedException)
                {
                    // silently skip invalid path
                    // NotSupportedException is thrown if path contains a colon (":") that is not part of a
                    // volume identifier (for example, "c:\" is Supported but not "c:\temp\Z:\invalidPath")
                }

                if (provider != null && resolvedPaths != null && provider.NameEquals(context.ProviderNames.FileSystem))
                {
                    var result = resolvedPaths.FirstOrDefault();
                    if (processedPathSet.Add(result))
                    {
                        return result;
                    }
                }
            }
            else if (Directory.Exists(trimmedenvPath))
            {
                return trimmedenvPath;
            }

            return null;
        }

#nullable enable
        private static void SortAndRemoveDuplicates<T>(List<T> input, Func<T, string> keyGetter)
        {
            Dbg.Assert(input is not null, "Caller should verify that input != null");

            input.Sort(
                (T x, T y) =>
                {
                    string kx = keyGetter(x);
                    string ky = keyGetter(y);
                    return string.Compare(kx, ky, StringComparison.OrdinalIgnoreCase);
                }
            );

            string? previousKey = null;
            input.RemoveAll(ShouldRemove);

            bool ShouldRemove(T item)
            {
                string currentKey = keyGetter(item);
                bool match = previousKey is not null
                    && currentKey.Equals(previousKey, StringComparison.OrdinalIgnoreCase);
                previousKey = currentKey;
                return match;
            }
        }
#nullable restore

        /// <summary>
        /// Mark stuff to be exported from the current environment using the various patterns.
        /// </summary>
        /// <param name="cmdlet">The cmdlet calling this method.</param>
        /// <param name="sessionState">The session state instance to do the exports on.</param>
        /// <param name="functionPatterns">Patterns describing the functions to export.</param>
        /// <param name="cmdletPatterns">Patterns describing the cmdlets to export.</param>
        /// <param name="aliasPatterns">Patterns describing the aliases to export.</param>
        /// <param name="variablePatterns">Patterns describing the variables to export.</param>
        /// <param name="doNotExportCmdlets">List of Cmdlets that will not be exported, even if they match in cmdletPatterns.</param>
        internal static void ExportModuleMembers(
            PSCmdlet cmdlet,
            SessionStateInternal sessionState,
            List<WildcardPattern> functionPatterns,
            List<WildcardPattern> cmdletPatterns,
            List<WildcardPattern> aliasPatterns,
            List<WildcardPattern> variablePatterns,
            List<string> doNotExportCmdlets)
        {
            // If this cmdlet is called, then mark that the export list should be used for exporting
            // module members...

            sessionState.UseExportList = true;

            if (functionPatterns != null)
            {
                sessionState.FunctionsExported = true;
                if (PatternContainsWildcard(functionPatterns))
                {
                    sessionState.FunctionsExportedWithWildcard = true;
                }

                IDictionary<string, FunctionInfo> ft = sessionState.ModuleScope.FunctionTable;

                foreach (KeyValuePair<string, FunctionInfo> entry in ft)
                {
                    // Skip AllScope functions
                    if ((entry.Value.Options & ScopedItemOptions.AllScope) != 0)
                    {
                        continue;
                    }

                    if (SessionStateUtilities.MatchesAnyWildcardPattern(entry.Key, functionPatterns, false))
                    {
                        sessionState.ExportedFunctions.Add(entry.Value);
                        string message = StringUtil.Format(Modules.ExportingFunction, entry.Key);
                        cmdlet.WriteVerbose(message);
                    }
                }

                SortAndRemoveDuplicates(sessionState.ExportedFunctions, static (FunctionInfo ci) => ci.Name);
            }

            if (cmdletPatterns != null)
            {
                IDictionary<string, List<CmdletInfo>> ft = sessionState.ModuleScope.CmdletTable;

                // Subset the existing cmdlet exports if there are any. This will be the case
                // if we're using ModuleToProcess to import a binary module which has nested modules.
                if (sessionState.Module.CompiledExports.Count > 0)
                {
                    CmdletInfo[] copy = sessionState.Module.CompiledExports.ToArray();
                    sessionState.Module.CompiledExports.Clear();

                    foreach (CmdletInfo element in copy)
                    {
                        if (doNotExportCmdlets == null
                            || !doNotExportCmdlets.Exists(cmdletName => string.Equals(element.FullName, cmdletName, StringComparison.OrdinalIgnoreCase)))
                        {
                            if (SessionStateUtilities.MatchesAnyWildcardPattern(element.Name, cmdletPatterns, false))
                            {
                                string message = StringUtil.Format(Modules.ExportingCmdlet, element.Name);
                                cmdlet.WriteVerbose(message);
                                // Copy the cmdlet info, changing the module association to be the current module...
                                CmdletInfo exportedCmdlet = new CmdletInfo(element.Name, element.ImplementingType,
                                    element.HelpFile, null, element.Context)
                                { Module = sessionState.Module };
                                Dbg.Assert(sessionState.Module != null, "sessionState.Module should not be null by the time we're exporting cmdlets");
                                sessionState.Module.CompiledExports.Add(exportedCmdlet);
                            }
                        }
                    }
                }

                // And copy in any cmdlets imported from the nested modules...
                foreach (KeyValuePair<string, List<CmdletInfo>> entry in ft)
                {
                    CmdletInfo cmdletToImport = entry.Value[0];
                    if (doNotExportCmdlets == null
                        || !doNotExportCmdlets.Exists(cmdletName => string.Equals(cmdletToImport.FullName, cmdletName, StringComparison.OrdinalIgnoreCase)))
                    {
                        if (SessionStateUtilities.MatchesAnyWildcardPattern(entry.Key, cmdletPatterns, false))
                        {
                            string message = StringUtil.Format(Modules.ExportingCmdlet, entry.Key);
                            cmdlet.WriteVerbose(message);
                            // Copy the cmdlet info, changing the module association to be the current module...
                            CmdletInfo exportedCmdlet = new CmdletInfo(cmdletToImport.Name, cmdletToImport.ImplementingType,
                                cmdletToImport.HelpFile, null, cmdletToImport.Context)
                            { Module = sessionState.Module };
                            Dbg.Assert(sessionState.Module != null, "sessionState.Module should not be null by the time we're exporting cmdlets");
                            sessionState.Module.CompiledExports.Add(exportedCmdlet);
                        }
                    }
                }

                SortAndRemoveDuplicates(sessionState.Module.CompiledExports, static (CmdletInfo ci) => ci.Name);
            }

            if (variablePatterns != null)
            {
                IDictionary<string, PSVariable> vt = sessionState.ModuleScope.Variables;

                foreach (KeyValuePair<string, PSVariable> entry in vt)
                {
                    // The magic variables are always private as are all-scope variables...
                    if (entry.Value.IsAllScope || Array.IndexOf(PSModuleInfo._builtinVariables, entry.Key) != -1)
                    {
                        continue;
                    }

                    if (SessionStateUtilities.MatchesAnyWildcardPattern(entry.Key, variablePatterns, false))
                    {
                        string message = StringUtil.Format(Modules.ExportingVariable, entry.Key);
                        cmdlet.WriteVerbose(message);
                        sessionState.ExportedVariables.Add(entry.Value);
                    }
                }

                SortAndRemoveDuplicates(sessionState.ExportedVariables, static (PSVariable v) => v.Name);
            }

            if (aliasPatterns != null)
            {
                IEnumerable<AliasInfo> mai = sessionState.ModuleScope.AliasTable;

                // Subset the existing alias exports if there are any. This will be the case
                // if we're using ModuleToProcess to import a binary module which has nested modules.
                if (sessionState.Module.CompiledAliasExports.Count > 0)
                {
                    AliasInfo[] copy = sessionState.Module.CompiledAliasExports.ToArray();

                    foreach (var element in copy)
                    {
                        if (SessionStateUtilities.MatchesAnyWildcardPattern(element.Name, aliasPatterns, false))
                        {
                            string message = StringUtil.Format(Modules.ExportingAlias, element.Name);
                            cmdlet.WriteVerbose(message);
                            sessionState.ExportedAliases.Add(NewAliasInfo(element, sessionState));
                        }
                    }
                }

                foreach (AliasInfo entry in mai)
                {
                    // Skip allscope items...
                    if ((entry.Options & ScopedItemOptions.AllScope) != 0)
                    {
                        continue;
                    }

                    if (SessionStateUtilities.MatchesAnyWildcardPattern(entry.Name, aliasPatterns, false))
                    {
                        string message = StringUtil.Format(Modules.ExportingAlias, entry.Name);
                        cmdlet.WriteVerbose(message);
                        sessionState.ExportedAliases.Add(NewAliasInfo(entry, sessionState));
                    }
                }

                SortAndRemoveDuplicates(sessionState.ExportedAliases, static (AliasInfo ci) => ci.Name);
            }
        }

        /// <summary>
        /// Checks pattern list for wildcard characters.
        /// </summary>
        /// <param name="list">Pattern list.</param>
        /// <returns>True if pattern contains '*'.</returns>
        internal static bool PatternContainsWildcard(List<WildcardPattern> list)
        {
            if (list != null)
            {
                foreach (var item in list)
                {
                    if (WildcardPattern.ContainsWildcardCharacters(item.Pattern))
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        private static AliasInfo NewAliasInfo(AliasInfo alias, SessionStateInternal sessionState)
        {
            Dbg.Assert(alias != null, "alias should not be null");
            Dbg.Assert(sessionState != null, "sessionState should not be null");
            Dbg.Assert(sessionState.Module != null, "sessionState.Module should not be null by the time we're exporting aliases");

            // Copy the alias info, changing the module association to be the current module...
            var aliasCopy = new AliasInfo(alias.Name, alias.Definition, alias.Context, alias.Options)
            {
                Module = sessionState.Module
            };
            return aliasCopy;
        }
    }

    /// <summary>
    /// Enumeration of reasons for a failure to match a module by constraints.
    /// </summary>
    internal enum ModuleMatchFailure
    {
        /// <summary>Match did not fail.</summary>
        None,

        /// <summary>Match failed because the module was null.</summary>
        NullModule,

        /// <summary>Module name did not match.</summary>
        Name,

        /// <summary>Module GUID did not match.</summary>
        Guid,

        /// <summary>Module version did not match the required version.</summary>
        RequiredVersion,

        /// <summary>Module version was lower than the minimum version.</summary>
        MinimumVersion,

        /// <summary>Module version was greater than the maximum version.</summary>
        MaximumVersion,

        /// <summary>The module specification passed in was null.</summary>
        NullModuleSpecification,
    }

#nullable enable
    /// <summary>
    /// Used by Modules/Snapins to provide a hook to the engine for startup initialization
    /// w.r.t compiled assembly loading.
    /// </summary>
#nullable enable
    public interface IModuleAssemblyInitializer
    {
        /// <summary>
        /// Gets called when assembly is loaded.
        /// </summary>
        void OnImport();
    }

    /// <summary>
    /// Used by modules to provide a hook to the engine for cleanup on removal
    /// w.r.t. compiled assembly being removed.
    /// </summary>
    public interface IModuleAssemblyCleanup
    {
        /// <summary>
        /// Gets called when the binary module is unloaded.
        /// </summary>
        void OnRemove(PSModuleInfo psModuleInfo);
    }
}