File size: 96,620 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 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
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.Language;
using System.Management.Automation.Runspaces;
using System.Reflection;
using System.Security;
using System.Threading;
using Microsoft.Management.Infrastructure;
using Microsoft.PowerShell.Cmdletization;
using Microsoft.PowerShell.Telemetry;
using Dbg = System.Management.Automation.Diagnostics;
using Parser = System.Management.Automation.Language.Parser;
using ScriptBlock = System.Management.Automation.ScriptBlock;
using Token = System.Management.Automation.Language.Token;
#if LEGACYTELEMETRY
using Microsoft.PowerShell.Telemetry.Internal;
#endif
//
// Now define the set of commands for manipulating modules.
//
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Implements a cmdlet that loads a module.
/// </summary>
[Cmdlet(VerbsData.Import, "Module", DefaultParameterSetName = ParameterSet_Name, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096585")]
[OutputType(typeof(PSModuleInfo))]
public sealed class ImportModuleCommand : ModuleCmdletBase, IDisposable
{
#region Cmdlet parameters
private const string ParameterSet_Name = "Name";
private const string ParameterSet_FQName = "FullyQualifiedName";
private const string ParameterSet_ModuleInfo = "ModuleInfo";
private const string ParameterSet_Assembly = "Assembly";
private const string ParameterSet_ViaPsrpSession = "PSSession";
private const string ParameterSet_ViaCimSession = "CimSession";
private const string ParameterSet_FQName_ViaPsrpSession = "FullyQualifiedNameAndPSSession";
private const string ParameterSet_ViaWinCompat = "WinCompat";
private const string ParameterSet_FQName_ViaWinCompat = "FullyQualifiedNameAndWinCompat";
/// <summary>
/// This parameter specifies whether to import to the current session state
/// or to the global / top-level session state.
/// </summary>
[Parameter]
public SwitchParameter Global
{
get { return base.BaseGlobal; }
set { base.BaseGlobal = value; }
}
/// <summary>
/// This parameter specified a prefix used to modify names of imported commands.
/// </summary>
[Parameter]
[ValidateNotNull]
public string Prefix
{
get { return BasePrefix; }
set { BasePrefix = value; }
}
/// <summary>
/// This parameter names the module to load.
/// </summary>
[Parameter(ParameterSetName = ParameterSet_Name, Mandatory = true, ValueFromPipeline = true, Position = 0)]
[Parameter(ParameterSetName = ParameterSet_ViaPsrpSession, Mandatory = true, ValueFromPipeline = true, Position = 0)]
[Parameter(ParameterSetName = ParameterSet_ViaCimSession, Mandatory = true, ValueFromPipeline = true, Position = 0)]
[Parameter(ParameterSetName = ParameterSet_ViaWinCompat, Mandatory = true, ValueFromPipeline = true, Position = 0)]
[ValidateTrustedData]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public string[] Name { get; set; } = Array.Empty<string>();
/// <summary>
/// This parameter specifies the current pipeline object.
/// </summary>
[Parameter(ParameterSetName = ParameterSet_FQName, Mandatory = true, ValueFromPipeline = true, Position = 0)]
[Parameter(ParameterSetName = ParameterSet_FQName_ViaPsrpSession, Mandatory = true, ValueFromPipeline = true, Position = 0)]
[Parameter(ParameterSetName = ParameterSet_FQName_ViaWinCompat, Mandatory = true, ValueFromPipeline = true, Position = 0)]
[ValidateTrustedData]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public ModuleSpecification[] FullyQualifiedName { get; set; }
/// <summary>
/// A list of assembly objects to process as modules.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
[Parameter(ParameterSetName = ParameterSet_Assembly, Mandatory = true, ValueFromPipeline = true, Position = 0)]
[ValidateTrustedData]
public Assembly[] Assembly { get; set; }
/// <summary>
/// This patterns matching the names of functions to import from the module...
/// </summary>
[Parameter]
[ValidateNotNull]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public string[] Function
{
get
{
return _functionImportList;
}
set
{
if (value == null)
return;
_functionImportList = value;
// Create the list of patterns to match at parameter bind time
// so errors will be reported before loading the module...
BaseFunctionPatterns = new List<WildcardPattern>();
foreach (string pattern in _functionImportList)
{
BaseFunctionPatterns.Add(WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase));
}
}
}
private string[] _functionImportList = Array.Empty<string>();
/// <summary>
/// This patterns matching the names of cmdlets to import from the module...
/// </summary>
[Parameter]
[ValidateNotNull]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public string[] Cmdlet
{
get
{
return _cmdletImportList;
}
set
{
if (value == null)
return;
_cmdletImportList = value;
// Create the list of patterns to match at parameter bind time
// so errors will be reported before loading the module...
BaseCmdletPatterns = new List<WildcardPattern>();
foreach (string pattern in _cmdletImportList)
{
BaseCmdletPatterns.Add(WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase));
}
}
}
private string[] _cmdletImportList = Array.Empty<string>();
/// <summary>
/// This parameter specifies the variables to import from the module...
/// </summary>
[Parameter]
[ValidateNotNull]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public string[] Variable
{
get
{
return _variableExportList;
}
set
{
if (value == null)
return;
_variableExportList = value;
// Create the list of patterns to match at parameter bind time
// so errors will be reported before loading the module...
BaseVariablePatterns = new List<WildcardPattern>();
foreach (string pattern in _variableExportList)
{
BaseVariablePatterns.Add(WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase));
}
}
}
private string[] _variableExportList;
/// <summary>
/// This parameter specifies the aliases to import from the module...
/// </summary>
[Parameter]
[ValidateNotNull]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public string[] Alias
{
get
{
return _aliasExportList;
}
set
{
if (value == null)
return;
_aliasExportList = value;
// Create the list of patterns to match at parameter bind time
// so errors will be reported before loading the module...
BaseAliasPatterns = new List<WildcardPattern>();
foreach (string pattern in _aliasExportList)
{
BaseAliasPatterns.Add(WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase));
}
}
}
private string[] _aliasExportList;
/// <summary>
/// This parameter causes a module to be loaded over top of the current one...
/// </summary>
[Parameter]
public SwitchParameter Force
{
get { return (SwitchParameter)BaseForce; }
set { BaseForce = value; }
}
/// <summary>
/// Skips the check on CompatiblePSEditions for modules loaded from the System32 module path.
/// This is mutually exclusive with UseWindowsPowerShell parameter.
/// </summary>
[Parameter(ParameterSetName = ParameterSet_Name)]
[Parameter(ParameterSetName = ParameterSet_FQName)]
[Parameter(ParameterSetName = ParameterSet_ModuleInfo)]
[Parameter(ParameterSetName = ParameterSet_Assembly)]
[Parameter(ParameterSetName = ParameterSet_ViaPsrpSession)]
[Parameter(ParameterSetName = ParameterSet_ViaCimSession)]
[Parameter(ParameterSetName = ParameterSet_FQName_ViaPsrpSession)]
public SwitchParameter SkipEditionCheck
{
get { return (SwitchParameter)BaseSkipEditionCheck; }
set { BaseSkipEditionCheck = value; }
}
/// <summary>
/// This parameter causes the session state instance to be written...
/// </summary>
[Parameter]
public SwitchParameter PassThru
{
get { return (SwitchParameter)BasePassThru; }
set { BasePassThru = value; }
}
/// <summary>
/// This parameter causes the session state instance to be written as a custom object...
/// </summary>
[Parameter]
public SwitchParameter AsCustomObject
{
get { return (SwitchParameter)BaseAsCustomObject; }
set { BaseAsCustomObject = value; }
}
/// <summary>
/// The minimum version of the module to load.
/// </summary>
[Parameter(ParameterSetName = ParameterSet_Name)]
[Parameter(ParameterSetName = ParameterSet_ViaPsrpSession)]
[Parameter(ParameterSetName = ParameterSet_ViaCimSession)]
[Parameter(ParameterSetName = ParameterSet_ViaWinCompat)]
[Alias("Version")]
public Version MinimumVersion
{
get { return BaseMinimumVersion; }
set { BaseMinimumVersion = value; }
}
/// <summary>
/// The maximum version of the module to load.
/// </summary>
[Parameter(ParameterSetName = ParameterSet_Name)]
[Parameter(ParameterSetName = ParameterSet_ViaPsrpSession)]
[Parameter(ParameterSetName = ParameterSet_ViaCimSession)]
[Parameter(ParameterSetName = ParameterSet_ViaWinCompat)]
public string MaximumVersion
{
get
{
if (BaseMaximumVersion == null)
return null;
else
return BaseMaximumVersion.ToString();
}
set
{
if (string.IsNullOrWhiteSpace(value))
{
BaseMaximumVersion = null;
}
else
{
BaseMaximumVersion = GetMaximumVersion(value);
}
}
}
/// <summary>
/// The version of the module to load.
/// </summary>
[Parameter(ParameterSetName = ParameterSet_Name)]
[Parameter(ParameterSetName = ParameterSet_ViaPsrpSession)]
[Parameter(ParameterSetName = ParameterSet_ViaCimSession)]
[Parameter(ParameterSetName = ParameterSet_ViaWinCompat)]
public Version RequiredVersion
{
get { return BaseRequiredVersion; }
set { BaseRequiredVersion = value; }
}
/// <summary>
/// This parameter specifies the current pipeline object.
/// </summary>
[Parameter(ParameterSetName = ParameterSet_ModuleInfo, Mandatory = true, ValueFromPipeline = true, Position = 0)]
[ValidateTrustedData]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public PSModuleInfo[] ModuleInfo { get; set; } = Array.Empty<PSModuleInfo>();
/// <summary>
/// The arguments to pass to the module script.
/// </summary>
[Parameter]
[Alias("Args")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public object[] ArgumentList
{
get { return BaseArgumentList; }
set { BaseArgumentList = value; }
}
/// <summary>
/// Disable warnings on cmdlet and function names that have non-standard verbs
/// or non-standard characters in the noun.
/// </summary>
[Parameter]
public SwitchParameter DisableNameChecking
{
get { return BaseDisableNameChecking; }
set { BaseDisableNameChecking = value; }
}
/// <summary>
/// Does not import a command if a command with same name exists on the target sessionstate.
/// </summary>
[Parameter, Alias("NoOverwrite")]
public SwitchParameter NoClobber { get; set; }
/// <summary>
/// Imports a command to the scope specified.
/// </summary>
[Parameter]
[ValidateSet("Local", "Global")]
public string Scope
{
get
{
return _scope;
}
set
{
_scope = value;
_isScopeSpecified = true;
}
}
private string _scope = string.Empty;
private bool _isScopeSpecified = false;
/// <summary>
/// If specified, then Import-Module will attempt to import PowerShell modules from a remote computer using the specified session.
/// </summary>
[Parameter(ParameterSetName = ParameterSet_ViaPsrpSession, Mandatory = true)]
[Parameter(ParameterSetName = ParameterSet_FQName_ViaPsrpSession, Mandatory = true)]
[ValidateNotNull]
public PSSession PSSession { get; set; }
/// Construct the Import-Module cmdlet object
public ImportModuleCommand()
{
base.BaseDisableNameChecking = false;
}
/// <summary>
/// If specified, then Import-Module will attempt to import PS-CIM modules from a remote computer using the specified session.
/// </summary>
[Parameter(ParameterSetName = ParameterSet_ViaCimSession, Mandatory = true)]
[ValidateNotNull]
public CimSession CimSession { get; set; }
/// <summary>
/// For interoperability with 3rd party CIM servers, user can specify custom resource URI.
/// </summary>
[Parameter(ParameterSetName = ParameterSet_ViaCimSession, Mandatory = false)]
[ValidateNotNull]
public Uri CimResourceUri { get; set; }
/// <summary>
/// For interoperability with 3rd party CIM servers, user can specify custom namespace.
/// </summary>
[Parameter(ParameterSetName = ParameterSet_ViaCimSession, Mandatory = false)]
[ValidateNotNullOrEmpty]
public string CimNamespace { get; set; }
/// <summary>
/// This parameter causes a module to be loaded into Windows PowerShell.
/// This is mutually exclusive with SkipEditionCheck parameter.
/// </summary>
[Parameter(ParameterSetName = ParameterSet_ViaWinCompat, Mandatory = true)]
[Parameter(ParameterSetName = ParameterSet_FQName_ViaWinCompat, Mandatory = true)]
[Alias("UseWinPS")]
public SwitchParameter UseWindowsPowerShell { get; set; }
#endregion Cmdlet parameters
#region Local import
private void ImportModule_ViaLocalModuleInfo(ImportModuleOptions importModuleOptions, PSModuleInfo module)
{
try
{
PSModuleInfo alreadyLoadedModule = null;
TryGetFromModuleTable(module.Path, out alreadyLoadedModule);
if (!BaseForce && DoesAlreadyLoadedModuleSatisfyConstraints(alreadyLoadedModule))
{
AddModuleToModuleTables(this.Context, this.TargetSessionState.Internal, alreadyLoadedModule);
// Even if the module has been loaded, import the specified members...
ImportModuleMembers(alreadyLoadedModule, this.BasePrefix, importModuleOptions);
if (BaseAsCustomObject)
{
if (alreadyLoadedModule.ModuleType != ModuleType.Script)
{
string message = StringUtil.Format(Modules.CantUseAsCustomObjectWithBinaryModule, alreadyLoadedModule.Path);
InvalidOperationException invalidOp = new InvalidOperationException(message);
ErrorRecord er = new ErrorRecord(invalidOp, "Modules_CantUseAsCustomObjectWithBinaryModule",
ErrorCategory.PermissionDenied, null);
WriteError(er);
}
else
{
WriteObject(alreadyLoadedModule.AsCustomObject());
}
}
else if (BasePassThru)
{
WriteObject(alreadyLoadedModule);
}
}
else
{
PSModuleInfo moduleToRemove;
if (TryGetFromModuleTable(module.Path, out moduleToRemove, toRemove: true))
{
Dbg.Assert(BaseForce, "We should only remove and reload if -Force was specified");
RemoveModule(moduleToRemove);
}
PSModuleInfo moduleToProcess = module;
try
{
// If we're passing in a dynamic module, then the session state will not be
// null and we want to just add the module to the module table. Otherwise, it's
// a module info from Get-Module -list so we need to read the actual module file.
if (module.SessionState == null)
{
if (File.Exists(module.Path))
{
bool found;
moduleToProcess = LoadModule(module.Path, null, this.BasePrefix, /*SessionState*/ null,
ref importModuleOptions,
ManifestProcessingFlags.LoadElements | ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.NullOnFirstError,
out found);
Dbg.Assert(found, "Module should be found when referenced by its absolute path");
}
}
else if (!string.IsNullOrEmpty(module.Name))
{
// It has a session state and a name but it's not in the module
// table so it's ok to add it
// Add it to the all module tables
AddModuleToModuleTables(this.Context, this.TargetSessionState.Internal, moduleToProcess);
if (moduleToProcess.SessionState != null)
{
ImportModuleMembers(moduleToProcess, this.BasePrefix, importModuleOptions);
}
if (BaseAsCustomObject && moduleToProcess.SessionState != null)
{
WriteObject(module.AsCustomObject());
}
else if (BasePassThru)
{
WriteObject(moduleToProcess);
}
}
}
catch (IOException)
{
}
}
}
catch (PSInvalidOperationException e)
{
ErrorRecord er = new ErrorRecord(e.ErrorRecord, e);
WriteError(er);
}
}
private void ImportModule_ViaAssembly(ImportModuleOptions importModuleOptions, Assembly suppliedAssembly)
{
bool moduleLoaded = false;
string moduleName = "dynamic_code_module_" + suppliedAssembly.FullName;
// Loop through Module Cache to ensure that the module is not already imported.
foreach (KeyValuePair<string, PSModuleInfo> pair in Context.Modules.ModuleTable)
{
if (pair.Value.Path == string.Empty)
{
// If the module in the moduleTable is an assembly module without path, the moduleName is the key.
if (pair.Key.Equals(moduleName, StringComparison.OrdinalIgnoreCase))
{
moduleLoaded = true;
if (BasePassThru)
{
WriteObject(pair.Value);
}
break;
}
continue;
}
if (pair.Value.Path.Equals(suppliedAssembly.Location, StringComparison.OrdinalIgnoreCase))
{
moduleLoaded = true;
if (BasePassThru)
{
WriteObject(pair.Value);
}
break;
}
}
if (!moduleLoaded)
{
PSModuleInfo module = LoadBinaryModule(
parentModule: null,
moduleName: null,
fileName: null,
suppliedAssembly,
moduleBase: null,
ss: null,
importModuleOptions,
ManifestProcessingFlags.LoadElements | ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.NullOnFirstError,
BasePrefix,
out bool found);
if (found && module is not null)
{
// Add it to all module tables ...
AddModuleToModuleTables(Context, TargetSessionState.Internal, module);
if (BasePassThru)
{
WriteObject(module);
}
}
}
}
private PSModuleInfo ImportModule_LocallyViaName_WithTelemetry(ImportModuleOptions importModuleOptions, string name)
{
PSModuleInfo foundModule = ImportModule_LocallyViaName(importModuleOptions, name);
if (foundModule != null)
{
SetModuleBaseForEngineModules(foundModule.Name, this.Context);
// report loading of the module in telemetry
// avoid double reporting for WinCompat modules that go through CommandDiscovery\AutoloadSpecifiedModule
if (!foundModule.IsWindowsPowerShellCompatModule)
{
ApplicationInsightsTelemetry.SendModuleTelemetryMetric(TelemetryType.ModuleLoad, foundModule);
#if LEGACYTELEMETRY
TelemetryAPI.ReportModuleLoad(foundModule);
#endif
}
}
return foundModule;
}
private PSModuleInfo ImportModule_LocallyViaName(ImportModuleOptions importModuleOptions, string name)
{
bool shallWriteError = !importModuleOptions.SkipSystem32ModulesAndSuppressError;
try
{
bool found = false;
PSModuleInfo foundModule = null;
string cachedPath = null;
string rootedPath = null;
// See if we can use the cached path for the file. If a version number has been specified, then
// we won't look in the cache
if (this.MinimumVersion == null && this.MaximumVersion == null && this.RequiredVersion == null && PSModuleInfo.UseAppDomainLevelModuleCache && !this.BaseForce)
{
// See if the name is in the appdomain-level module path name cache...
cachedPath = PSModuleInfo.ResolveUsingAppDomainLevelModuleCache(name);
}
if (!string.IsNullOrEmpty(cachedPath))
{
if (File.Exists(cachedPath))
{
rootedPath = cachedPath;
}
else
{
PSModuleInfo.RemoveFromAppDomainLevelCache(name);
}
}
// If null check for full-qualified paths - either absolute or relative
rootedPath ??= ResolveRootedFilePath(name, this.Context);
bool alreadyLoaded = false;
var manifestProcessingFlags = ManifestProcessingFlags.LoadElements | ManifestProcessingFlags.NullOnFirstError;
if (shallWriteError)
{
manifestProcessingFlags |= ManifestProcessingFlags.WriteErrors;
}
if (!string.IsNullOrEmpty(rootedPath))
{
// If the module has already been loaded, just emit it and continue...
if (!BaseForce && TryGetFromModuleTable(rootedPath, out PSModuleInfo module))
{
if (module.ModuleType != ModuleType.Manifest
|| ModuleIntrinsics.IsVersionMatchingConstraints(module.Version, RequiredVersion, BaseMinimumVersion, BaseMaximumVersion))
{
alreadyLoaded = true;
AddModuleToModuleTables(this.Context, this.TargetSessionState.Internal, module);
ImportModuleMembers(module, this.BasePrefix, importModuleOptions);
if (BaseAsCustomObject)
{
if (module.ModuleType != ModuleType.Script)
{
string message = StringUtil.Format(Modules.CantUseAsCustomObjectWithBinaryModule, module.Path);
InvalidOperationException invalidOp = new InvalidOperationException(message);
ErrorRecord er = new ErrorRecord(invalidOp, "Modules_CantUseAsCustomObjectWithBinaryModule",
ErrorCategory.PermissionDenied, null);
WriteError(er);
}
else
{
WriteObject(module.AsCustomObject());
}
}
else if (BasePassThru)
{
WriteObject(module);
}
found = true;
foundModule = module;
}
}
if (!alreadyLoaded)
{
// If the path names a file, load that file...
if (File.Exists(rootedPath))
{
PSModuleInfo moduleToRemove;
if (TryGetFromModuleTable(rootedPath, out moduleToRemove, toRemove: true))
{
RemoveModule(moduleToRemove);
}
foundModule = LoadModule(
fileName: rootedPath,
moduleBase: null,
prefix: BasePrefix,
ss: null, /*SessionState*/
ref importModuleOptions,
manifestProcessingFlags,
out found);
}
else if (Directory.Exists(rootedPath))
{
// If the path ends with a directory separator, remove it
if (rootedPath.EndsWith(Path.DirectorySeparatorChar))
{
rootedPath = Path.GetDirectoryName(rootedPath);
}
// Load the latest valid version if it is a multi-version module directory
foundModule = LoadUsingMultiVersionModuleBase(rootedPath, manifestProcessingFlags, importModuleOptions, out found);
if (!found)
{
// If the path is a directory, double up the end of the string
// then try to load that using extensions...
rootedPath = Path.Combine(rootedPath, Path.GetFileName(rootedPath));
foundModule = LoadUsingExtensions(
parentModule: null,
moduleName: rootedPath,
fileBaseName: rootedPath,
extension: null,
moduleBase: null,
prefix: BasePrefix,
ss: null, /*SessionState*/
importModuleOptions,
manifestProcessingFlags,
out found);
}
}
}
}
else
{
// Check if module could be a snapin. This was the case for PowerShell version 2 engine modules.
if (InitialSessionState.IsEngineModule(name))
{
PSSnapInInfo snapin = Context.CurrentRunspace.InitialSessionState.GetPSSnapIn(name);
// Return the command if we found a module
if (snapin != null)
{
// warn that this module already exists as a snapin
string warningMessage = string.Format(
CultureInfo.InvariantCulture,
Modules.ModuleLoadedAsASnapin,
snapin.Name);
WriteWarning(warningMessage);
found = true;
return foundModule;
}
}
// At this point, the name didn't resolve to an existing file or directory.
// It may still be rooted (relative or absolute). If it is, then we'll only use
// the extension search. If it's not rooted, use a path-based search.
if (IsRooted(name))
{
// If there is no extension, we'll have to search using the extensions
if (!string.IsNullOrEmpty(Path.GetExtension(name)))
{
foundModule = LoadModule(
fileName: name,
moduleBase: null,
prefix: BasePrefix,
ss: null, /*SessionState*/
ref importModuleOptions,
manifestProcessingFlags,
out found);
}
else
{
foundModule = LoadUsingExtensions(
parentModule: null,
moduleName: name,
fileBaseName: name,
extension: null,
moduleBase: null,
prefix: BasePrefix,
ss: null, /*SessionState*/
importModuleOptions,
manifestProcessingFlags,
out found);
}
}
else
{
IEnumerable<string> modulePath = ModuleIntrinsics.GetModulePath(false, this.Context);
if (this.MinimumVersion == null && this.RequiredVersion == null && this.MaximumVersion == null)
{
this.AddToAppDomainLevelCache = true;
}
found = LoadUsingModulePath(
modulePath,
name,
ss: null, /* SessionState*/
importModuleOptions,
manifestProcessingFlags,
out foundModule);
}
}
if (!found && shallWriteError)
{
ErrorRecord er = null;
string message = null;
if (BaseRequiredVersion != null)
{
message = StringUtil.Format(Modules.ModuleWithVersionNotFound, name, BaseRequiredVersion);
}
else if (BaseMinimumVersion != null && BaseMaximumVersion != null)
{
message = StringUtil.Format(Modules.MinimumVersionAndMaximumVersionNotFound, name, BaseMinimumVersion, BaseMaximumVersion);
}
else if (BaseMinimumVersion != null)
{
message = StringUtil.Format(Modules.ModuleWithVersionNotFound, name, BaseMinimumVersion);
}
else if (BaseMaximumVersion != null)
{
message = StringUtil.Format(Modules.MaximumVersionNotFound, name, BaseMaximumVersion);
}
if (BaseRequiredVersion != null || BaseMinimumVersion != null || BaseMaximumVersion != null)
{
FileNotFoundException fnf = new FileNotFoundException(message);
er = new ErrorRecord(fnf, "Modules_ModuleWithVersionNotFound",
ErrorCategory.ResourceUnavailable, name);
}
else
{
message = StringUtil.Format(Modules.ModuleNotFound, name);
FileNotFoundException fnf = new FileNotFoundException(message);
er = new ErrorRecord(fnf, "Modules_ModuleNotFound",
ErrorCategory.ResourceUnavailable, name);
}
WriteError(er);
}
return foundModule;
}
catch (PSInvalidOperationException e)
{
if (shallWriteError)
{
WriteError(new ErrorRecord(e.ErrorRecord, e));
}
}
return null;
}
private PSModuleInfo ImportModule_LocallyViaFQName(ImportModuleOptions importModuleOptions, ModuleSpecification modulespec)
{
RequiredVersion = modulespec.RequiredVersion;
MinimumVersion = modulespec.Version;
MaximumVersion = modulespec.MaximumVersion;
BaseGuid = modulespec.Guid;
PSModuleInfo foundModule = ImportModule_LocallyViaName(importModuleOptions, modulespec.Name);
if (foundModule != null)
{
ApplicationInsightsTelemetry.SendModuleTelemetryMetric(TelemetryType.ModuleLoad, foundModule);
SetModuleBaseForEngineModules(foundModule.Name, this.Context);
}
return foundModule;
}
#endregion Local import
#region Remote import
#region PSSession parameterset
private IList<PSModuleInfo> ImportModule_RemotelyViaPsrpSession(
ImportModuleOptions importModuleOptions,
IEnumerable<string> moduleNames,
IEnumerable<ModuleSpecification> fullyQualifiedNames,
PSSession psSession,
bool usingWinCompat = false)
{
var remotelyImportedModules = new List<PSModuleInfo>();
if (moduleNames != null)
{
foreach (string moduleName in moduleNames)
{
var tmp = ImportModule_RemotelyViaPsrpSession(importModuleOptions, moduleName, null, psSession);
remotelyImportedModules.AddRange(tmp);
}
}
if (fullyQualifiedNames != null)
{
foreach (var fullyQualifiedName in fullyQualifiedNames)
{
var tmp = ImportModule_RemotelyViaPsrpSession(importModuleOptions, null, fullyQualifiedName, psSession);
remotelyImportedModules.AddRange(tmp);
}
}
// Send telemetry on the imported modules
foreach (PSModuleInfo moduleInfo in remotelyImportedModules)
{
ApplicationInsightsTelemetry.SendModuleTelemetryMetric(usingWinCompat ? TelemetryType.WinCompatModuleLoad : TelemetryType.ModuleLoad, moduleInfo);
}
return remotelyImportedModules;
}
private IList<PSModuleInfo> ImportModule_RemotelyViaPsrpSession(
ImportModuleOptions importModuleOptions,
string moduleName,
ModuleSpecification fullyQualifiedName,
PSSession psSession)
{
//
// import the module in the remote session first
//
List<PSObject> remotelyImportedModules;
using (var powerShell = System.Management.Automation.PowerShell.Create())
{
powerShell.Runspace = psSession.Runspace;
powerShell.AddCommand("Import-Module");
powerShell.AddParameter("DisableNameChecking", this.DisableNameChecking);
powerShell.AddParameter("PassThru", true);
if (fullyQualifiedName != null)
{
powerShell.AddParameter("FullyQualifiedName", fullyQualifiedName);
}
else
{
powerShell.AddParameter("Name", moduleName);
if (this.MinimumVersion != null)
{
powerShell.AddParameter("Version", this.MinimumVersion);
}
if (this.RequiredVersion != null)
{
powerShell.AddParameter("RequiredVersion", this.RequiredVersion);
}
if (this.MaximumVersion != null)
{
powerShell.AddParameter("MaximumVersion", this.MaximumVersion);
}
}
if (this.ArgumentList != null)
{
powerShell.AddParameter("ArgumentList", this.ArgumentList);
}
if (this.BaseForce)
{
powerShell.AddParameter("Force", true);
}
string errorMessageTemplate = string.Format(
CultureInfo.InvariantCulture,
Modules.RemoteDiscoveryRemotePsrpCommandFailed,
string.Create(CultureInfo.InvariantCulture, $"Import-Module -Name '{moduleName}'"));
remotelyImportedModules = RemoteDiscoveryHelper.InvokePowerShell(
powerShell,
this,
errorMessageTemplate,
this.CancellationToken).ToList();
}
List<PSModuleInfo> result = new List<PSModuleInfo>();
foreach (PSObject remotelyImportedModule in remotelyImportedModules)
{
PSPropertyInfo nameProperty = remotelyImportedModule.Properties["Name"];
if (nameProperty != null)
{
string remoteModuleName = (string)LanguagePrimitives.ConvertTo(
nameProperty.Value,
typeof(string),
CultureInfo.InvariantCulture);
PSPropertyInfo helpInfoProperty = remotelyImportedModule.Properties["HelpInfoUri"];
string remoteHelpInfoUri = null;
if (helpInfoProperty != null)
{
remoteHelpInfoUri = (string)LanguagePrimitives.ConvertTo(
helpInfoProperty.Value,
typeof(string),
CultureInfo.InvariantCulture);
}
PSPropertyInfo guidProperty = remotelyImportedModule.Properties["Guid"];
Guid remoteModuleGuid = Guid.Empty;
if (guidProperty != null)
{
LanguagePrimitives.TryConvertTo(guidProperty.Value, out remoteModuleGuid);
}
PSPropertyInfo versionProperty = remotelyImportedModule.Properties["Version"];
Version remoteModuleVersion = null;
if (versionProperty != null)
{
Version tmp;
if (LanguagePrimitives.TryConvertTo<Version>(versionProperty.Value, CultureInfo.InvariantCulture, out tmp))
{
remoteModuleVersion = tmp;
}
}
PSModuleInfo moduleInfo = ImportModule_RemotelyViaPsrpSession_SinglePreimportedModule(
importModuleOptions,
remoteModuleName,
remoteModuleVersion,
psSession);
// Set the HelpInfoUri and Guid as necessary, so that Save-Help can work with this module object
// to retrieve help files from the remote site.
if (moduleInfo != null)
{
// set the HelpInfoUri if it's needed
if (string.IsNullOrEmpty(moduleInfo.HelpInfoUri) && !string.IsNullOrEmpty(remoteHelpInfoUri))
{
moduleInfo.SetHelpInfoUri(remoteHelpInfoUri);
}
// set the Guid if it's needed
if (remoteModuleGuid != Guid.Empty)
{
moduleInfo.SetGuid(remoteModuleGuid);
}
result.Add(moduleInfo);
}
}
}
return result;
}
private PSModuleInfo ImportModule_RemotelyViaPsrpSession_SinglePreimportedModule(
ImportModuleOptions importModuleOptions,
string remoteModuleName,
Version remoteModuleVersion,
PSSession psSession)
{
string temporaryModulePath = RemoteDiscoveryHelper.GetModulePath(
remoteModuleName,
remoteModuleVersion,
psSession.ComputerName,
this.Context.CurrentRunspace);
string wildcardEscapedPath = WildcardPattern.Escape(temporaryModulePath);
try
{
//
// avoid importing a module twice
//
string localPsm1File = Path.Combine(temporaryModulePath, Path.GetFileName(temporaryModulePath) + ".psm1");
PSModuleInfo alreadyImportedModule = this.IsModuleImportUnnecessaryBecauseModuleIsAlreadyLoaded(
localPsm1File, this.BasePrefix, importModuleOptions);
if (alreadyImportedModule != null)
{
return alreadyImportedModule;
}
//
// create proxy module in a temporary folder
//
using (var powerShell = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace))
{
powerShell.AddCommand("Export-PSSession");
powerShell.AddParameter("OutputModule", wildcardEscapedPath);
if (!importModuleOptions.NoClobberExportPSSession)
{
powerShell.AddParameter("AllowClobber", true);
}
powerShell.AddParameter("Module", remoteModuleName); // remoteModulePath is currently unsupported by Get-Command and implicit remoting
powerShell.AddParameter("Force", true);
powerShell.AddParameter("FormatTypeName", "*");
powerShell.AddParameter("Session", psSession);
string errorMessageTemplate = string.Format(
CultureInfo.InvariantCulture,
Modules.RemoteDiscoveryFailedToGenerateProxyForRemoteModule,
remoteModuleName);
if (!RemoteDiscoveryHelper.InvokePowerShell(powerShell, this, errorMessageTemplate, this.CancellationToken).Any())
{
return null;
}
}
//
// rename the psd1 file
//
string localPsd1File = Path.Combine(temporaryModulePath, remoteModuleName + ".psd1");
if (File.Exists(localPsd1File))
{
File.Delete(localPsd1File);
}
File.Move(
sourceFileName: Path.Combine(temporaryModulePath, Path.GetFileName(temporaryModulePath) + ".psd1"),
destFileName: localPsd1File);
string wildcardEscapedPsd1Path = WildcardPattern.Escape(localPsd1File);
//
// import the proxy module just as any other local module
//
object[] oldArgumentList = this.ArgumentList;
Version originalBaseMinimumVersion = BaseMinimumVersion;
Version originalBaseMaximumVersion = BaseMaximumVersion;
Version originalBaseRequiredVersion = BaseRequiredVersion;
try
{
this.ArgumentList = new object[] { psSession };
// The correct module version has already been imported from the remote session and created locally.
// The locally created module always has a version of 1.0 regardless of the actual module version
// imported from the remote session, and version checking is no longer needed and will not work while
// importing this created local module.
BaseMinimumVersion = null;
BaseMaximumVersion = null;
BaseRequiredVersion = null;
ImportModule_LocallyViaName(importModuleOptions, wildcardEscapedPsd1Path);
}
finally
{
this.ArgumentList = oldArgumentList;
BaseMinimumVersion = originalBaseMinimumVersion;
BaseMaximumVersion = originalBaseMaximumVersion;
BaseRequiredVersion = originalBaseRequiredVersion;
}
//
// make sure the temporary folder gets removed when the module is removed
//
string psm1Path = Path.Combine(temporaryModulePath, Path.GetFileName(temporaryModulePath) + ".psm1");
if (!TryGetFromModuleTable(psm1Path, out PSModuleInfo moduleInfo, toRemove: true))
{
if (Directory.Exists(temporaryModulePath))
{
Directory.Delete(temporaryModulePath, recursive: true);
}
return null;
}
const string onRemoveScriptBody = @"
Microsoft.PowerShell.Management\Remove-Item `
-LiteralPath $temporaryModulePath `
-Force `
-Recurse `
-ErrorAction SilentlyContinue
if ($null -ne $previousOnRemoveScript)
{
& $previousOnRemoveScript $args
}
";
ScriptBlock onRemoveScriptBlock = this.Context.Engine.ParseScriptBlock(onRemoveScriptBody, false);
onRemoveScriptBlock = onRemoveScriptBlock.GetNewClosure(); // create a separate scope for variables set below
onRemoveScriptBlock.Module.SessionState.PSVariable.Set("temporaryModulePath", temporaryModulePath);
onRemoveScriptBlock.Module.SessionState.PSVariable.Set("previousOnRemoveScript", moduleInfo.OnRemove);
moduleInfo.OnRemove = onRemoveScriptBlock;
return moduleInfo;
}
catch
{
if (Directory.Exists(temporaryModulePath))
{
Directory.Delete(temporaryModulePath, recursive: true);
}
throw;
}
}
#endregion PSSession parameterset
#region CimSession parameterset
private static bool IsNonEmptyManifestField(Hashtable manifestData, string key)
{
object value = manifestData[key];
if (value == null)
{
return false;
}
object[] array;
if (LanguagePrimitives.TryConvertTo(value, CultureInfo.InvariantCulture, out array))
{
return array.Length != 0;
}
else
{
return true;
}
}
private bool IsMixedModePsCimModule(RemoteDiscoveryHelper.CimModule cimModule)
{
string temporaryModuleManifestPath = RemoteDiscoveryHelper.GetModulePath(cimModule.ModuleName, null, string.Empty, this.Context.CurrentRunspace);
bool containedErrors = false;
RemoteDiscoveryHelper.CimModuleFile mainManifestFile = cimModule.MainManifest;
if (mainManifestFile == null)
{
return true;
}
Hashtable manifestData = RemoteDiscoveryHelper.ConvertCimModuleFileToManifestHashtable(
mainManifestFile,
temporaryModuleManifestPath,
this,
ref containedErrors);
if (containedErrors || manifestData == null)
{
return false;
}
if (IsNonEmptyManifestField(manifestData, "ScriptsToProcess") ||
IsNonEmptyManifestField(manifestData, "RequiredAssemblies"))
{
return true;
}
int numberOfSubmodules = 0;
string[] nestedModules = null;
if (LanguagePrimitives.TryConvertTo(manifestData["NestedModules"], CultureInfo.InvariantCulture, out nestedModules))
{
if (nestedModules != null)
{
numberOfSubmodules += nestedModules.Length;
}
}
object rootModuleValue = manifestData["RootModule"];
if (rootModuleValue != null)
{
string rootModule;
if (LanguagePrimitives.TryConvertTo(rootModuleValue, CultureInfo.InvariantCulture, out rootModule))
{
if (!string.IsNullOrEmpty(rootModule))
{
numberOfSubmodules += 1;
}
}
}
else
{
object moduleToProcessValue = manifestData["ModuleToProcess"];
string moduleToProcess;
if (moduleToProcessValue != null && LanguagePrimitives.TryConvertTo(moduleToProcessValue, CultureInfo.InvariantCulture, out moduleToProcess))
{
if (!string.IsNullOrEmpty(moduleToProcess))
{
numberOfSubmodules += 1;
}
}
}
int numberOfCmdletizationFiles = 0;
foreach (var moduleFile in cimModule.ModuleFiles)
{
if (moduleFile.FileCode == RemoteDiscoveryHelper.CimFileCode.CmdletizationV1)
numberOfCmdletizationFiles++;
}
bool isMixedModePsCimModule = numberOfSubmodules > numberOfCmdletizationFiles;
return isMixedModePsCimModule;
}
private void ImportModule_RemotelyViaCimSession(
ImportModuleOptions importModuleOptions,
string[] moduleNames,
CimSession cimSession,
Uri resourceUri,
string cimNamespace)
{
//
// find all remote PS-CIM modules
//
IEnumerable<RemoteDiscoveryHelper.CimModule> remoteModules = RemoteDiscoveryHelper.GetCimModules(
cimSession,
resourceUri,
cimNamespace,
moduleNames,
false /* onlyManifests */,
this,
this.CancellationToken).ToList();
IEnumerable<RemoteDiscoveryHelper.CimModule> remotePsCimModules = remoteModules.Where(static cimModule => cimModule.IsPsCimModule);
IEnumerable<string> remotePsrpModuleNames = remoteModules.Where(static cimModule => !cimModule.IsPsCimModule).Select(static cimModule => cimModule.ModuleName);
foreach (string psrpModuleName in remotePsrpModuleNames)
{
string errorMessage = string.Format(
CultureInfo.InvariantCulture,
Modules.PsModuleOverCimSessionError,
psrpModuleName);
ErrorRecord errorRecord = new ErrorRecord(
new ArgumentException(errorMessage),
"PsModuleOverCimSessionError",
ErrorCategory.InvalidArgument,
psrpModuleName);
this.WriteError(errorRecord);
}
//
// report an error if some modules were not found
//
IEnumerable<string> allFoundModuleNames = remoteModules.Select(static cimModule => cimModule.ModuleName).ToList();
foreach (string requestedModuleName in moduleNames)
{
var wildcardPattern = WildcardPattern.Get(requestedModuleName, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant);
bool requestedModuleWasFound = allFoundModuleNames.Any(foundModuleName => wildcardPattern.IsMatch(foundModuleName));
if (!requestedModuleWasFound)
{
string message = StringUtil.Format(Modules.ModuleNotFound, requestedModuleName);
FileNotFoundException fnf = new FileNotFoundException(message);
ErrorRecord er = new ErrorRecord(fnf, "Modules_ModuleNotFound",
ErrorCategory.ResourceUnavailable, requestedModuleName);
WriteError(er);
}
}
//
// import the PS-CIM modules
//
foreach (RemoteDiscoveryHelper.CimModule remoteCimModule in remotePsCimModules)
{
ImportModule_RemotelyViaCimModuleData(importModuleOptions, remoteCimModule, cimSession);
// we don't know the version of the module
ApplicationInsightsTelemetry.SendModuleTelemetryMetric(TelemetryType.ModuleLoad, remoteCimModule.ModuleName);
}
}
private bool IsPs1xmlFileHelper_IsPresentInEntries(RemoteDiscoveryHelper.CimModuleFile cimModuleFile, List<string> manifestEntries)
{
const string ps1xmlExt = ".ps1xml";
string fileName = cimModuleFile.FileName;
foreach (string entry in manifestEntries)
{
if (entry.EndsWith(fileName, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
foreach (string entry in manifestEntries)
{
string tempName = entry.EndsWith(ps1xmlExt, StringComparison.OrdinalIgnoreCase) ? entry : entry + ps1xmlExt;
string resolvedPath = ResolveRootedFilePath(tempName, Context);
if (resolvedPath is not null && resolvedPath.EndsWith(fileName, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
private bool IsPs1xmlFileHelper(RemoteDiscoveryHelper.CimModuleFile cimModuleFile, Hashtable manifestData, string goodKey, string badKey)
{
if (!Path.GetExtension(cimModuleFile.FileName).Equals(".ps1xml", StringComparison.OrdinalIgnoreCase))
{
return false;
}
List<string> goodEntries;
if (!this.GetListOfStringsFromData(manifestData, null, goodKey, 0, out goodEntries))
{
goodEntries = new List<string>();
}
goodEntries ??= new List<string>();
List<string> badEntries;
if (!this.GetListOfStringsFromData(manifestData, null, badKey, 0, out badEntries))
{
badEntries = new List<string>();
}
badEntries ??= new List<string>();
bool presentInGoodEntries = IsPs1xmlFileHelper_IsPresentInEntries(cimModuleFile, goodEntries);
bool presentInBadEntries = IsPs1xmlFileHelper_IsPresentInEntries(cimModuleFile, badEntries);
return presentInGoodEntries && !presentInBadEntries;
}
private bool IsTypesPs1XmlFile(RemoteDiscoveryHelper.CimModuleFile cimModuleFile, Hashtable manifestData)
{
return IsPs1xmlFileHelper(cimModuleFile, manifestData, goodKey: "TypesToProcess", badKey: "FormatsToProcess");
}
private bool IsFormatPs1XmlFile(RemoteDiscoveryHelper.CimModuleFile cimModuleFile, Hashtable manifestData)
{
return IsPs1xmlFileHelper(cimModuleFile, manifestData, goodKey: "FormatsToProcess", badKey: "TypesToProcess");
}
private static bool IsCmdletizationFile(RemoteDiscoveryHelper.CimModuleFile cimModuleFile)
{
return cimModuleFile.FileCode == RemoteDiscoveryHelper.CimFileCode.CmdletizationV1;
}
private static IEnumerable<string> CreateCimModuleFiles(
RemoteDiscoveryHelper.CimModule remoteCimModule,
RemoteDiscoveryHelper.CimFileCode fileCode,
Func<RemoteDiscoveryHelper.CimModuleFile, bool> filesFilter,
string temporaryModuleDirectory)
{
string fileNameTemplate = null;
switch (fileCode)
{
case RemoteDiscoveryHelper.CimFileCode.CmdletizationV1:
fileNameTemplate = "{0}_{1}.cdxml";
break;
case RemoteDiscoveryHelper.CimFileCode.TypesV1:
fileNameTemplate = "{0}_{1}.types.ps1xml";
break;
case RemoteDiscoveryHelper.CimFileCode.FormatV1:
fileNameTemplate = "{0}_{1}.format.ps1xml";
break;
default:
Dbg.Assert(false, "Unrecognized file code");
break;
}
List<string> relativePathsToCreatedFiles = new List<string>();
foreach (RemoteDiscoveryHelper.CimModuleFile file in remoteCimModule.ModuleFiles)
{
if (!filesFilter(file))
{
continue;
}
string originalFileName = Path.GetFileName(file.FileName);
string fileName = string.Format(
CultureInfo.InvariantCulture,
fileNameTemplate,
originalFileName.Substring(0, Math.Min(originalFileName.Length, 20)),
Path.GetRandomFileName());
relativePathsToCreatedFiles.Add(fileName);
string fullPath = Path.Combine(temporaryModuleDirectory, fileName);
File.WriteAllBytes(
fullPath,
file.RawFileData);
#if !UNIX
AlternateDataStreamUtilities.SetZoneOfOrigin(fullPath, SecurityZone.Intranet);
#endif
}
return relativePathsToCreatedFiles;
}
private PSModuleInfo ImportModule_RemotelyViaCimModuleData(
ImportModuleOptions importModuleOptions,
RemoteDiscoveryHelper.CimModule remoteCimModule,
CimSession cimSession)
{
try
{
if (remoteCimModule.MainManifest == null)
{
string errorMessage = string.Format(
CultureInfo.InvariantCulture,
Modules.EmptyModuleManifest,
remoteCimModule.ModuleName + ".psd1");
ArgumentException argumentException = new ArgumentException(errorMessage);
throw argumentException;
}
bool containedErrors = false;
PSModuleInfo moduleInfo = null;
//
// read the original manifest
//
string temporaryModuleDirectory = RemoteDiscoveryHelper.GetModulePath(
remoteCimModule.ModuleName,
null,
cimSession.ComputerName,
this.Context.CurrentRunspace);
string temporaryModuleManifestPath = Path.Combine(
temporaryModuleDirectory,
remoteCimModule.ModuleName + ".psd1");
Hashtable data = null;
Hashtable localizedData = null;
{
ScriptBlockAst scriptBlockAst = null;
Token[] throwAwayTokens;
ParseError[] parseErrors;
scriptBlockAst = Parser.ParseInput(
remoteCimModule.MainManifest.FileData,
temporaryModuleManifestPath,
out throwAwayTokens,
out parseErrors);
if ((scriptBlockAst == null) ||
(parseErrors != null && parseErrors.Length > 0))
{
throw new ParseException(parseErrors);
}
ScriptBlock scriptBlock = new ScriptBlock(scriptBlockAst, isFilter: false);
data = LoadModuleManifestData(
temporaryModuleManifestPath,
scriptBlock,
ModuleManifestMembers,
ManifestProcessingFlags.NullOnFirstError | ManifestProcessingFlags.WriteErrors, /* - don't load elements */
ref containedErrors);
if ((data == null) || containedErrors)
{
return null;
}
localizedData = data;
}
//
// flatten module contents and rewrite the manifest to point to the flattened file hierarchy
//
// recalculate module path, taking into account the module version fetched above
Version moduleVersion;
if (!GetScalarFromData<Version>(data, null, "ModuleVersion", 0, out moduleVersion))
{
moduleVersion = null;
}
temporaryModuleDirectory = RemoteDiscoveryHelper.GetModulePath(
remoteCimModule.ModuleName,
moduleVersion,
cimSession.ComputerName,
this.Context.CurrentRunspace);
temporaryModuleManifestPath = Path.Combine(
temporaryModuleDirectory,
remoteCimModule.ModuleName + ".psd1");
// avoid loading an already loaded module
PSModuleInfo alreadyImportedModule = this.IsModuleImportUnnecessaryBecauseModuleIsAlreadyLoaded(
temporaryModuleManifestPath, this.BasePrefix, importModuleOptions);
if (alreadyImportedModule != null)
{
return alreadyImportedModule;
}
try
{
Directory.CreateDirectory(temporaryModuleDirectory);
IEnumerable<string> typesToProcess = CreateCimModuleFiles(
remoteCimModule,
RemoteDiscoveryHelper.CimFileCode.TypesV1,
cimModuleFile => IsTypesPs1XmlFile(cimModuleFile, data),
temporaryModuleDirectory);
IEnumerable<string> formatsToProcess = CreateCimModuleFiles(
remoteCimModule,
RemoteDiscoveryHelper.CimFileCode.FormatV1,
cimModuleFile => IsFormatPs1XmlFile(cimModuleFile, data),
temporaryModuleDirectory);
IEnumerable<string> nestedModules = CreateCimModuleFiles(
remoteCimModule,
RemoteDiscoveryHelper.CimFileCode.CmdletizationV1,
IsCmdletizationFile,
temporaryModuleDirectory);
data = RemoteDiscoveryHelper.RewriteManifest(
data,
nestedModules: nestedModules,
typesToProcess: typesToProcess,
formatsToProcess: formatsToProcess);
localizedData = RemoteDiscoveryHelper.RewriteManifest(localizedData);
//
// import the module
// (from memory - this avoids the authenticode signature problems
// that would be introduced by rewriting the contents of the manifest)
//
moduleInfo = LoadModuleManifest(
temporaryModuleManifestPath,
null, // scriptInfo
data,
localizedData,
ManifestProcessingFlags.LoadElements | ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.NullOnFirstError,
BaseMinimumVersion,
BaseMaximumVersion,
BaseRequiredVersion,
BaseGuid,
ref importModuleOptions,
ref containedErrors);
if (moduleInfo == null)
{
return null;
}
foreach (PSModuleInfo nestedModule in moduleInfo.NestedModules)
{
Type cmdletAdapter;
bool gotCmdletAdapter = PSPrimitiveDictionary.TryPathGet(
nestedModule.PrivateData as IDictionary,
out cmdletAdapter,
"CmdletsOverObjects",
"CmdletAdapter");
Dbg.Assert(gotCmdletAdapter, "PrivateData from cdxml should always include cmdlet adapter");
if (!cmdletAdapter.AssemblyQualifiedName.Equals(StringLiterals.DefaultCmdletAdapter, StringComparison.OrdinalIgnoreCase))
{
string errorMessage = string.Format(
CultureInfo.InvariantCulture,
CmdletizationCoreResources.ImportModule_UnsupportedCmdletAdapter,
cmdletAdapter.FullName);
ErrorRecord errorRecord = new ErrorRecord(
new InvalidOperationException(errorMessage),
"UnsupportedCmdletAdapter",
ErrorCategory.InvalidData,
cmdletAdapter);
this.ThrowTerminatingError(errorRecord);
}
}
if (IsMixedModePsCimModule(remoteCimModule))
{
// warn that some commands have not been imported
string warningMessage = string.Format(
CultureInfo.InvariantCulture,
Modules.MixedModuleOverCimSessionWarning,
remoteCimModule.ModuleName);
this.WriteWarning(warningMessage);
}
//
// store the default session
//
Dbg.Assert(moduleInfo.ModuleType == ModuleType.Manifest, "Remote discovery should always produce a 'manifest' module");
Dbg.Assert(moduleInfo.NestedModules != null, "Remote discovery should always produce a 'manifest' module with nested modules entry");
Dbg.Assert(moduleInfo.NestedModules.Count > 0, "Remote discovery should always produce a 'manifest' module with some nested modules");
foreach (PSModuleInfo nestedModule in moduleInfo.NestedModules)
{
IDictionary cmdletsOverObjectsPrivateData;
bool cmdletsOverObjectsPrivateDataWasFound = PSPrimitiveDictionary.TryPathGet<IDictionary>(
nestedModule.PrivateData as IDictionary,
out cmdletsOverObjectsPrivateData,
ScriptWriter.PrivateDataKey_CmdletsOverObjects);
Dbg.Assert(cmdletsOverObjectsPrivateDataWasFound, "Cmdletization should always set the PrivateData properly");
cmdletsOverObjectsPrivateData[ScriptWriter.PrivateDataKey_DefaultSession] = cimSession;
}
//
// make sure the temporary folder gets removed when the module is removed
//
const string onRemoveScriptBody =
@"
Microsoft.PowerShell.Management\Remove-Item `
-LiteralPath $temporaryModulePath `
-Force `
-Recurse `
-ErrorAction SilentlyContinue
if ($null -ne $previousOnRemoveScript)
{
& $previousOnRemoveScript $args
}
";
ScriptBlock onRemoveScriptBlock = this.Context.Engine.ParseScriptBlock(onRemoveScriptBody, false);
onRemoveScriptBlock = onRemoveScriptBlock.GetNewClosure();
// create a separate scope for variables set below
onRemoveScriptBlock.Module.SessionState.PSVariable.Set("temporaryModulePath", temporaryModuleDirectory);
onRemoveScriptBlock.Module.SessionState.PSVariable.Set("previousOnRemoveScript", moduleInfo.OnRemove);
moduleInfo.OnRemove = onRemoveScriptBlock;
//
// Some processing common for local and remote modules
//
AddModuleToModuleTables(
this.Context,
this.TargetSessionState.Internal,
moduleInfo);
if (BasePassThru)
{
WriteObject(moduleInfo);
}
return moduleInfo;
}
catch
{
if (Directory.Exists(temporaryModuleDirectory))
{
Directory.Delete(temporaryModuleDirectory, recursive: true);
}
throw;
}
finally
{
if (moduleInfo == null)
{
if (Directory.Exists(temporaryModuleDirectory))
{
Directory.Delete(temporaryModuleDirectory, recursive: true);
}
}
}
}
catch (Exception e)
{
ErrorRecord errorRecord = RemoteDiscoveryHelper.GetErrorRecordForProcessingOfCimModule(e, remoteCimModule.ModuleName);
this.WriteError(errorRecord);
return null;
}
}
#endregion CimSession parameterset
#endregion Remote import
#region Cancellation support
private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
private CancellationToken CancellationToken
{
get
{
return _cancellationTokenSource.Token;
}
}
/// <summary>
/// When overridden in the derived class, interrupts currently
/// running code within the command. It should interrupt BeginProcessing,
/// ProcessRecord, and EndProcessing.
/// Default implementation in the base class just returns.
/// </summary>
protected override void StopProcessing()
{
_cancellationTokenSource.Cancel();
}
#endregion
#region IDisposable Members
/// <summary>
/// Release all resources.
/// </summary>
public void Dispose()
{
if (_disposed)
{
return;
}
_cancellationTokenSource.Dispose();
_disposed = true;
}
private bool _disposed;
#endregion
/// <summary>
/// BeginProcessing override.
/// </summary>
protected override void BeginProcessing()
{
// Make sure that only one of (Global | Scope) is specified
if (Global.IsPresent && _isScopeSpecified)
{
InvalidOperationException ioe = new InvalidOperationException(Modules.GlobalAndScopeParameterCannotBeSpecifiedTogether);
ErrorRecord er = new ErrorRecord(ioe, "Modules_GlobalAndScopeParameterCannotBeSpecifiedTogether",
ErrorCategory.InvalidOperation, null);
ThrowTerminatingError(er);
}
if (!string.IsNullOrEmpty(Scope) && Scope.Equals(StringLiterals.Global, StringComparison.OrdinalIgnoreCase))
{
base.BaseGlobal = true;
}
}
/// <summary>
/// Load the specified modules...
/// </summary>
/// <remarks>
/// Examples:
/// c:\temp\mdir\mdir.psm1 # load absolute path
/// ./mdir.psm1 # load relative path
/// c:\temp\mdir\mdir # resolve by using extensions. mdir is a directory, mdir.xxx is a file.
/// c:\temp\mdir # load default module if mdir is directory
/// module # $PSScriptRoot/module/module.psd1 (ps1,psm1,dll)
/// module/examplemodule.psm1 # $PSScriptRoot/module/module.psm1
/// module/examplemodule # $PSScriptRoot/module/examplemodule.XXX if examplemodule is not a directory...
/// module/examplemodule # $PSScriptRoot/module/examplemodule is a directory and $PSScriptRoot/module/examplemodule/examplemodule.XXX exists
/// module/examplemodule/examplemodule.XXX
/// </remarks>
protected override void ProcessRecord()
{
if (BaseMaximumVersion != null && BaseMinimumVersion != null && BaseMaximumVersion < BaseMinimumVersion)
{
string message = StringUtil.Format(Modules.MinimumVersionAndMaximumVersionInvalidRange, BaseMinimumVersion, BaseMaximumVersion);
throw new PSArgumentOutOfRangeException(message);
}
ImportModuleOptions importModuleOptions = new ImportModuleOptions();
importModuleOptions.NoClobber = NoClobber;
if (!string.IsNullOrEmpty(Scope) && Scope.Equals(StringLiterals.Local, StringComparison.OrdinalIgnoreCase))
{
importModuleOptions.Local = true;
}
if (this.ParameterSetName.Equals(ParameterSet_ModuleInfo, StringComparison.OrdinalIgnoreCase))
{
// Process all of the specified PSModuleInfo objects. These would typically be coming in as a result
// of doing Get-Module -list
foreach (PSModuleInfo module in ModuleInfo)
{
ApplicationInsightsTelemetry.SendModuleTelemetryMetric(TelemetryType.ModuleLoad, module);
RemoteDiscoveryHelper.DispatchModuleInfoProcessing(
module,
localAction: () =>
{
ImportModule_ViaLocalModuleInfo(importModuleOptions, module);
SetModuleBaseForEngineModules(module.Name, this.Context);
},
cimSessionAction: (cimSession, resourceUri, cimNamespace) => ImportModule_RemotelyViaCimSession(
importModuleOptions,
new string[] { module.Name },
cimSession,
resourceUri,
cimNamespace),
psSessionAction: psSession => ImportModule_RemotelyViaPsrpSession(
importModuleOptions,
new string[] { module.Path },
null,
psSession));
}
}
else if (this.ParameterSetName.Equals(ParameterSet_Assembly, StringComparison.OrdinalIgnoreCase))
{
// Now load all of the supplied assemblies...
foreach (Assembly suppliedAssembly in Assembly)
{
// we don't know what the version of the module is.
ApplicationInsightsTelemetry.SendModuleTelemetryMetric(TelemetryType.ModuleLoad, suppliedAssembly.GetName().Name);
ImportModule_ViaAssembly(importModuleOptions, suppliedAssembly);
}
}
else if (this.ParameterSetName.Equals(ParameterSet_Name, StringComparison.OrdinalIgnoreCase))
{
foreach (string name in Name)
{
ImportModule_LocallyViaName_WithTelemetry(importModuleOptions, name);
}
}
else if (this.ParameterSetName.Equals(ParameterSet_ViaPsrpSession, StringComparison.OrdinalIgnoreCase))
{
ImportModule_RemotelyViaPsrpSession(importModuleOptions, this.Name, null, this.PSSession);
}
else if (this.ParameterSetName.Equals(ParameterSet_ViaCimSession, StringComparison.OrdinalIgnoreCase))
{
ImportModule_RemotelyViaCimSession(importModuleOptions, this.Name, this.CimSession, this.CimResourceUri, this.CimNamespace);
}
else if (this.ParameterSetName.Equals(ParameterSet_FQName, StringComparison.OrdinalIgnoreCase))
{
foreach (var modulespec in FullyQualifiedName)
{
ImportModule_LocallyViaFQName(importModuleOptions, modulespec);
}
}
else if (this.ParameterSetName.Equals(ParameterSet_FQName_ViaPsrpSession, StringComparison.OrdinalIgnoreCase))
{
ImportModule_RemotelyViaPsrpSession(importModuleOptions, null, FullyQualifiedName, this.PSSession);
foreach (ModuleSpecification modulespec in FullyQualifiedName)
{
ApplicationInsightsTelemetry.SendModuleTelemetryMetric(TelemetryType.ModuleLoad, modulespec.Name);
}
}
else if (this.ParameterSetName.Equals(ParameterSet_ViaWinCompat, StringComparison.OrdinalIgnoreCase)
|| this.ParameterSetName.Equals(ParameterSet_FQName_ViaWinCompat, StringComparison.OrdinalIgnoreCase))
{
if (this.UseWindowsPowerShell)
{
ImportModulesUsingWinCompat(this.Name, this.FullyQualifiedName, importModuleOptions);
}
}
else
{
Dbg.Assert(false, "Unrecognized parameter set");
}
}
private bool IsModuleInDenyList(string[] moduleDenyList, string moduleName, ModuleSpecification moduleSpec)
{
Debug.Assert(string.IsNullOrEmpty(moduleName) ^ (moduleSpec == null), "Either moduleName or moduleSpec must be specified");
// moduleName can be just a module name and it also can be a full path to psd1 from which we need to extract the module name
string exactModuleName = ModuleIntrinsics.GetModuleName(moduleSpec == null ? moduleName : moduleSpec.Name);
bool match = false;
foreach (var deniedModuleName in moduleDenyList)
{
// use case-insensitive module name comparison
match = exactModuleName.Equals(deniedModuleName, StringComparison.InvariantCultureIgnoreCase);
if (match)
{
string errorMessage = string.Format(CultureInfo.InvariantCulture, Modules.WinCompatModuleInDenyList, exactModuleName);
InvalidOperationException exception = new InvalidOperationException(errorMessage);
ErrorRecord er = new ErrorRecord(exception, "Modules_ModuleInWinCompatDenyList", ErrorCategory.ResourceUnavailable, exactModuleName);
WriteError(er);
break;
}
}
return match;
}
private IEnumerable<T> FilterModuleCollection<T>(IEnumerable<T> moduleCollection)
{
if (moduleCollection is null)
{
return null;
}
// The ModuleDeny list is cached in PowerShellConfig object
string[] moduleDenyList = PowerShellConfig.Instance.GetWindowsPowerShellCompatibilityModuleDenyList();
if (moduleDenyList is null || moduleDenyList.Length == 0)
{
return moduleCollection;
}
var filteredModuleCollection = new List<T>();
foreach (var module in moduleCollection)
{
if (!IsModuleInDenyList(moduleDenyList, module as string, module as ModuleSpecification))
{
filteredModuleCollection.Add(module);
}
}
return filteredModuleCollection;
}
private void PrepareNoClobberWinCompatModuleImport(string moduleName, ModuleSpecification moduleSpec, ref ImportModuleOptions importModuleOptions)
{
Debug.Assert(string.IsNullOrEmpty(moduleName) ^ (moduleSpec == null), "Either moduleName or moduleSpec must be specified");
// moduleName can be just a module name and it also can be a full path to psd1 from which we need to extract the module name
string moduleToLoad = ModuleIntrinsics.GetModuleName(moduleSpec is null ? moduleName : moduleSpec.Name);
var isBuiltInModule = BuiltInModules.TryGetValue(moduleToLoad, out string normalizedName);
if (isBuiltInModule)
{
moduleToLoad = normalizedName;
}
string[] noClobberModuleList = PowerShellConfig.Instance.GetWindowsPowerShellCompatibilityNoClobberModuleList();
if (isBuiltInModule || noClobberModuleList?.Contains(moduleToLoad, StringComparer.OrdinalIgnoreCase) == true)
{
bool shouldLoadModuleLocally = true;
if (isBuiltInModule)
{
PSSnapInInfo loadedSnapin = Context.CurrentRunspace.InitialSessionState.GetPSSnapIn(moduleToLoad);
shouldLoadModuleLocally = loadedSnapin is null;
if (shouldLoadModuleLocally)
{
// If it is one of built-in modules, first try loading it from $PSHOME\Modules, otherwise rely on $env:PSModulePath.
string expectedCoreModulePath = Path.Combine(ModuleIntrinsics.GetPSHomeModulePath(), moduleToLoad);
if (Directory.Exists(expectedCoreModulePath))
{
moduleToLoad = expectedCoreModulePath;
}
}
}
if (shouldLoadModuleLocally)
{
// Here we want to load a core-edition compatible version of the module, so the loading procedure will skip
// the 'System32' module path when searching. Also, we want to suppress writing out errors in case that a
// core-compatible version of the module cannot be found, because:
// 1. that's OK as long as it's not a PowerShell built-in module such as the 'Utility' moudle;
// 2. the error message will be confusing to the user.
bool savedValue = importModuleOptions.SkipSystem32ModulesAndSuppressError;
importModuleOptions.SkipSystem32ModulesAndSuppressError = true;
PSModuleInfo moduleInfo = moduleSpec is null
? ImportModule_LocallyViaName_WithTelemetry(importModuleOptions, moduleToLoad)
: ImportModule_LocallyViaFQName(
importModuleOptions,
new ModuleSpecification()
{
Guid = moduleSpec.Guid,
MaximumVersion = moduleSpec.MaximumVersion,
Version = moduleSpec.Version,
RequiredVersion = moduleSpec.RequiredVersion,
Name = moduleToLoad
});
// If we failed to load a core-compatible version of a built-in module, we should stop trying to load the
// module in 'WinCompat' mode and report an error. This could happen when a user didn't correctly deploy
// the built-in modules, which would result in very confusing errors when the module auto-loading silently
// attempts to load those built-in modules in 'WinCompat' mode from the 'System32' module path.
//
// If the loading failed but it's NOT a built-in module, then it's fine to ignore this failure and continue
// to load the module in 'WinCompat' mode.
if (moduleInfo is null && isBuiltInModule)
{
throw new InvalidOperationException(
StringUtil.Format(
Modules.CannotFindCoreCompatibleBuiltInModule,
moduleToLoad));
}
importModuleOptions.SkipSystem32ModulesAndSuppressError = savedValue;
}
importModuleOptions.NoClobberExportPSSession = true;
}
}
internal override IList<PSModuleInfo> ImportModulesUsingWinCompat(IEnumerable<string> moduleNames, IEnumerable<ModuleSpecification> moduleFullyQualifiedNames, ImportModuleOptions importModuleOptions)
{
IList<PSModuleInfo> moduleProxyList = new List<PSModuleInfo>();
#if !UNIX
// one of the two parameters can be passed: either ModuleNames (most of the time) or ModuleSpecifications (they are used in different parameter sets)
IEnumerable<string> filteredModuleNames = FilterModuleCollection(moduleNames);
IEnumerable<ModuleSpecification> filteredModuleFullyQualifiedNames = FilterModuleCollection(moduleFullyQualifiedNames);
// do not setup WinCompat resources if we have no modules to import
if (filteredModuleNames?.Any() != true && filteredModuleFullyQualifiedNames?.Any() != true)
{
return moduleProxyList;
}
// perform necessary preparations if module has to be imported with NoClobber mode
if (filteredModuleNames != null)
{
foreach (string moduleName in filteredModuleNames)
{
PrepareNoClobberWinCompatModuleImport(moduleName, null, ref importModuleOptions);
}
}
if (filteredModuleFullyQualifiedNames != null)
{
foreach (var moduleSpec in filteredModuleFullyQualifiedNames)
{
PrepareNoClobberWinCompatModuleImport(null, moduleSpec, ref importModuleOptions);
}
}
var winPSVersionString = Utils.GetWindowsPowerShellVersionFromRegistry();
if (!winPSVersionString.StartsWith("5.1", StringComparison.OrdinalIgnoreCase))
{
string errorMessage = string.Format(CultureInfo.InvariantCulture, Modules.WinCompatRequredVersionError, winPSVersionString);
throw new InvalidOperationException(errorMessage);
}
PSSession WindowsPowerShellCompatRemotingSession = CreateWindowsPowerShellCompatResources();
if (WindowsPowerShellCompatRemotingSession == null)
{
return new List<PSModuleInfo>();
}
// perform the module import / proxy generation
moduleProxyList = ImportModule_RemotelyViaPsrpSession(importModuleOptions, filteredModuleNames, filteredModuleFullyQualifiedNames, WindowsPowerShellCompatRemotingSession, usingWinCompat: true);
foreach (PSModuleInfo moduleProxy in moduleProxyList)
{
moduleProxy.IsWindowsPowerShellCompatModule = true;
Interlocked.Increment(ref s_WindowsPowerShellCompatUsageCounter);
string message = StringUtil.Format(Modules.WinCompatModuleWarning, moduleProxy.Name, WindowsPowerShellCompatRemotingSession.Name);
WriteWarning(message);
}
// register LocationChanged handler so that $PWD in Windows PS process mirrors local $PWD changes
if (moduleProxyList.Count > 0)
{
// make sure that we add registration only once to a multicast delegate
SyncCurrentLocationDelegate ??= SyncCurrentLocationHandler;
var alreadyregistered = this.SessionState.InvokeCommand.LocationChangedAction?.GetInvocationList().Contains(SyncCurrentLocationDelegate);
if (!alreadyregistered ?? true)
{
this.SessionState.InvokeCommand.LocationChangedAction += SyncCurrentLocationDelegate;
// first sync has to be triggered manually
SyncCurrentLocationHandler(sender: this, args: new LocationChangedEventArgs(sessionState: null, oldPath: null, newPath: this.SessionState.Path.CurrentLocation));
}
}
#endif
return moduleProxyList;
}
private static void SetModuleBaseForEngineModules(string moduleName, System.Management.Automation.ExecutionContext context)
{
// Set modulebase of engine modules to point to $pshome
// This is so that Get-Help can load the correct help.
if (InitialSessionState.IsEngineModule(moduleName))
{
foreach (var m in context.EngineSessionState.ModuleTable.Values)
{
if (m.Name.Equals(moduleName, StringComparison.OrdinalIgnoreCase))
{
m.SetModuleBase(Utils.DefaultPowerShellAppBase);
// Also set ModuleBase for nested modules of Engine modules
foreach (var nestedModule in m.NestedModules)
{
nestedModule.SetModuleBase(Utils.DefaultPowerShellAppBase);
}
}
}
foreach (var m in context.Modules.ModuleTable.Values)
{
if (m.Name.Equals(moduleName, StringComparison.OrdinalIgnoreCase))
{
m.SetModuleBase(Utils.DefaultPowerShellAppBase);
// Also set ModuleBase for nested modules of Engine modules
foreach (var nestedModule in m.NestedModules)
{
nestedModule.SetModuleBase(Utils.DefaultPowerShellAppBase);
}
}
}
}
}
}
}
|