File size: 186,252 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 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Management.Automation.Remoting;
using System.Management.Automation.Remoting.Client;
using System.Management.Automation.Runspaces;
using System.Threading;
using Dbg = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// This class defines most of the common functionality used
/// across remoting cmdlets.
///
/// It contains tons of utility functions which are used all
/// across the remoting cmdlets.
/// </summary>
public abstract class PSRemotingCmdlet : PSCmdlet
{
#region Overrides
/// <summary>
/// Verifies if remoting cmdlets can be used.
/// </summary>
protected override void BeginProcessing()
{
if (!SkipWinRMCheck)
{
RemotingCommandUtil.CheckRemotingCmdletPrerequisites();
}
}
#endregion Overrides
#region Utility functions
/// <summary>
/// Handle the object obtained from an ObjectStream's reader
/// based on its type.
/// </summary>
internal void WriteStreamObject(Action<Cmdlet> action)
{
action(this);
}
/// <summary>
/// Resolve all the machine names provided. Basically, if a machine
/// name is '.' assume localhost.
/// </summary>
/// <param name="computerNames">Array of computer names to resolve.</param>
/// <param name="resolvedComputerNames">Resolved array of machine names.</param>
protected void ResolveComputerNames(string[] computerNames, out string[] resolvedComputerNames)
{
if (computerNames == null)
{
resolvedComputerNames = new string[1];
resolvedComputerNames[0] = ResolveComputerName(".");
}
else if (computerNames.Length == 0)
{
resolvedComputerNames = Array.Empty<string>();
}
else
{
resolvedComputerNames = new string[computerNames.Length];
for (int i = 0; i < resolvedComputerNames.Length; i++)
{
resolvedComputerNames[i] = ResolveComputerName(computerNames[i]);
}
}
}
/// <summary>
/// Resolves a computer name. If its null or empty
/// its assumed to be localhost.
/// </summary>
/// <param name="computerName">Computer name to resolve.</param>
/// <returns>Resolved computer name.</returns>
protected string ResolveComputerName(string computerName)
{
Diagnostics.Assert(computerName != null, "Null ComputerName");
if (string.Equals(computerName, ".", StringComparison.OrdinalIgnoreCase))
{
// tracer.WriteEvent(ref PSEventDescriptors.PS_EVENT_HOSTNAMERESOLVE);
// tracer.Dispose();
// tracer.OperationalChannel.WriteVerbose(PSEventId.HostNameResolve, PSOpcode.Method, PSTask.CreateRunspace);
return s_LOCALHOST;
}
else
{
return computerName;
}
}
/// <summary>
/// Load the resource corresponding to the specified errorId and
/// return the message as a string.
/// </summary>
/// <param name="resourceString">resource String which holds the message
/// </param>
/// <returns>Error message loaded from appropriate resource cache.</returns>
internal string GetMessage(string resourceString)
{
string message = GetMessage(resourceString, null);
return message;
}
/// <summary>
/// </summary>
/// <param name="resourceString"></param>
/// <param name="args"></param>
/// <returns></returns>
internal string GetMessage(string resourceString, params object[] args)
{
string message;
if (args != null)
{
message = StringUtil.Format(resourceString, args);
}
else
{
message = resourceString;
}
return message;
}
#endregion Utility functions
#region Private Members
private static readonly string s_LOCALHOST = "localhost";
// private PSETWTracer tracer = PSETWTracer.GetETWTracer(PSKeyword.Cmdlets);
#endregion Private Members
#region Protected Members
/// <summary>
/// Computername parameter set.
/// </summary>
protected const string ComputerNameParameterSet = "ComputerName";
/// <summary>
/// Computername with session instance ID parameter set.
/// </summary>
protected const string ComputerInstanceIdParameterSet = "ComputerInstanceId";
/// <summary>
/// Container ID parameter set.
/// </summary>
protected const string ContainerIdParameterSet = "ContainerId";
/// <summary>
/// VM guid parameter set.
/// </summary>
protected const string VMIdParameterSet = "VMId";
/// <summary>
/// VM name parameter set.
/// </summary>
protected const string VMNameParameterSet = "VMName";
/// <summary>
/// SSH host parameter set.
/// </summary>
protected const string SSHHostParameterSet = "SSHHost";
/// <summary>
/// SSH host parmeter set supporting hash connection parameters.
/// </summary>
protected const string SSHHostHashParameterSet = "SSHHostHashParam";
/// <summary>
/// Runspace parameter set.
/// </summary>
protected const string SessionParameterSet = "Session";
/// <summary>
/// Parameter set to use Windows PowerShell.
/// </summary>
protected const string UseWindowsPowerShellParameterSet = "UseWindowsPowerShellParameterSet";
/// <summary>
/// Default shellname.
/// </summary>
protected const string DefaultPowerShellRemoteShellName = WSManNativeApi.ResourceURIPrefix + "Microsoft.PowerShell";
/// <summary>
/// Default application name for the connection uri.
/// </summary>
protected const string DefaultPowerShellRemoteShellAppName = "WSMan";
#endregion Protected Members
#region Internal Members
/// <summary>
/// Skip checking for WinRM.
/// </summary>
internal bool SkipWinRMCheck { get; set; } = false;
#endregion Internal Members
#region Protected Methods
/// <summary>
/// Determines the shellname to use based on the following order:
/// 1. ShellName parameter specified
/// 2. DEFAULTREMOTESHELLNAME variable set
/// 3. PowerShell.
/// </summary>
/// <returns>The shell to launch in the remote machine.</returns>
protected string ResolveShell(string shell)
{
string resolvedShell;
if (!string.IsNullOrEmpty(shell))
{
resolvedShell = shell;
}
else
{
resolvedShell = (string)SessionState.Internal.ExecutionContext.GetVariableValue(
SpecialVariables.PSSessionConfigurationNameVarPath, DefaultPowerShellRemoteShellName);
}
return resolvedShell;
}
/// <summary>
/// Determines the appname to be used based on the following order:
/// 1. AppName parameter specified
/// 2. DEFAULTREMOTEAPPNAME variable set
/// 3. WSMan.
/// </summary>
/// <param name="appName">Application name to resolve.</param>
/// <returns>Resolved appname.</returns>
protected string ResolveAppName(string appName)
{
string resolvedAppName;
if (!string.IsNullOrEmpty(appName))
{
resolvedAppName = appName;
}
else
{
resolvedAppName = (string)SessionState.Internal.ExecutionContext.GetVariableValue(
SpecialVariables.PSSessionApplicationNameVarPath,
DefaultPowerShellRemoteShellAppName);
}
return resolvedAppName;
}
#endregion
}
/// <summary>
/// Contains SSH connection information.
/// </summary>
internal struct SSHConnection
{
public string ComputerName;
public string UserName;
public string KeyFilePath;
public int Port;
public string Subsystem;
public int ConnectingTimeout;
public Hashtable Options;
}
/// <summary>
/// Base class for any cmdlet which takes a -Session parameter
/// or a -ComputerName parameter (along with its other associated
/// parameters). The following cmdlets currently fall under this
/// category:
/// 1. New-PSSession
/// 2. Invoke-Expression
/// 3. Start-PSJob.
/// </summary>
public abstract class PSRemotingBaseCmdlet : PSRemotingCmdlet
{
#region Enums
/// <summary>
/// State of virtual machine. This is the same as VMState in
/// \vm\ux\powershell\objects\common\Types.cs.
/// </summary>
internal enum VMState
{
/// <summary>
/// Other. Corresponds to CIM_EnabledLogicalElement.EnabledState = Other.
/// </summary>
Other = 1,
/// <summary>
/// Running. Corresponds to CIM_EnabledLogicalElement.EnabledState = Enabled.
/// </summary>
Running = 2,
/// <summary>
/// Off. Corresponds to CIM_EnabledLogicalElement.EnabledState = Disabled.
/// </summary>
Off = 3,
/// <summary>
/// Stopping. Corresponds to CIM_EnabledLogicalElement.EnabledState = ShuttingDown.
/// </summary>
Stopping = 4,
/// <summary>
/// Saved. Corresponds to CIM_EnabledLogicalElement.EnabledState = Enabled but offline.
/// </summary>
Saved = 6,
/// <summary>
/// Paused. Corresponds to CIM_EnabledLogicalElement.EnabledState = Quiesce.
/// </summary>
Paused = 9,
/// <summary>
/// Starting. EnabledStateStarting. State transition from PowerOff or Saved to Running.
/// </summary>
Starting = 10,
/// <summary>
/// Reset. Corresponds to CIM_EnabledLogicalElement.EnabledState = Reset.
/// </summary>
Reset = 11,
/// <summary>
/// Saving. Corresponds to EnabledStateSaving.
/// </summary>
Saving = 32773,
/// <summary>
/// Pausing. Corresponds to EnabledStatePausing.
/// </summary>
Pausing = 32776,
/// <summary>
/// Resuming. Corresponds to EnabledStateResuming.
/// </summary>
Resuming = 32777,
/// <summary>
/// FastSaved. EnabledStateFastSuspend.
/// </summary>
FastSaved = 32779,
/// <summary>
/// FastSaving. EnabledStateFastSuspending.
/// </summary>
FastSaving = 32780,
/// <summary>
/// ForceShutdown. Used to force a graceful shutdown of the virtual machine.
/// </summary>
ForceShutdown = 32781,
/// <summary>
/// ForceReboot. Used to force a graceful reboot of the virtual machine.
/// </summary>
ForceReboot = 32782,
/// <summary>
/// RunningCritical. Critical states.
/// </summary>
RunningCritical,
/// <summary>
/// OffCritical. Critical states.
/// </summary>
OffCritical,
/// <summary>
/// StoppingCritical. Critical states.
/// </summary>
StoppingCritical,
/// <summary>
/// SavedCritical. Critical states.
/// </summary>
SavedCritical,
/// <summary>
/// PausedCritical. Critical states.
/// </summary>
PausedCritical,
/// <summary>
/// StartingCritical. Critical states.
/// </summary>
StartingCritical,
/// <summary>
/// ResetCritical. Critical states.
/// </summary>
ResetCritical,
/// <summary>
/// SavingCritical. Critical states.
/// </summary>
SavingCritical,
/// <summary>
/// PausingCritical. Critical states.
/// </summary>
PausingCritical,
/// <summary>
/// ResumingCritical. Critical states.
/// </summary>
ResumingCritical,
/// <summary>
/// FastSavedCritical. Critical states.
/// </summary>
FastSavedCritical,
/// <summary>
/// FastSavingCritical. Critical states.
/// </summary>
FastSavingCritical,
}
#nullable enable
/// <summary>
/// Get the State property from Get-VM result.
/// </summary>
/// <param name="value">The raw PSObject as returned by Get-VM.</param>
/// <returns>The VMState value of the State property if present and parsable, otherwise null.</returns>
internal VMState? GetVMStateProperty(PSObject value)
{
object? rawState = value.Properties["State"].Value;
if (rawState is Enum enumState)
{
// If the Hyper-V module was directly importable we have the VMState enum
// value which we can just cast to our VMState type.
return (VMState)enumState;
}
else if (rawState is string stringState && Enum.TryParse(stringState, true, out VMState result))
{
// If the Hyper-V module was imported through implicit remoting on old
// Windows versions we get a string back which we will try and parse
// as the enum label.
return result;
}
// Unknown scenario, this should not happen.
string message = PSRemotingErrorInvariants.FormatResourceString(
RemotingErrorIdStrings.HyperVFailedToGetStateUnknownType,
rawState?.GetType()?.FullName ?? "null");
throw new InvalidOperationException(message);
}
#nullable disable
#endregion
#region Tracer
// PSETWTracer tracer = PSETWTracer.GetETWTracer(PSKeyword.Runspace);
#endregion Tracer
#region Properties
/// <summary>
/// The PSSession object describing the remote runspace
/// using which the specified cmdlet operation will be performed.
/// </summary>
[Parameter(Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.SessionParameterSet)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public virtual PSSession[] Session { get; set; }
/// <summary>
/// This parameter represents the address(es) of the remote
/// computer(s). The following formats are supported:
/// (a) Computer name
/// (b) IPv4 address : 132.3.4.5
/// (c) IPv6 address: 3ffe:8311:ffff:f70f:0:5efe:172.30.162.18.
/// </summary>
[Parameter(Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.ComputerNameParameterSet)]
[Alias("Cn")]
public virtual string[] ComputerName { get; set; }
/// <summary>
/// Computer names after they have been resolved
/// (null, empty string, "." resolves to localhost)
/// </summary>
/// <remarks>If Null or empty string is specified, then localhost is assumed.
/// The ResolveComputerNames will include this.
/// </remarks>
protected string[] ResolvedComputerNames { get; set; }
/// <summary>
/// Guid of target virtual machine.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Justification = "This is by spec.")]
[Parameter(Position = 0,
Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.VMIdParameterSet)]
[ValidateNotNullOrEmpty]
[Alias("VMGuid")]
public virtual Guid[] VMId { get; set; }
/// <summary>
/// Name of target virtual machine.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Justification = "This is by spec.")]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.VMNameParameterSet)]
[ValidateNotNullOrEmpty]
public virtual string[] VMName { get; set; }
/// <summary>
/// Specifies the credentials of the user to impersonate in the
/// remote machine. If this parameter is not specified then the
/// credentials of the current user process will be assumed.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.ComputerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.UriParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.VMIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.VMNameParameterSet)]
[Credential()]
public virtual PSCredential Credential
{
get
{
return _pscredential;
}
set
{
_pscredential = value;
ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication);
}
}
private PSCredential _pscredential;
/// <summary>
/// ID of target container.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Justification = "This is by spec.")]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.ContainerIdParameterSet)]
[ValidateNotNullOrEmpty]
public virtual string[] ContainerId { get; set; }
/// <summary>
/// When set, PowerShell process inside container will be launched with
/// high privileged account.
/// Otherwise (default case), PowerShell process inside container will be launched
/// with low privileged account.
/// </summary>
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.ContainerIdParameterSet)]
public virtual SwitchParameter RunAsAdministrator { get; set; }
/// <summary>
/// Port specifies the alternate port to be used in case the
/// default ports are not used for the transport mechanism
/// (port 80 for http and port 443 for useSSL)
/// </summary>
/// <remarks>
/// Currently this is being accepted as a parameter. But in future
/// support will be added to make this a part of a policy setting.
/// When a policy setting is in place this parameter can be used
/// to override the policy setting
/// </remarks>
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.ComputerNameParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.SSHHostParameterSet)]
[ValidateRange((int)1, (int)UInt16.MaxValue)]
public virtual int Port { get; set; }
/// <summary>
/// This parameter suggests that the transport scheme to be used for
/// remote connections is useSSL instead of the default http.Since
/// there are only two possible transport schemes that are possible
/// at this point, a SwitchParameter is being used to switch between
/// the two.
/// </summary>
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.ComputerNameParameterSet)]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")]
public virtual SwitchParameter UseSSL { get; set; }
/// <summary>
/// This parameters specifies the appname which identifies the connection
/// end point on the remote machine. If this parameter is not specified
/// then the value specified in DEFAULTREMOTEAPPNAME will be used. If that's
/// not specified as well, then "WSMAN" will be used.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.ComputerNameParameterSet)]
public virtual string ApplicationName
{
get
{
return _appName;
}
set
{
_appName = ResolveAppName(value);
}
}
private string _appName;
/// <summary>
/// Allows the user of the cmdlet to specify a throttling value
/// for throttling the number of remote operations that can
/// be executed simultaneously.
/// </summary>
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.ComputerNameParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.SessionParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.UriParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.ContainerIdParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.VMIdParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.VMNameParameterSet)]
public virtual int ThrottleLimit { get; set; } = 0;
/// <summary>
/// A complete URI(s) specified for the remote computer and shell to
/// connect to and create runspace for.
/// </summary>
[Parameter(Position = 0, Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.UriParameterSet)]
[ValidateNotNullOrEmpty]
[Alias("URI", "CU")]
public virtual Uri[] ConnectionUri { get; set; }
/// <summary>
/// The AllowRedirection parameter enables the implicit redirection functionality.
/// </summary>
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.UriParameterSet)]
public virtual SwitchParameter AllowRedirection
{
get { return _allowRedirection; }
set { _allowRedirection = value; }
}
private bool _allowRedirection = false;
/// <summary>
/// Extended Session Options for controlling the session creation. Use
/// "New-WSManSessionOption" cmdlet to supply value for this parameter.
/// </summary>
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.ComputerNameParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.UriParameterSet)]
[ValidateNotNull]
public virtual PSSessionOption SessionOption
{
get
{
if (_sessionOption == null)
{
object tmp = this.SessionState.PSVariable.GetValue(DEFAULT_SESSION_OPTION);
if (tmp == null || !LanguagePrimitives.TryConvertTo<PSSessionOption>(tmp, out _sessionOption))
{
_sessionOption = new PSSessionOption();
}
}
return _sessionOption;
}
set
{
_sessionOption = value;
}
}
private PSSessionOption _sessionOption;
internal const string DEFAULT_SESSION_OPTION = "PSSessionOption";
// Quota related variables.
/// <summary>
/// Use basic authentication to authenticate the user.
/// </summary>
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.ComputerNameParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.UriParameterSet)]
public virtual AuthenticationMechanism Authentication
{
get
{
return _authMechanism;
}
set
{
_authMechanism = value;
// Validate if a user can specify this authentication.
ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication);
}
}
private AuthenticationMechanism _authMechanism = AuthenticationMechanism.Default;
/// <summary>
/// Specifies the certificate thumbprint to be used to impersonate the user on the
/// remote machine.
/// </summary>
[Parameter(ParameterSetName = NewPSSessionCommand.ComputerNameParameterSet)]
[Parameter(ParameterSetName = NewPSSessionCommand.UriParameterSet)]
public virtual string CertificateThumbprint
{
get
{
return _thumbPrint;
}
set
{
_thumbPrint = value;
ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication);
}
}
private string _thumbPrint = null;
#region SSHHostParameters
/// <summary>
/// Host name for an SSH remote connection.
/// </summary>
[Parameter(Position = 0, Mandatory = true,
ParameterSetName = PSRemotingBaseCmdlet.SSHHostParameterSet)]
[ValidateNotNullOrEmpty()]
public virtual string[] HostName
{
get;
set;
}
/// <summary>
/// SSH User Name.
/// </summary>
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.SSHHostParameterSet)]
[ValidateNotNullOrEmpty()]
public virtual string UserName
{
get;
set;
}
/// <summary>
/// SSH Key File Path.
/// </summary>
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.SSHHostParameterSet)]
[ValidateNotNullOrEmpty()]
[Alias("IdentityFilePath")]
public virtual string KeyFilePath
{
get;
set;
}
/// <summary>
/// Gets or sets a value for the SSH subsystem to use for the remote connection.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.SSHHostParameterSet)]
public virtual string Subsystem { get; set; }
/// <summary>
/// Gets or sets a value in milliseconds that limits the time allowed for an SSH connection to be established.
/// Default timeout value is infinite.
/// </summary>
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.SSHHostParameterSet)]
public virtual int ConnectingTimeout { get; set; } = Timeout.Infinite;
/// <summary>
/// This parameter specifies that SSH is used to establish the remote
/// connection and act as the remoting transport. By default WinRM is used
/// as the remoting transport. Using the SSH transport requires that SSH is
/// installed and PowerShell remoting is enabled on both client and remote machines.
/// </summary>
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.SSHHostParameterSet)]
[ValidateSet("true")]
public virtual SwitchParameter SSHTransport
{
get;
set;
}
/// <summary>
/// Hashtable array containing SSH connection parameters for each remote target
/// ComputerName (Alias: HostName) (required)
/// UserName (optional)
/// KeyFilePath (Alias: IdentityFilePath) (optional)
/// </summary>
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.SSHHostHashParameterSet, Mandatory = true)]
[ValidateNotNullOrEmpty()]
public virtual Hashtable[] SSHConnection
{
get;
set;
}
/// <summary>
/// Gets or sets the Hashtable containing options to be passed to OpenSSH.
/// </summary>
[Parameter(ParameterSetName = InvokeCommandCommand.SSHHostParameterSet)]
[ValidateNotNullOrEmpty]
public virtual Hashtable Options { get; set; }
#endregion
#endregion Properties
#region Internal Static Methods
/// <summary>
/// Used to resolve authentication from the parameters chosen by the user.
/// User has the following options:
/// 1. AuthMechanism + Credential
/// 2. CertificateThumbPrint
///
/// All the above are mutually exclusive.
/// </summary>
/// <exception cref="InvalidOperationException">
/// If there is ambiguity as specified above.
/// </exception>
internal static void ValidateSpecifiedAuthentication(PSCredential credential, string thumbprint, AuthenticationMechanism authentication)
{
if ((credential != null) && (thumbprint != null))
{
string message = PSRemotingErrorInvariants.FormatResourceString(
RemotingErrorIdStrings.NewRunspaceAmbiguousAuthentication,
"CertificateThumbPrint", "Credential");
throw new InvalidOperationException(message);
}
if ((authentication != AuthenticationMechanism.Default) && (thumbprint != null))
{
string message = PSRemotingErrorInvariants.FormatResourceString(
RemotingErrorIdStrings.NewRunspaceAmbiguousAuthentication,
"CertificateThumbPrint", authentication.ToString());
throw new InvalidOperationException(message);
}
if ((authentication == AuthenticationMechanism.NegotiateWithImplicitCredential) &&
(credential != null))
{
string message = PSRemotingErrorInvariants.FormatResourceString(
RemotingErrorIdStrings.NewRunspaceAmbiguousAuthentication,
"Credential", authentication.ToString());
throw new InvalidOperationException(message);
}
}
#endregion
#region Internal Methods
#region SSH Connection Strings
private const string ComputerNameParameter = "ComputerName";
private const string HostNameAlias = "HostName";
private const string UserNameParameter = "UserName";
private const string KeyFilePathParameter = "KeyFilePath";
private const string IdentityFilePathAlias = "IdentityFilePath";
private const string PortParameter = "Port";
private const string SubsystemParameter = "Subsystem";
private const string ConnectingTimeoutParameter = "ConnectingTimeout";
private const string OptionsParameter = "Options";
#endregion
/// <summary>
/// Parse a hostname used with SSH Transport to get embedded
/// username and/or port.
/// </summary>
/// <param name="hostname">Host name to parse.</param>
/// <param name="host">Resolved target host.</param>
/// <param name="userName">Resolved target user name.</param>
/// <param name="port">Resolved target port.</param>
protected void ParseSshHostName(string hostname, out string host, out string userName, out int port)
{
host = hostname;
userName = this.UserName;
port = this.Port;
try
{
Uri uri = new System.Uri("ssh://" + hostname);
host = ResolveComputerName(uri.Host);
ValidateComputerName(new string[] { host });
if (uri.UserInfo != string.Empty)
{
userName = uri.UserInfo;
}
if (uri.Port != -1)
{
port = uri.Port;
}
}
catch (UriFormatException)
{
ThrowTerminatingError(new ErrorRecord(
new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(
RemotingErrorIdStrings.InvalidComputerName)), "PSSessionInvalidComputerName",
ErrorCategory.InvalidArgument, hostname));
}
}
/// <summary>
/// Parse the Connection parameter HashTable array.
/// </summary>
/// <returns>Array of SSHConnection objects.</returns>
internal SSHConnection[] ParseSSHConnectionHashTable()
{
List<SSHConnection> connections = new();
foreach (var item in this.SSHConnection)
{
if (item.ContainsKey(ComputerNameParameter) && item.ContainsKey(HostNameAlias))
{
throw new PSArgumentException(RemotingErrorIdStrings.SSHConnectionDuplicateHostName);
}
if (item.ContainsKey(KeyFilePathParameter) && item.ContainsKey(IdentityFilePathAlias))
{
throw new PSArgumentException(RemotingErrorIdStrings.SSHConnectionDuplicateKeyPath);
}
SSHConnection connectionInfo = new();
foreach (var key in item.Keys)
{
string paramName = key as string;
if (string.IsNullOrEmpty(paramName))
{
throw new PSArgumentException(RemotingErrorIdStrings.InvalidSSHConnectionParameter);
}
if (paramName.Equals(ComputerNameParameter, StringComparison.OrdinalIgnoreCase) || paramName.Equals(HostNameAlias, StringComparison.OrdinalIgnoreCase))
{
var resolvedComputerName = ResolveComputerName(GetSSHConnectionStringParameter(item[paramName]));
ParseSshHostName(resolvedComputerName, out string host, out string userName, out int port);
connectionInfo.ComputerName = host;
if (userName != string.Empty)
{
connectionInfo.UserName = userName;
}
if (port != -1)
{
connectionInfo.Port = port;
}
}
else if (paramName.Equals(UserNameParameter, StringComparison.OrdinalIgnoreCase))
{
connectionInfo.UserName = GetSSHConnectionStringParameter(item[paramName]);
}
else if (paramName.Equals(KeyFilePathParameter, StringComparison.OrdinalIgnoreCase) || paramName.Equals(IdentityFilePathAlias, StringComparison.OrdinalIgnoreCase))
{
connectionInfo.KeyFilePath = GetSSHConnectionStringParameter(item[paramName]);
}
else if (paramName.Equals(PortParameter, StringComparison.OrdinalIgnoreCase))
{
connectionInfo.Port = GetSSHConnectionIntParameter(item[paramName]);
}
else if (paramName.Equals(SubsystemParameter, StringComparison.OrdinalIgnoreCase))
{
connectionInfo.Subsystem = GetSSHConnectionStringParameter(item[paramName]);
}
else if (paramName.Equals(ConnectingTimeoutParameter, StringComparison.OrdinalIgnoreCase))
{
connectionInfo.ConnectingTimeout = GetSSHConnectionIntParameter(item[paramName]);
}
else if (paramName.Equals(OptionsParameter, StringComparison.OrdinalIgnoreCase))
{
connectionInfo.Options = item[paramName] as Hashtable;
}
else
{
throw new PSArgumentException(
StringUtil.Format(RemotingErrorIdStrings.UnknownSSHConnectionParameter, paramName));
}
}
if (string.IsNullOrEmpty(connectionInfo.ComputerName))
{
throw new PSArgumentException(RemotingErrorIdStrings.MissingRequiredSSHParameter);
}
connections.Add(connectionInfo);
}
return connections.ToArray();
}
#endregion
#region Private Methods
/// <summary>
/// Validate the PSSession objects specified and write
/// appropriate error records.
/// </summary>
/// <remarks>This function will lead in terminating errors when any of
/// the validations fail</remarks>
protected void ValidateRemoteRunspacesSpecified()
{
Dbg.Assert(Session != null && Session.Length != 0,
"Remote Runspaces specified must not be null or empty");
// Check if there are duplicates in the specified PSSession objects
if (RemotingCommandUtil.HasRepeatingRunspaces(Session))
{
ThrowTerminatingError(new ErrorRecord(new ArgumentException(
GetMessage(RemotingErrorIdStrings.RemoteRunspaceInfoHasDuplicates)),
nameof(PSRemotingErrorId.RemoteRunspaceInfoHasDuplicates),
ErrorCategory.InvalidArgument, Session));
}
// BUGBUG: The following is a bogus check
// Check if the number of PSSession objects specified is greater
// than the maximum allowable range
if (RemotingCommandUtil.ExceedMaximumAllowableRunspaces(Session))
{
ThrowTerminatingError(new ErrorRecord(new ArgumentException(
GetMessage(RemotingErrorIdStrings.RemoteRunspaceInfoLimitExceeded)),
nameof(PSRemotingErrorId.RemoteRunspaceInfoLimitExceeded),
ErrorCategory.InvalidArgument, Session));
}
}
/// <summary>
/// Updates connection info with the data read from cmdlet's parameters and
/// sessions variables.
/// The following data is updated:
/// 1. MaxURIRedirectionCount
/// 2. MaxRecvdDataSizePerSession
/// 3. MaxRecvdDataSizePerCommand
/// 4. MaxRecvdObjectSize.
/// </summary>
/// <param name="connectionInfo"></param>
internal void UpdateConnectionInfo(WSManConnectionInfo connectionInfo)
{
Dbg.Assert(connectionInfo != null, "connectionInfo cannot be null.");
connectionInfo.SetSessionOptions(this.SessionOption);
if (!ParameterSetName.Equals(PSRemotingBaseCmdlet.UriParameterSet, StringComparison.OrdinalIgnoreCase))
{
// uri redirection is supported only with URI parameter set
connectionInfo.MaximumConnectionRedirectionCount = 0;
}
if (!_allowRedirection)
{
// uri redirection required explicit user consent
connectionInfo.MaximumConnectionRedirectionCount = 0;
}
}
/// <summary>
/// Uri parameter set.
/// </summary>
protected const string UriParameterSet = "Uri";
/// <summary>
/// Validates computer names to check if none of them
/// happen to be a Uri. If so this throws an error.
/// </summary>
/// <param name="computerNames">collection of computer
/// names to validate</param>
protected void ValidateComputerName(string[] computerNames)
{
foreach (string computerName in computerNames)
{
UriHostNameType nametype = Uri.CheckHostName(computerName);
if (!(nametype == UriHostNameType.Dns || nametype == UriHostNameType.IPv4 ||
nametype == UriHostNameType.IPv6))
{
ThrowTerminatingError(new ErrorRecord(
new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(
RemotingErrorIdStrings.InvalidComputerName)), "PSSessionInvalidComputerName",
ErrorCategory.InvalidArgument, computerNames));
}
}
}
/// <summary>
/// Validates parameter value and returns as string.
/// </summary>
/// <param name="param">Parameter value to be validated.</param>
/// <returns>Parameter value as string.</returns>
private static string GetSSHConnectionStringParameter(object param)
{
string paramValue;
try
{
paramValue = LanguagePrimitives.ConvertTo<string>(param);
}
catch (PSInvalidCastException e)
{
throw new PSArgumentException(e.Message, e);
}
if (!string.IsNullOrEmpty(paramValue))
{
return paramValue;
}
throw new PSArgumentException(RemotingErrorIdStrings.InvalidSSHConnectionParameter);
}
/// <summary>
/// Validates parameter value and returns as integer.
/// </summary>
/// <param name="param">Parameter value to be validated.</param>
/// <returns>Parameter value as integer.</returns>
private static int GetSSHConnectionIntParameter(object param)
{
if (param == null)
{
throw new PSArgumentException(RemotingErrorIdStrings.InvalidSSHConnectionParameter);
}
try
{
return LanguagePrimitives.ConvertTo<int>(param);
}
catch (PSInvalidCastException e)
{
throw new PSArgumentException(e.Message, e);
}
}
#endregion Private Methods
#region Overrides
/// <summary>
/// Resolves shellname and appname.
/// </summary>
protected override void BeginProcessing()
{
base.BeginProcessing();
// Validate KeyFilePath parameter.
if ((ParameterSetName == PSRemotingBaseCmdlet.SSHHostParameterSet) &&
(this.KeyFilePath != null))
{
// Resolve the key file path when set.
this.KeyFilePath = PathResolver.ResolveProviderAndPath(this.KeyFilePath, true, this, false, RemotingErrorIdStrings.FilePathNotFromFileSystemProvider);
}
// Validate IdleTimeout parameter.
int idleTimeout = (int)SessionOption.IdleTimeout.TotalMilliseconds;
if (idleTimeout != BaseTransportManager.UseServerDefaultIdleTimeout &&
idleTimeout < BaseTransportManager.MinimumIdleTimeout)
{
throw new PSArgumentException(
StringUtil.Format(RemotingErrorIdStrings.InvalidIdleTimeoutOption,
idleTimeout / 1000, BaseTransportManager.MinimumIdleTimeout / 1000));
}
if (string.IsNullOrEmpty(_appName))
{
_appName = ResolveAppName(null);
}
}
#endregion Overrides
}
/// <summary>
/// Base class for any cmdlet which has to execute a pipeline. The
/// following cmdlets currently fall under this category:
/// 1. Invoke-Expression
/// 2. Start-PSJob.
/// </summary>
public abstract class PSExecutionCmdlet : PSRemotingBaseCmdlet
{
#region Strings
/// <summary>
/// VM guid file path parameter set.
/// </summary>
protected const string FilePathVMIdParameterSet = "FilePathVMId";
/// <summary>
/// VM name file path parameter set.
/// </summary>
protected const string FilePathVMNameParameterSet = "FilePathVMName";
/// <summary>
/// Container ID file path parameter set.
/// </summary>
protected const string FilePathContainerIdParameterSet = "FilePathContainerId";
/// <summary>
/// SSH Host file path parameter set.
/// </summary>
protected const string FilePathSSHHostParameterSet = "FilePathSSHHost";
/// <summary>
/// SSH Host file path parameter set with HashTable connection parameter.
/// </summary>
protected const string FilePathSSHHostHashParameterSet = "FilePathSSHHostHash";
#endregion
#region Parameters
/// <summary>
/// Input object which gets assigned to $input when executed
/// on the remote machine. This is the only parameter in
/// this cmdlet which will bind with a ValueFromPipeline=true.
/// </summary>
[Parameter(ValueFromPipeline = true)]
public virtual PSObject InputObject { get; set; } = AutomationNull.Value;
/// <summary>
/// Command to execute specified as a string. This can be a single
/// cmdlet, an expression or anything that can be internally
/// converted into a ScriptBlock.
/// </summary>
public virtual ScriptBlock ScriptBlock
{
get
{
return _scriptBlock;
}
set
{
_scriptBlock = value;
}
}
private ScriptBlock _scriptBlock;
/// <summary>
/// The file containing the script that the user has specified in the
/// cmdlet. This will be converted to a powershell before
/// its actually sent to the remote end.
/// </summary>
[Parameter(Position = 1,
Mandatory = true,
ParameterSetName = FilePathComputerNameParameterSet)]
[Parameter(Position = 1,
Mandatory = true,
ParameterSetName = FilePathSessionParameterSet)]
[Parameter(Position = 1,
Mandatory = true,
ParameterSetName = FilePathUriParameterSet)]
[ValidateNotNull]
public virtual string FilePath
{
get
{
return _filePath;
}
set
{
_filePath = value;
}
}
private string _filePath;
/// <summary>
/// True if FilePath should be processed as a literal path.
/// </summary>
protected bool IsLiteralPath { get; set; }
/// <summary>
/// Arguments that are passed to this scriptblock.
/// </summary>
[Parameter()]
[Alias("Args")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public virtual object[] ArgumentList
{
get
{
return _args;
}
set
{
_args = value;
}
}
private object[] _args;
/// <summary>
/// Indicates that if a job/command is invoked remotely the connection should be severed
/// right have invocation of job/command.
/// </summary>
protected bool InvokeAndDisconnect { get; set; } = false;
/// <summary>
/// Session names optionally provided for Disconnected parameter.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
protected string[] DisconnectedSessionName { get; set; }
/// <summary>
/// When set and in loopback scenario (localhost) this enables creation of WSMan
/// host process with the user interactive token, allowing PowerShell script network access,
/// i.e., allows going off box. When this property is true and a PSSession is disconnected,
/// reconnection is allowed only if reconnecting from a PowerShell session on the same box.
/// </summary>
public virtual SwitchParameter EnableNetworkAccess { get; set; }
/// <summary>
/// Guid of target virtual machine.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Justification = "This is by spec.")]
[Parameter(Position = 0, Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.VMIdParameterSet)]
[Parameter(Position = 0, Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.FilePathVMIdParameterSet)]
[ValidateNotNullOrEmpty]
[Alias("VMGuid")]
public override Guid[] VMId { get; set; }
/// <summary>
/// Name of target virtual machine.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Justification = "This is by spec.")]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.VMNameParameterSet)]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.FilePathVMNameParameterSet)]
[ValidateNotNullOrEmpty]
public override string[] VMName { get; set; }
/// <summary>
/// ID of target container.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Justification = "This is by spec.")]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.ContainerIdParameterSet)]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.FilePathContainerIdParameterSet)]
[ValidateNotNullOrEmpty]
public override string[] ContainerId { get; set; }
/// <summary>
/// For WSMan session:
/// If this parameter is not specified then the value specified in
/// the environment variable DEFAULTREMOTESHELLNAME will be used. If
/// this is not set as well, then Microsoft.PowerShell is used.
///
/// For VM/Container sessions:
/// If this parameter is not specified then no configuration is used.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.ComputerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.UriParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.FilePathComputerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.FilePathUriParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.ContainerIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.VMIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.VMNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.FilePathContainerIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.FilePathVMIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.FilePathVMNameParameterSet)]
public virtual string ConfigurationName { get; set; }
#endregion Parameters
#region Private Methods
/// <summary>
/// Creates helper objects with the command for the specified
/// remote computer names.
/// </summary>
protected virtual void CreateHelpersForSpecifiedComputerNames()
{
ValidateComputerName(ResolvedComputerNames);
// create helper objects for computer names
RemoteRunspace remoteRunspace = null;
string scheme = UseSSL.IsPresent ? WSManConnectionInfo.HttpsScheme : WSManConnectionInfo.HttpScheme;
for (int i = 0; i < ResolvedComputerNames.Length; i++)
{
try
{
WSManConnectionInfo connectionInfo = new WSManConnectionInfo();
connectionInfo.Scheme = scheme;
connectionInfo.ComputerName = ResolvedComputerNames[i];
connectionInfo.Port = Port;
connectionInfo.AppName = ApplicationName;
connectionInfo.ShellUri = ConfigurationName;
if (CertificateThumbprint != null)
{
connectionInfo.CertificateThumbprint = CertificateThumbprint;
}
else
{
connectionInfo.Credential = Credential;
}
connectionInfo.AuthenticationMechanism = Authentication;
UpdateConnectionInfo(connectionInfo);
connectionInfo.EnableNetworkAccess = EnableNetworkAccess;
// Use the provided session name or create one for this remote runspace so that
// it can be easily identified if it becomes disconnected and is queried on the server.
int rsId = PSSession.GenerateRunspaceId();
string rsName = (DisconnectedSessionName != null && DisconnectedSessionName.Length > i) ?
DisconnectedSessionName[i] : PSSession.GenerateRunspaceName(out rsId);
remoteRunspace = new RemoteRunspace(Utils.GetTypeTableFromExecutionContextTLS(), connectionInfo,
this.Host, this.SessionOption.ApplicationArguments, rsName, rsId);
remoteRunspace.Events.ReceivedEvents.PSEventReceived += OnRunspacePSEventReceived;
}
catch (UriFormatException uriException)
{
ErrorRecord errorRecord = new ErrorRecord(uriException, "CreateRemoteRunspaceFailed",
ErrorCategory.InvalidArgument, ResolvedComputerNames[i]);
WriteError(errorRecord);
continue;
}
Pipeline pipeline = CreatePipeline(remoteRunspace);
IThrottleOperation operation =
new ExecutionCmdletHelperComputerName(remoteRunspace, pipeline, InvokeAndDisconnect);
Operations.Add(operation);
}
}
/// <summary>
/// Creates helper objects for SSH remoting computer names
/// remoting.
/// </summary>
protected void CreateHelpersForSpecifiedSSHComputerNames()
{
foreach (string computerName in ResolvedComputerNames)
{
ParseSshHostName(computerName, out string host, out string userName, out int port);
var sshConnectionInfo = new SSHConnectionInfo(userName, host, KeyFilePath, port, Subsystem, ConnectingTimeout, Options);
var typeTable = TypeTable.LoadDefaultTypeFiles();
var remoteRunspace = RunspaceFactory.CreateRunspace(sshConnectionInfo, Host, typeTable) as RemoteRunspace;
var pipeline = CreatePipeline(remoteRunspace);
var operation = new ExecutionCmdletHelperComputerName(remoteRunspace, pipeline);
Operations.Add(operation);
}
}
/// <summary>
/// Creates helper objects for SSH remoting from HashTable parameters.
/// </summary>
protected void CreateHelpersForSpecifiedSSHHashComputerNames()
{
var sshConnections = ParseSSHConnectionHashTable();
foreach (var sshConnection in sshConnections)
{
var sshConnectionInfo = new SSHConnectionInfo(
sshConnection.UserName,
sshConnection.ComputerName,
sshConnection.KeyFilePath,
sshConnection.Port,
sshConnection.Subsystem,
sshConnection.ConnectingTimeout);
var typeTable = TypeTable.LoadDefaultTypeFiles();
var remoteRunspace = RunspaceFactory.CreateRunspace(sshConnectionInfo, this.Host, typeTable) as RemoteRunspace;
var pipeline = CreatePipeline(remoteRunspace);
var operation = new ExecutionCmdletHelperComputerName(remoteRunspace, pipeline);
Operations.Add(operation);
}
}
/// <summary>
/// Creates helper objects with the specified command for
/// the specified remote runspaceinfo objects.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspaces")]
protected void CreateHelpersForSpecifiedRunspaces()
{
RemoteRunspace[] remoteRunspaces;
Pipeline[] pipelines;
// extract RemoteRunspace out of the PSSession objects
int length = Session.Length;
remoteRunspaces = new RemoteRunspace[length];
for (int i = 0; i < length; i++)
{
remoteRunspaces[i] = (RemoteRunspace)Session[i].Runspace;
}
// create the set of pipelines from the RemoteRunspace objects and
// create IREHelperRunspace helper class to create operations
pipelines = new Pipeline[length];
for (int i = 0; i < length; i++)
{
pipelines[i] = CreatePipeline(remoteRunspaces[i]);
// create the operation object
IThrottleOperation operation = new ExecutionCmdletHelperRunspace(pipelines[i]);
Operations.Add(operation);
}
}
/// <summary>
/// Creates helper objects with the command for the specified
/// remote connection uris.
/// </summary>
protected void CreateHelpersForSpecifiedUris()
{
// create helper objects for computer names
RemoteRunspace remoteRunspace = null;
for (int i = 0; i < ConnectionUri.Length; i++)
{
try
{
WSManConnectionInfo connectionInfo = new WSManConnectionInfo();
connectionInfo.ConnectionUri = ConnectionUri[i];
connectionInfo.ShellUri = ConfigurationName;
if (CertificateThumbprint != null)
{
connectionInfo.CertificateThumbprint = CertificateThumbprint;
}
else
{
connectionInfo.Credential = Credential;
}
connectionInfo.AuthenticationMechanism = Authentication;
UpdateConnectionInfo(connectionInfo);
connectionInfo.EnableNetworkAccess = EnableNetworkAccess;
remoteRunspace = (RemoteRunspace)RunspaceFactory.CreateRunspace(connectionInfo, this.Host,
Utils.GetTypeTableFromExecutionContextTLS(),
this.SessionOption.ApplicationArguments);
Dbg.Assert(remoteRunspace != null,
"RemoteRunspace object created using URI is null");
remoteRunspace.Events.ReceivedEvents.PSEventReceived += OnRunspacePSEventReceived;
}
catch (UriFormatException e)
{
WriteErrorCreateRemoteRunspaceFailed(e, ConnectionUri[i]);
continue;
}
catch (InvalidOperationException e)
{
WriteErrorCreateRemoteRunspaceFailed(e, ConnectionUri[i]);
continue;
}
catch (ArgumentException e)
{
WriteErrorCreateRemoteRunspaceFailed(e, ConnectionUri[i]);
continue;
}
Pipeline pipeline = CreatePipeline(remoteRunspace);
IThrottleOperation operation =
new ExecutionCmdletHelperComputerName(remoteRunspace, pipeline, InvokeAndDisconnect);
Operations.Add(operation);
}
}
/// <summary>
/// Creates helper objects with the command for the specified
/// VM GUIDs or VM names.
/// </summary>
protected virtual void CreateHelpersForSpecifiedVMSession()
{
int inputArraySize;
int index;
string command;
bool[] vmIsRunning;
Collection<PSObject> results;
if ((ParameterSetName == PSExecutionCmdlet.VMIdParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.FilePathVMIdParameterSet))
{
inputArraySize = this.VMId.Length;
this.VMName = new string[inputArraySize];
vmIsRunning = new bool[inputArraySize];
for (index = 0; index < inputArraySize; index++)
{
vmIsRunning[index] = false;
command = "Get-VM -Id $args[0]";
try
{
results = this.InvokeCommand.InvokeScript(
command, false, PipelineResultTypes.None, null, this.VMId[index]);
}
catch (CommandNotFoundException)
{
ThrowTerminatingError(
new ErrorRecord(
new ArgumentException(RemotingErrorIdStrings.HyperVModuleNotAvailable),
nameof(PSRemotingErrorId.HyperVModuleNotAvailable),
ErrorCategory.NotInstalled,
null));
return;
}
if (results.Count != 1)
{
this.VMName[index] = string.Empty;
}
else
{
this.VMName[index] = (string)results[0].Properties["VMName"].Value;
if (GetVMStateProperty(results[0]) == VMState.Running)
{
vmIsRunning[index] = true;
}
}
}
}
else
{
Dbg.Assert((ParameterSetName == PSExecutionCmdlet.VMNameParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.FilePathVMNameParameterSet),
"Expected ParameterSetName == VMName or FilePathVMName");
inputArraySize = this.VMName.Length;
this.VMId = new Guid[inputArraySize];
vmIsRunning = new bool[inputArraySize];
for (index = 0; index < inputArraySize; index++)
{
vmIsRunning[index] = false;
command = "Get-VM -Name $args";
try
{
results = this.InvokeCommand.InvokeScript(
command, false, PipelineResultTypes.None, null, this.VMName[index]);
}
catch (CommandNotFoundException)
{
ThrowTerminatingError(
new ErrorRecord(
new ArgumentException(RemotingErrorIdStrings.HyperVModuleNotAvailable),
nameof(PSRemotingErrorId.HyperVModuleNotAvailable),
ErrorCategory.NotInstalled,
null));
return;
}
if (results.Count != 1)
{
this.VMId[index] = Guid.Empty;
}
else
{
this.VMId[index] = (Guid)results[0].Properties["VMId"].Value;
this.VMName[index] = (string)results[0].Properties["VMName"].Value;
if (GetVMStateProperty(results[0]) == VMState.Running)
{
vmIsRunning[index] = true;
}
}
}
}
ResolvedComputerNames = this.VMName;
for (index = 0; index < ResolvedComputerNames.Length; index++)
{
if ((this.VMId[index] == Guid.Empty) &&
((ParameterSetName == PSExecutionCmdlet.VMNameParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.FilePathVMNameParameterSet)))
{
WriteError(
new ErrorRecord(
new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMNameNotSingle,
this.VMName[index])),
nameof(PSRemotingErrorId.InvalidVMNameNotSingle),
ErrorCategory.InvalidArgument,
null));
continue;
}
else if ((this.VMName[index] == string.Empty) &&
((ParameterSetName == PSExecutionCmdlet.VMIdParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.FilePathVMIdParameterSet)))
{
WriteError(
new ErrorRecord(
new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMIdNotSingle,
this.VMId[index].ToString(null))),
nameof(PSRemotingErrorId.InvalidVMIdNotSingle),
ErrorCategory.InvalidArgument,
null));
continue;
}
else if (!vmIsRunning[index])
{
WriteError(
new ErrorRecord(
new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMState,
this.VMName[index])),
nameof(PSRemotingErrorId.InvalidVMState),
ErrorCategory.InvalidArgument,
null));
continue;
}
// create helper objects for VM GUIDs or names
RemoteRunspace remoteRunspace = null;
VMConnectionInfo connectionInfo;
try
{
connectionInfo = new VMConnectionInfo(this.Credential, this.VMId[index], this.VMName[index], this.ConfigurationName);
remoteRunspace = new RemoteRunspace(Utils.GetTypeTableFromExecutionContextTLS(),
connectionInfo, this.Host, null, null, -1);
remoteRunspace.Events.ReceivedEvents.PSEventReceived += OnRunspacePSEventReceived;
}
catch (InvalidOperationException e)
{
ErrorRecord errorRecord = new ErrorRecord(e,
"CreateRemoteRunspaceForVMFailed",
ErrorCategory.InvalidOperation,
null);
WriteError(errorRecord);
}
catch (ArgumentException e)
{
ErrorRecord errorRecord = new ErrorRecord(e,
"CreateRemoteRunspaceForVMFailed",
ErrorCategory.InvalidArgument,
null);
WriteError(errorRecord);
}
Pipeline pipeline = CreatePipeline(remoteRunspace);
IThrottleOperation operation =
new ExecutionCmdletHelperComputerName(remoteRunspace, pipeline, false);
Operations.Add(operation);
}
}
/// <summary>
/// Creates helper objects with the command for the specified
/// container IDs or names.
/// </summary>
protected virtual void CreateHelpersForSpecifiedContainerSession()
{
List<string> resolvedNameList = new List<string>();
Dbg.Assert((ParameterSetName == PSExecutionCmdlet.ContainerIdParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.FilePathContainerIdParameterSet),
"Expected ParameterSetName == ContainerId or FilePathContainerId");
foreach (var input in ContainerId)
{
//
// Create helper objects for container ID or name.
//
RemoteRunspace remoteRunspace = null;
ContainerConnectionInfo connectionInfo = null;
try
{
//
// Hyper-V container uses Hype-V socket as transport.
// Windows Server container uses named pipe as transport.
//
connectionInfo = ContainerConnectionInfo.CreateContainerConnectionInfo(input, RunAsAdministrator.IsPresent, this.ConfigurationName);
resolvedNameList.Add(connectionInfo.ComputerName);
connectionInfo.CreateContainerProcess();
remoteRunspace = new RemoteRunspace(Utils.GetTypeTableFromExecutionContextTLS(),
connectionInfo, this.Host, null, null, -1);
remoteRunspace.Events.ReceivedEvents.PSEventReceived += OnRunspacePSEventReceived;
}
catch (InvalidOperationException e)
{
ErrorRecord errorRecord = new ErrorRecord(e,
"CreateRemoteRunspaceForContainerFailed",
ErrorCategory.InvalidOperation,
null);
WriteError(errorRecord);
continue;
}
catch (ArgumentException e)
{
ErrorRecord errorRecord = new ErrorRecord(e,
"CreateRemoteRunspaceForContainerFailed",
ErrorCategory.InvalidArgument,
null);
WriteError(errorRecord);
continue;
}
catch (Exception e)
{
ErrorRecord errorRecord = new ErrorRecord(e,
"CreateRemoteRunspaceForContainerFailed",
ErrorCategory.InvalidOperation,
null);
WriteError(errorRecord);
continue;
}
Pipeline pipeline = CreatePipeline(remoteRunspace);
IThrottleOperation operation =
new ExecutionCmdletHelperComputerName(remoteRunspace, pipeline, false);
Operations.Add(operation);
}
ResolvedComputerNames = resolvedNameList.ToArray();
}
/// <summary>
/// Creates a pipeline from the powershell.
/// </summary>
/// <param name="remoteRunspace">Runspace on which to create the pipeline.</param>
/// <returns>A pipeline.</returns>
internal Pipeline CreatePipeline(RemoteRunspace remoteRunspace)
{
// The fix to WinBlue#475223 changed how UsingExpression is handled on the client/server sides, if the remote end is PSv5
// or later, we send the dictionary-form using values to the remote end. If the remote end is PSv3 or PSv4, then we send
// the array-form using values if all UsingExpressions are in the same scope, otherwise, we handle the UsingExpression as
// if the remote end is PSv2.
string serverPsVersion = GetRemoteServerPsVersion(remoteRunspace);
System.Management.Automation.PowerShell powershellToUse = GetPowerShellForPSv3OrLater(serverPsVersion);
Pipeline pipeline =
remoteRunspace.CreatePipeline(powershellToUse.Commands.Commands[0].CommandText, true);
pipeline.Commands.Clear();
foreach (Command command in powershellToUse.Commands.Commands)
{
pipeline.Commands.Add(command);
}
pipeline.RedirectShellErrorOutputPipe = true;
return pipeline;
}
/// <summary>
/// Check the powershell version of the remote server.
/// </summary>
private static string GetRemoteServerPsVersion(RemoteRunspace remoteRunspace)
{
if (remoteRunspace.ConnectionInfo is not WSManConnectionInfo)
{
// All transport types except for WSManConnectionInfo work with 5.1 or later.
return PSv5OrLater;
}
PSPrimitiveDictionary psApplicationPrivateData = remoteRunspace.GetApplicationPrivateData();
if (psApplicationPrivateData == null)
{
// The remote runspace is not opened yet, or it's disconnected before the private data is retrieved.
// In this case we cannot validate if the remote server is running PSv5 or later, so for safety purpose,
// we will handle the $using expressions as if the remote server is PSv3Orv4.
return PSv3Orv4;
}
PSPrimitiveDictionary.TryPathGet(
psApplicationPrivateData,
out Version serverPsVersion,
PSVersionInfo.PSVersionTableName,
PSVersionInfo.PSVersionName);
// PSv5 server will return 5.0 whereas older versions will always be 2.0. As we don't care about v2
// anymore we can use a simple ternary check here to differenciate v5 using behaviour vs v3/4.
return serverPsVersion != null && serverPsVersion.Major >= 5 ? PSv5OrLater : PSv3Orv4;
}
/// <summary>
/// Adds forwarded events to the local queue.
/// </summary>
internal void OnRunspacePSEventReceived(object sender, PSEventArgs e) => this.Events?.AddForwardedEvent(e);
#endregion Private Methods
#region Protected Members / Methods
/// <summary>
/// List of operations.
/// </summary>
internal List<IThrottleOperation> Operations { get; } = new List<IThrottleOperation>();
/// <summary>
/// Closes the input streams on all the pipelines.
/// </summary>
protected void CloseAllInputStreams()
{
foreach (IThrottleOperation operation in Operations)
{
ExecutionCmdletHelper helper = (ExecutionCmdletHelper)operation;
helper.Pipeline.Input.Close();
}
}
/// <summary>
/// Writes an error record specifying that creation of remote runspace
/// failed.
/// </summary>
/// <param name="e">exception which is causing this error record
/// to be written</param>
/// <param name="uri">Uri which caused this exception.</param>
private void WriteErrorCreateRemoteRunspaceFailed(Exception e, Uri uri)
{
Dbg.Assert(e is UriFormatException || e is InvalidOperationException ||
e is ArgumentException,
"Exception has to be of type UriFormatException or InvalidOperationException or ArgumentException");
ErrorRecord errorRecord = new ErrorRecord(e, "CreateRemoteRunspaceFailed",
ErrorCategory.InvalidArgument, uri);
WriteError(errorRecord);
}
/// <summary>
/// FilePathComputername parameter set.
/// </summary>
protected const string FilePathComputerNameParameterSet = "FilePathComputerName";
/// <summary>
/// LiteralFilePathComputername parameter set.
/// </summary>
protected const string LiteralFilePathComputerNameParameterSet = "LiteralFilePathComputerName";
/// <summary>
/// FilePathRunspace parameter set.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspace")]
protected const string FilePathSessionParameterSet = "FilePathRunspace";
/// <summary>
/// FilePathUri parameter set.
/// </summary>
protected const string FilePathUriParameterSet = "FilePathUri";
/// <summary>
/// PS version of the remote server.
/// </summary>
private const string PSv5OrLater = "PSv5OrLater";
private const string PSv3Orv4 = "PSv3Orv4";
private System.Management.Automation.PowerShell _powershellV2;
private System.Management.Automation.PowerShell _powershellV3;
/// <summary>
/// Reads content of file and converts it to a scriptblock.
/// </summary>
/// <param name="filePath"></param>
/// <param name="isLiteralPath"></param>
/// <returns></returns>
protected ScriptBlock GetScriptBlockFromFile(string filePath, bool isLiteralPath)
{
// Make sure filepath doesn't contain wildcards
if ((!isLiteralPath) && WildcardPattern.ContainsWildcardCharacters(filePath))
{
throw new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.WildCardErrorFilePathParameter), nameof(filePath));
}
if (!filePath.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.FilePathShouldPS1Extension), nameof(filePath));
}
// Resolve file path
string resolvedPath = PathResolver.ResolveProviderAndPath(filePath, isLiteralPath, this, false, RemotingErrorIdStrings.FilePathNotFromFileSystemProvider);
// read content of file
ExternalScriptInfo scriptInfo = new ExternalScriptInfo(filePath, resolvedPath, this.Context);
// Skip ShouldRun check for .psd1 files.
// Use ValidateScriptInfo() for explicitly validating the checkpolicy for psd1 file.
//
if (!filePath.EndsWith(".psd1", StringComparison.OrdinalIgnoreCase))
{
this.Context.AuthorizationManager.ShouldRunInternal(scriptInfo, CommandOrigin.Internal, this.Context.EngineHostInterface);
}
return scriptInfo.ScriptBlock;
}
#endregion Protected Members / Methods
#region Overrides
/// <summary>
/// Creates the helper classes for the specified
/// parameter set.
/// </summary>
protected override void BeginProcessing()
{
if ((ParameterSetName == PSExecutionCmdlet.VMIdParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.VMNameParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.ContainerIdParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.FilePathVMIdParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.FilePathVMNameParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.FilePathContainerIdParameterSet))
{
SkipWinRMCheck = true;
}
base.BeginProcessing();
if (_filePath != null)
{
_scriptBlock = GetScriptBlockFromFile(_filePath, IsLiteralPath);
}
switch (ParameterSetName)
{
case PSExecutionCmdlet.FilePathComputerNameParameterSet:
case PSExecutionCmdlet.LiteralFilePathComputerNameParameterSet:
case PSExecutionCmdlet.ComputerNameParameterSet:
{
string[] resolvedComputerNames = null;
ResolveComputerNames(ComputerName, out resolvedComputerNames);
ResolvedComputerNames = resolvedComputerNames;
CreateHelpersForSpecifiedComputerNames();
}
break;
case PSExecutionCmdlet.SSHHostParameterSet:
case PSExecutionCmdlet.FilePathSSHHostParameterSet:
{
string[] resolvedComputerNames = null;
ResolveComputerNames(HostName, out resolvedComputerNames);
ResolvedComputerNames = resolvedComputerNames;
CreateHelpersForSpecifiedSSHComputerNames();
}
break;
case PSExecutionCmdlet.SSHHostHashParameterSet:
case PSExecutionCmdlet.FilePathSSHHostHashParameterSet:
{
CreateHelpersForSpecifiedSSHHashComputerNames();
}
break;
case PSExecutionCmdlet.FilePathSessionParameterSet:
case PSExecutionCmdlet.SessionParameterSet:
{
ValidateRemoteRunspacesSpecified();
CreateHelpersForSpecifiedRunspaces();
}
break;
case PSExecutionCmdlet.FilePathUriParameterSet:
case PSExecutionCmdlet.UriParameterSet:
{
CreateHelpersForSpecifiedUris();
}
break;
case PSExecutionCmdlet.VMIdParameterSet:
case PSExecutionCmdlet.VMNameParameterSet:
case PSExecutionCmdlet.FilePathVMIdParameterSet:
case PSExecutionCmdlet.FilePathVMNameParameterSet:
{
CreateHelpersForSpecifiedVMSession();
}
break;
case PSExecutionCmdlet.ContainerIdParameterSet:
case PSExecutionCmdlet.FilePathContainerIdParameterSet:
{
CreateHelpersForSpecifiedContainerSession();
}
break;
}
}
#endregion Overrides
#region "Get PowerShell instance"
/// <summary>
/// Get the PowerShell instance for the PSv2 remote end
/// Generate the PowerShell instance by using the text of the scriptblock.
/// </summary>
/// <remarks>
/// PSv2 doesn't understand the '$using' prefix. To make UsingExpression work on PSv2 remote end, we will have to
/// alter the script, and send the altered script to the remote end. Since the script is altered, when there is an
/// error, the error message will show the altered script, and that could be confusing to the user. So if the remote
/// server is PSv3 or later version, we will use a different approach to handle UsingExpression so that we can keep
/// the script unchanged.
///
/// However, on PSv3 and PSv4 remote server, it's not well supported if UsingExpressions are used in different scopes (fixed in PSv5).
/// If the remote end is PSv3 or PSv4, and there are UsingExpressions in different scopes, then we have to revert back to the approach
/// used for PSv2 remote server.
/// </remarks>
/// <returns></returns>
private System.Management.Automation.PowerShell GetPowerShellForPSv2()
{
if (_powershellV2 != null) { return _powershellV2; }
// Try to convert the scriptblock to powershell commands.
_powershellV2 = ConvertToPowerShell();
if (_powershellV2 != null)
{
// Look for EndOfStatement tokens.
foreach (var command in _powershellV2.Commands.Commands)
{
if (command.IsEndOfStatement)
{
// PSv2 cannot process this. Revert to sending script.
_powershellV2 = null;
break;
}
}
if (_powershellV2 != null) { return _powershellV2; }
}
List<string> newParameterNames;
List<object> newParameterValues;
string scriptTextAdaptedForPSv2 = GetConvertedScript(out newParameterNames, out newParameterValues);
_powershellV2 = System.Management.Automation.PowerShell.Create().AddScript(scriptTextAdaptedForPSv2);
if (_args != null)
{
foreach (object arg in _args)
{
_powershellV2.AddArgument(arg);
}
}
if (newParameterNames != null)
{
Dbg.Assert(newParameterValues != null && newParameterNames.Count == newParameterValues.Count, "We should get the value for each using variable");
for (int i = 0; i < newParameterNames.Count; i++)
{
_powershellV2.AddParameter(newParameterNames[i], newParameterValues[i]);
}
}
return _powershellV2;
}
/// <summary>
/// Get the PowerShell instance for the PSv3 (or later) remote end
/// Generate the PowerShell instance by using the text of the scriptblock.
/// </summary>
/// <remarks>
/// In PSv3 and PSv4, if the remote server is PSv3 or later, we generate an object array that contains the value of each using expression in
/// the parsing order, and then pass the array to the remote end as a special argument. On the remote end, the using expressions will be indexed
/// in the same parsing order during the variable analysis process, and the index is used to get the value of the corresponding using expression
/// from the special array. There is a limitation in that approach -- $using cannot be used in different scopes with Invoke-Command/Start-Job
/// (see WinBlue#475223), because the variable analysis process can only index using expressions within the same scope (this is by design), and a
/// using expression from a different scope may be assigned with an index that conflicts with other using expressions.
///
/// To fix the limitation described above, we changed to pass a dictionary with key/value pairs for the using expressions on the client side. The key
/// is an unique base64 encoded string generated based on the text of the using expression. On the remote end, it can always get the unique key of a
/// using expression because the text passed to the server side is the same, and thus the value of the using expression can be retrieved from the special
/// dictionary. With this approach, $using in different scopes can be supported for Invoke-Command/Start-Job.
///
/// This fix involved changes on the server side, so the fix will work only if the remote end is PSv5 or later. In order to avoid possible breaking
/// change in 'PSv5 client - PSv3 server' and 'PSv5 client - PSv4 server' scenarios, we should keep sending the array-form using values if the remote
/// end is PSv3 or PSv4 as long as no UsingExpression is in a different scope. If the remote end is PSv3 or PSv4 and we do have UsingExpressions
/// in different scopes, then we will revert back to the approach we use to handle UsingExpression for PSv2 remote server.
/// </remarks>
/// <returns></returns>
private System.Management.Automation.PowerShell GetPowerShellForPSv3OrLater(string serverPsVersion)
{
if (_powershellV3 != null) { return _powershellV3; }
// Try to convert the scriptblock to powershell commands.
_powershellV3 = ConvertToPowerShell();
if (_powershellV3 != null) { return _powershellV3; }
// Using expressions can be a variable, as well as property and / or array references. E.g.
//
// icm { echo $using:a }
// icm { echo $using:a[3] }
// icm { echo $using:a.Length }
//
// Semantic checks on the using statement have already validated that there are no arbitrary expressions,
// so we'll allow these expressions in everything but NoLanguage mode.
bool allowUsingExpressions = Context.SessionState.LanguageMode != PSLanguageMode.NoLanguage;
object[] usingValuesInArray = null;
IDictionary usingValuesInDict = null;
// Value of 'serverPsVersion' should be either 'PSv3Orv4' or 'PSv5OrLater'
if (serverPsVersion == PSv3Orv4)
{
usingValuesInArray = ScriptBlockToPowerShellConverter.GetUsingValuesAsArray(_scriptBlock, allowUsingExpressions, Context, null);
if (usingValuesInArray == null)
{
// 'usingValuesInArray' will be null only if there are UsingExpressions used in different scopes.
// PSv3 and PSv4 remote server cannot handle this, so we revert back to the approach we use for PSv2 remote end.
return GetPowerShellForPSv2();
}
}
else
{
// Remote server is PSv5 or later version
usingValuesInDict = ScriptBlockToPowerShellConverter.GetUsingValuesAsDictionary(_scriptBlock, allowUsingExpressions, Context, null);
}
string textOfScriptBlock = this.MyInvocation.ExpectingInput
? _scriptBlock.GetWithInputHandlingForInvokeCommand()
: _scriptBlock.ToString();
_powershellV3 = System.Management.Automation.PowerShell.Create().AddScript(textOfScriptBlock);
if (_args != null)
{
foreach (object arg in _args)
{
_powershellV3.AddArgument(arg);
}
}
if (usingValuesInDict != null && usingValuesInDict.Count > 0)
{
_powershellV3.AddParameter(Parser.VERBATIM_ARGUMENT, usingValuesInDict);
}
else if (usingValuesInArray != null && usingValuesInArray.Length > 0)
{
_powershellV3.AddParameter(Parser.VERBATIM_ARGUMENT, usingValuesInArray);
}
return _powershellV3;
}
private System.Management.Automation.PowerShell ConvertToPowerShell()
{
System.Management.Automation.PowerShell powershell = null;
try
{
// This is trusted input as long as we're in FullLanguage mode
bool isTrustedInput = Context.LanguageMode == PSLanguageMode.FullLanguage;
powershell = _scriptBlock.GetPowerShell(isTrustedInput, _args);
}
catch (ScriptBlockToPowerShellNotSupportedException)
{
// conversion failed, we need to send the script to the remote end.
// since the PowerShell instance would be different according to the PSVersion of the remote end,
// we generate it when we know which version we are talking to.
}
return powershell;
}
#endregion "Get PowerShell instance"
#region "UsingExpression Utilities"
/// <summary>
/// Get the converted script for a remote PSv2 end.
/// </summary>
/// <param name="newParameterNames">
/// The new parameter names that we added to the param block
/// </param>
/// <param name="newParameterValues">
/// The new parameter values that need to be added to the powershell instance
/// </param>
/// <returns></returns>
private string GetConvertedScript(out List<string> newParameterNames, out List<object> newParameterValues)
{
newParameterNames = null; newParameterValues = null;
string textOfScriptBlock = null;
// Scan for the using variables
List<VariableExpressionAst> usingVariables = GetUsingVariables(_scriptBlock);
if (usingVariables == null || usingVariables.Count == 0)
{
// No using variable is used, then we don't change the script
textOfScriptBlock = this.MyInvocation.ExpectingInput
? _scriptBlock.GetWithInputHandlingForInvokeCommand()
: _scriptBlock.ToString();
}
else
{
newParameterNames = new List<string>();
var paramNamesWithDollarSign = new List<string>();
var paramUsingVars = new List<VariableExpressionAst>();
var nameHashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var varAst in usingVariables)
{
VariablePath varPath = varAst.VariablePath;
string varName = varPath.IsDriveQualified ? $"{varPath.DriveName}_{varPath.UnqualifiedPath}" : $"{varPath.UnqualifiedPath}";
string paramName = UsingExpressionAst.UsingPrefix + varName;
string paramNameWithDollar = "$" + paramName;
if (!nameHashSet.Contains(paramNameWithDollar))
{
newParameterNames.Add(paramName);
paramNamesWithDollarSign.Add(paramNameWithDollar);
paramUsingVars.Add(varAst);
nameHashSet.Add(paramNameWithDollar);
}
}
// Retrieve the value for each using variable
newParameterValues = GetUsingVariableValues(paramUsingVars);
// Generate the wrapped script
string additionalNewParams = string.Join(", ", paramNamesWithDollarSign);
textOfScriptBlock = this.MyInvocation.ExpectingInput
? _scriptBlock.GetWithInputHandlingForInvokeCommandWithUsingExpression(Tuple.Create(usingVariables, additionalNewParams))
: _scriptBlock.ToStringWithDollarUsingHandling(Tuple.Create(usingVariables, additionalNewParams));
}
return textOfScriptBlock;
}
/// <summary>
/// Get the values for the using variables that are passed in.
/// </summary>
/// <param name="paramUsingVars"></param>
/// <returns></returns>
private List<object> GetUsingVariableValues(List<VariableExpressionAst> paramUsingVars)
{
var values = new List<object>(paramUsingVars.Count);
VariableExpressionAst currentVarAst = null;
Version oldStrictVersion = Context.EngineSessionState.CurrentScope.StrictModeVersion;
try
{
Context.EngineSessionState.CurrentScope.StrictModeVersion = PSVersionInfo.PSVersion;
// GetExpressionValue ensures that it only does variable access when supplied a VariableExpressionAst.
// So, this is still safe to use in ConstrainedLanguage and will not result in arbitrary code
// execution.
bool allowVariableAccess = Context.SessionState.LanguageMode != PSLanguageMode.NoLanguage;
foreach (var varAst in paramUsingVars)
{
currentVarAst = varAst;
object value = Compiler.GetExpressionValue(varAst, allowVariableAccess, Context);
values.Add(value);
}
}
catch (RuntimeException rte)
{
if (rte.ErrorRecord.FullyQualifiedErrorId.Equals("VariableIsUndefined", StringComparison.Ordinal))
{
throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException),
currentVarAst.Extent, "UsingVariableIsUndefined", AutomationExceptions.UsingVariableIsUndefined, rte.ErrorRecord.TargetObject);
}
}
finally
{
Context.EngineSessionState.CurrentScope.StrictModeVersion = oldStrictVersion;
}
return values;
}
/// <summary>
/// Get all Using expressions that we care about.
/// </summary>
/// <param name="localScriptBlock"></param>
/// <returns>A list of UsingExpressionAsts ordered by the StartOffset.</returns>
private static List<VariableExpressionAst> GetUsingVariables(ScriptBlock localScriptBlock)
{
ArgumentNullException.ThrowIfNull(localScriptBlock, "Caller needs to make sure the parameter value is not null");
var allUsingExprs = UsingExpressionAstSearcher.FindAllUsingExpressions(localScriptBlock.Ast);
return allUsingExprs.Select(static usingExpr => UsingExpressionAst.ExtractUsingVariable((UsingExpressionAst)usingExpr)).ToList();
}
#endregion "UsingExpression Utilities"
}
/// <summary>
/// Base class for any cmdlet which operates on a runspace. The
/// following cmdlets currently fall under this category:
/// 1. Get-PSSession
/// 2. Remove-PSSession
/// 3. Disconnect-PSSession
/// 4. Connect-PSSession.
/// </summary>
public abstract class PSRunspaceCmdlet : PSRemotingCmdlet
{
#region Parameters
/// <summary>
/// ContainerIdInstanceId parameter set: container id + session instance id.
/// </summary>
protected const string ContainerIdInstanceIdParameterSet = "ContainerIdInstanceId";
/// <summary>
/// VMIdInstanceId parameter set: vm id + session instance id.
/// </summary>
protected const string VMIdInstanceIdParameterSet = "VMIdInstanceId";
/// <summary>
/// VMNameInstanceId parameter set: vm name + session instance id.
/// </summary>
protected const string VMNameInstanceIdParameterSet = "VMNameInstanceId";
/// <summary>
/// RemoteRunspaceId to retrieve corresponding PSSession
/// object.
/// </summary>
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRunspaceCmdlet.InstanceIdParameterSet)]
[ValidateNotNull]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public virtual Guid[] InstanceId
{
get
{
return _remoteRunspaceIds;
}
set
{
_remoteRunspaceIds = value;
}
}
private Guid[] _remoteRunspaceIds;
/// <summary>
/// Session Id of the remoterunspace info object.
/// </summary>
[Parameter(Position = 0,
ValueFromPipelineByPropertyName = true,
Mandatory = true,
ParameterSetName = PSRunspaceCmdlet.IdParameterSet)]
[ValidateNotNull]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public int[] Id { get; set; }
/// <summary>
/// Name of the remote runspaceinfo object.
/// </summary>
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRunspaceCmdlet.NameParameterSet)]
[ValidateNotNullOrEmpty()]
public virtual string[] Name
{
get
{
return _names;
}
set
{
_names = value;
}
}
private string[] _names;
/// <summary>
/// Name of the computer for which the runspace needs to be
/// returned.
/// </summary>
[Parameter(Position = 0,
Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRunspaceCmdlet.ComputerNameParameterSet)]
[ValidateNotNullOrEmpty]
[Alias("Cn")]
public virtual string[] ComputerName
{
get
{
return _computerNames;
}
set
{
_computerNames = value;
}
}
private string[] _computerNames;
/// <summary>
/// ID of target container.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Justification = "This is by spec.")]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRunspaceCmdlet.ContainerIdParameterSet)]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRunspaceCmdlet.ContainerIdInstanceIdParameterSet)]
[ValidateNotNullOrEmpty]
public virtual string[] ContainerId { get; set; }
/// <summary>
/// Guid of target virtual machine.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Justification = "This is by spec.")]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRunspaceCmdlet.VMIdParameterSet)]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRunspaceCmdlet.VMIdInstanceIdParameterSet)]
[ValidateNotNullOrEmpty]
[Alias("VMGuid")]
public virtual Guid[] VMId { get; set; }
/// <summary>
/// Name of target virtual machine.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Justification = "This is by spec.")]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRunspaceCmdlet.VMNameParameterSet)]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRunspaceCmdlet.VMNameInstanceIdParameterSet)]
[ValidateNotNullOrEmpty]
public virtual string[] VMName { get; set; }
#endregion Parameters
#region Private / Protected Methods
/// <summary>
/// Gets the matching runspaces based on the parameterset.
/// </summary>
/// <param name="writeErrorOnNoMatch">write an error record when
/// no matches are found</param>
/// <param name="writeobject">if true write the object down
/// the pipeline</param>
/// <returns>List of matching runspaces.</returns>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspaces")]
protected Dictionary<Guid, PSSession> GetMatchingRunspaces(bool writeobject,
bool writeErrorOnNoMatch)
{
return GetMatchingRunspaces(writeobject, writeErrorOnNoMatch, SessionFilterState.All, null);
}
/// <summary>
/// Gets the matching runspaces based on the parameterset.
/// </summary>
/// <param name="writeErrorOnNoMatch">write an error record when
/// no matches are found</param>
/// <param name="writeobject">if true write the object down
/// the pipeline</param>
/// <param name="filterState">Runspace state filter value.</param>
/// <param name="configurationName">Runspace configuration name filter value.</param>
/// <returns>List of matching runspaces.</returns>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspaces")]
protected Dictionary<Guid, PSSession> GetMatchingRunspaces(bool writeobject,
bool writeErrorOnNoMatch,
SessionFilterState filterState,
string configurationName)
{
switch (ParameterSetName)
{
case PSRunspaceCmdlet.ComputerNameParameterSet:
{
return GetMatchingRunspacesByComputerName(writeobject, writeErrorOnNoMatch);
}
case PSRunspaceCmdlet.InstanceIdParameterSet:
{
return GetMatchingRunspacesByRunspaceId(writeobject, writeErrorOnNoMatch);
}
case PSRunspaceCmdlet.NameParameterSet:
{
return GetMatchingRunspacesByName(writeobject, writeErrorOnNoMatch);
}
case PSRunspaceCmdlet.IdParameterSet:
{
return GetMatchingRunspacesBySessionId(writeobject, writeErrorOnNoMatch);
}
//
// writeErrorOnNoMatch should always be false for container/vm id/name inputs
// in Get-PSSession/Remove-PSSession cmdlets
//
// container id + optional session name
case PSRunspaceCmdlet.ContainerIdParameterSet:
{
return GetMatchingRunspacesByVMNameContainerId(writeobject, filterState, configurationName, true);
}
// container id + session instanceid
case PSRunspaceCmdlet.ContainerIdInstanceIdParameterSet:
{
return GetMatchingRunspacesByVMNameContainerIdSessionInstanceId(writeobject, filterState, configurationName, true);
}
// vm Guid + optional session name
case PSRunspaceCmdlet.VMIdParameterSet:
{
return GetMatchingRunspacesByVMId(writeobject, filterState, configurationName);
}
// vm Guid + session instanceid
case PSRunspaceCmdlet.VMIdInstanceIdParameterSet:
{
return GetMatchingRunspacesByVMIdSessionInstanceId(writeobject, filterState, configurationName);
}
// vm name + optional session name
case PSRunspaceCmdlet.VMNameParameterSet:
{
return GetMatchingRunspacesByVMNameContainerId(writeobject, filterState, configurationName, false);
}
// vm name + session instanceid
case PSRunspaceCmdlet.VMNameInstanceIdParameterSet:
{
return GetMatchingRunspacesByVMNameContainerIdSessionInstanceId(writeobject, filterState, configurationName, false);
}
}
return null;
}
internal Dictionary<Guid, PSSession> GetAllRunspaces(bool writeobject,
bool writeErrorOnNoMatch)
{
Dictionary<Guid, PSSession> matches = new Dictionary<Guid, PSSession>();
List<PSSession> remoteRunspaceInfos = this.RunspaceRepository.Runspaces;
foreach (PSSession remoteRunspaceInfo in remoteRunspaceInfos)
{
// return all remote runspace info objects
if (writeobject)
{
WriteObject(remoteRunspaceInfo);
}
else
{
matches.Add(remoteRunspaceInfo.InstanceId, remoteRunspaceInfo);
}
}
return matches;
}
/// <summary>
/// Gets the matching runspaces by computernames.
/// </summary>
/// <param name="writeErrorOnNoMatch">write an error record when
/// no matches are found</param>
/// <param name="writeobject">if true write the object down
/// the pipeline</param>
/// <returns>List of matching runspaces.</returns>
private Dictionary<Guid, PSSession> GetMatchingRunspacesByComputerName(bool writeobject,
bool writeErrorOnNoMatch)
{
if (_computerNames == null || _computerNames.Length == 0)
{
return GetAllRunspaces(writeobject, writeErrorOnNoMatch);
}
Dictionary<Guid, PSSession> matches = new Dictionary<Guid, PSSession>();
List<PSSession> remoteRunspaceInfos = this.RunspaceRepository.Runspaces;
// Loop through all computer-name patterns and runspaces to find matches.
foreach (string computerName in _computerNames)
{
WildcardPattern computerNamePattern = WildcardPattern.Get(computerName, WildcardOptions.IgnoreCase);
// Match the computer-name patterns against all the runspaces and remember the matches.
bool found = false;
foreach (PSSession remoteRunspaceInfo in remoteRunspaceInfos)
{
if (computerNamePattern.IsMatch(remoteRunspaceInfo.ComputerName))
{
found = true;
if (writeobject)
{
WriteObject(remoteRunspaceInfo);
}
else
{
try
{
matches.Add(remoteRunspaceInfo.InstanceId, remoteRunspaceInfo);
}
catch (ArgumentException)
{
// if match already found ignore
}
}
}
}
// If no match found write an error record.
if (!found && writeErrorOnNoMatch)
{
WriteInvalidArgumentError(PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedComputer, RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedComputer,
computerName);
}
}
return matches;
}
/// <summary>
/// Gets the matching runspaces based on name.
/// </summary>
/// <param name="writeErrorOnNoMatch">write an error record when
/// no matches are found</param>
/// <param name="writeobject">if true write the object down
/// the pipeline</param>
/// <returns>List of matching runspaces.</returns>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspaces")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "writeobject")]
protected Dictionary<Guid, PSSession> GetMatchingRunspacesByName(bool writeobject,
bool writeErrorOnNoMatch)
{
Dictionary<Guid, PSSession> matches = new Dictionary<Guid, PSSession>();
List<PSSession> remoteRunspaceInfos = this.RunspaceRepository.Runspaces;
// Loop through all computer-name patterns and runspaces to find matches.
foreach (string name in _names)
{
WildcardPattern namePattern = WildcardPattern.Get(name, WildcardOptions.IgnoreCase);
// Match the computer-name patterns against all the runspaces and remember the matches.
bool found = false;
foreach (PSSession remoteRunspaceInfo in remoteRunspaceInfos)
{
if (namePattern.IsMatch(remoteRunspaceInfo.Name))
{
found = true;
if (writeobject)
{
WriteObject(remoteRunspaceInfo);
}
else
{
try
{
matches.Add(remoteRunspaceInfo.InstanceId, remoteRunspaceInfo);
}
catch (ArgumentException)
{
// if match already found ignore
}
}
}
}
// If no match found write an error record.
if (!found && writeErrorOnNoMatch && !WildcardPattern.ContainsWildcardCharacters(name))
{
WriteInvalidArgumentError(PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedName, RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedName,
name);
}
}
return matches;
}
/// <summary>
/// Gets the matching runspaces based on the runspaces instance id.
/// </summary>
/// <param name="writeErrorOnNoMatch">write an error record when
/// no matches are found</param>
/// <param name="writeobject">if true write the object down
/// the pipeline</param>
/// <returns>List of matching runspaces.</returns>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspaces")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "writeobject")]
protected Dictionary<Guid, PSSession> GetMatchingRunspacesByRunspaceId(bool writeobject,
bool writeErrorOnNoMatch)
{
Dictionary<Guid, PSSession> matches = new Dictionary<Guid, PSSession>();
List<PSSession> remoteRunspaceInfos = this.RunspaceRepository.Runspaces;
// Loop through all computer-name patterns and runspaces to find matches.
foreach (Guid remoteRunspaceId in _remoteRunspaceIds)
{
// Match the computer-name patterns against all the runspaces and remember the matches.
bool found = false;
foreach (PSSession remoteRunspaceInfo in remoteRunspaceInfos)
{
if (remoteRunspaceId.Equals(remoteRunspaceInfo.InstanceId))
{
found = true;
if (writeobject)
{
WriteObject(remoteRunspaceInfo);
}
else
{
try
{
matches.Add(remoteRunspaceInfo.InstanceId, remoteRunspaceInfo);
}
catch (ArgumentException)
{
// if match already found ignore
}
}
}
}
// If no match found write an error record.
if (!found && writeErrorOnNoMatch)
{
WriteInvalidArgumentError(PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedRunspaceId, RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedRunspaceId,
remoteRunspaceId);
}
}
return matches;
}
/// <summary>
/// Gets the matching runspaces based on the session id (the
/// short integer id which is unique for a runspace)
/// </summary>
/// <param name="writeErrorOnNoMatch">write an error record when
/// no matches are found</param>
/// <param name="writeobject">if true write the object down
/// the pipeline</param>
/// <returns>List of matching runspaces.</returns>
private Dictionary<Guid, PSSession> GetMatchingRunspacesBySessionId(bool writeobject,
bool writeErrorOnNoMatch)
{
Dictionary<Guid, PSSession> matches = new Dictionary<Guid, PSSession>();
List<PSSession> remoteRunspaceInfos = this.RunspaceRepository.Runspaces;
// Loop through all computer-name patterns and runspaces to find matches.
foreach (int sessionId in Id)
{
// Match the computer-name patterns against all the runspaces and remember the matches.
bool found = false;
foreach (PSSession remoteRunspaceInfo in remoteRunspaceInfos)
{
if (sessionId == remoteRunspaceInfo.Id)
{
found = true;
if (writeobject)
{
WriteObject(remoteRunspaceInfo);
}
else
{
try
{
matches.Add(remoteRunspaceInfo.InstanceId, remoteRunspaceInfo);
}
catch (ArgumentException)
{
// if match already found ignore
}
}
}
}
// If no match found write an error record.
if (!found && writeErrorOnNoMatch)
{
WriteInvalidArgumentError(PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedSessionId, RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedSessionId,
sessionId);
}
}
return matches;
}
/// <summary>
/// Gets the matching runspaces by vm name or container id with optional session name.
/// </summary>
/// <param name="writeobject">If true write the object down the pipeline.</param>
/// <param name="filterState">Runspace state filter value.</param>
/// <param name="configurationName">Runspace configuration name filter value.</param>
/// <param name="isContainer">If true the target is a container instead of virtual machine.</param>
/// <returns>List of matching runspaces.</returns>
private Dictionary<Guid, PSSession> GetMatchingRunspacesByVMNameContainerId(bool writeobject,
SessionFilterState filterState,
string configurationName,
bool isContainer)
{
string[] inputNames;
TargetMachineType computerType;
bool supportWildChar;
string[] sessionNames = { "*" };
WildcardPattern configurationNamePattern =
string.IsNullOrEmpty(configurationName) ? null : WildcardPattern.Get(configurationName, WildcardOptions.IgnoreCase);
Dictionary<Guid, PSSession> matches = new Dictionary<Guid, PSSession>();
List<PSSession> remoteRunspaceInfos = this.RunspaceRepository.Runspaces;
// vm name support wild characters, while container id does not.
// vm id does not apply in this method, which does not support wild characters either.
if (isContainer)
{
inputNames = ContainerId;
computerType = TargetMachineType.Container;
supportWildChar = false;
}
else
{
inputNames = VMName;
computerType = TargetMachineType.VirtualMachine;
supportWildChar = true;
}
// When "-name" is not set, we use "*" that means matching all.
if (Name != null)
{
sessionNames = Name;
}
foreach (string inputName in inputNames)
{
WildcardPattern inputNamePattern = WildcardPattern.Get(inputName, WildcardOptions.IgnoreCase);
foreach (string sessionName in sessionNames)
{
WildcardPattern sessionNamePattern =
string.IsNullOrEmpty(sessionName) ? null : WildcardPattern.Get(sessionName, WildcardOptions.IgnoreCase);
var matchingRunspaceInfos = remoteRunspaceInfos
.Where<PSSession>(session => (supportWildChar ? inputNamePattern.IsMatch(session.VMName)
: inputName.Equals(session.ContainerId)) &&
(sessionNamePattern == null || sessionNamePattern.IsMatch(session.Name)) &&
QueryRunspaces.TestRunspaceState(session.Runspace, filterState) &&
(configurationNamePattern == null || configurationNamePattern.IsMatch(session.ConfigurationName)) &&
(session.ComputerType == computerType))
.ToList<PSSession>();
WriteOrAddMatches(matchingRunspaceInfos, writeobject, ref matches);
}
}
return matches;
}
/// <summary>
/// Gets the matching runspaces by vm name or container id with session instanceid.
/// </summary>
/// <param name="writeobject">If true write the object down the pipeline.</param>
/// <param name="filterState">Runspace state filter value.</param>
/// <param name="configurationName">Runspace configuration name filter value.</param>
/// <param name="isContainer">If true the target is a container instead of virtual machine.</param>
/// <returns>List of matching runspaces.</returns>
private Dictionary<Guid, PSSession> GetMatchingRunspacesByVMNameContainerIdSessionInstanceId(bool writeobject,
SessionFilterState filterState,
string configurationName,
bool isContainer)
{
string[] inputNames;
TargetMachineType computerType;
bool supportWildChar;
WildcardPattern configurationNamePattern =
string.IsNullOrEmpty(configurationName) ? null : WildcardPattern.Get(configurationName, WildcardOptions.IgnoreCase);
Dictionary<Guid, PSSession> matches = new Dictionary<Guid, PSSession>();
List<PSSession> remoteRunspaceInfos = this.RunspaceRepository.Runspaces;
// vm name support wild characters, while container id does not.
// vm id does not apply in this method, which does not support wild characters either.
if (isContainer)
{
inputNames = ContainerId;
computerType = TargetMachineType.Container;
supportWildChar = false;
}
else
{
inputNames = VMName;
computerType = TargetMachineType.VirtualMachine;
supportWildChar = true;
}
foreach (string inputName in inputNames)
{
WildcardPattern inputNamePattern = WildcardPattern.Get(inputName, WildcardOptions.IgnoreCase);
foreach (Guid sessionInstanceId in InstanceId)
{
var matchingRunspaceInfos = remoteRunspaceInfos
.Where<PSSession>(session => (supportWildChar ? inputNamePattern.IsMatch(session.VMName)
: inputName.Equals(session.ContainerId)) &&
sessionInstanceId.Equals(session.InstanceId) &&
QueryRunspaces.TestRunspaceState(session.Runspace, filterState) &&
(configurationNamePattern == null || configurationNamePattern.IsMatch(session.ConfigurationName)) &&
(session.ComputerType == computerType))
.ToList<PSSession>();
WriteOrAddMatches(matchingRunspaceInfos, writeobject, ref matches);
}
}
return matches;
}
/// <summary>
/// Gets the matching runspaces by vm guid and optional session name.
/// </summary>
/// <param name="writeobject">If true write the object down the pipeline.</param>
/// <param name="filterState">Runspace state filter value.</param>
/// <param name="configurationName">Runspace configuration name filter value.</param>
/// <returns>List of matching runspaces.</returns>
private Dictionary<Guid, PSSession> GetMatchingRunspacesByVMId(bool writeobject,
SessionFilterState filterState,
string configurationName)
{
string[] sessionNames = { "*" };
WildcardPattern configurationNamePattern =
string.IsNullOrEmpty(configurationName) ? null : WildcardPattern.Get(configurationName, WildcardOptions.IgnoreCase);
Dictionary<Guid, PSSession> matches = new Dictionary<Guid, PSSession>();
List<PSSession> remoteRunspaceInfos = this.RunspaceRepository.Runspaces;
// When "-name" is not set, we use "*" that means matching all .
if (Name != null)
{
sessionNames = Name;
}
foreach (Guid vmId in VMId)
{
foreach (string sessionName in sessionNames)
{
WildcardPattern sessionNamePattern =
string.IsNullOrEmpty(sessionName) ? null : WildcardPattern.Get(sessionName, WildcardOptions.IgnoreCase);
var matchingRunspaceInfos = remoteRunspaceInfos
.Where<PSSession>(session => vmId.Equals(session.VMId) &&
(sessionNamePattern == null || sessionNamePattern.IsMatch(session.Name)) &&
QueryRunspaces.TestRunspaceState(session.Runspace, filterState) &&
(configurationNamePattern == null || configurationNamePattern.IsMatch(session.ConfigurationName)) &&
(session.ComputerType == TargetMachineType.VirtualMachine))
.ToList<PSSession>();
WriteOrAddMatches(matchingRunspaceInfos, writeobject, ref matches);
}
}
return matches;
}
/// <summary>
/// Gets the matching runspaces by vm guid and session instanceid.
/// </summary>
/// <param name="writeobject">If true write the object down the pipeline.</param>
/// <param name="filterState">Runspace state filter value.</param>
/// <param name="configurationName">Runspace configuration name filter value.</param>
/// <returns>List of matching runspaces.</returns>
private Dictionary<Guid, PSSession> GetMatchingRunspacesByVMIdSessionInstanceId(bool writeobject,
SessionFilterState filterState,
string configurationName)
{
WildcardPattern configurationNamePattern =
string.IsNullOrEmpty(configurationName) ? null : WildcardPattern.Get(configurationName, WildcardOptions.IgnoreCase);
Dictionary<Guid, PSSession> matches = new Dictionary<Guid, PSSession>();
List<PSSession> remoteRunspaceInfos = this.RunspaceRepository.Runspaces;
foreach (Guid vmId in VMId)
{
foreach (Guid sessionInstanceId in InstanceId)
{
var matchingRunspaceInfos = remoteRunspaceInfos
.Where<PSSession>(session => vmId.Equals(session.VMId) &&
sessionInstanceId.Equals(session.InstanceId) &&
QueryRunspaces.TestRunspaceState(session.Runspace, filterState) &&
(configurationNamePattern == null || configurationNamePattern.IsMatch(session.ConfigurationName)) &&
(session.ComputerType == TargetMachineType.VirtualMachine))
.ToList<PSSession>();
WriteOrAddMatches(matchingRunspaceInfos, writeobject, ref matches);
}
}
return matches;
}
/// <summary>
/// Write the matching runspace objects down the pipeline, or add to the list.
/// </summary>
/// <param name="matchingRunspaceInfos">The matching runspaces.</param>
/// <param name="writeobject">If true write the object down the pipeline. Otherwise, add to the list.</param>
/// <param name="matches">The list we add the matching runspaces to.</param>
private void WriteOrAddMatches(List<PSSession> matchingRunspaceInfos,
bool writeobject,
ref Dictionary<Guid, PSSession> matches)
{
foreach (PSSession remoteRunspaceInfo in matchingRunspaceInfos)
{
if (writeobject)
{
WriteObject(remoteRunspaceInfo);
}
else
{
try
{
matches.Add(remoteRunspaceInfo.InstanceId, remoteRunspaceInfo);
}
catch (ArgumentException)
{
// if match already found ignore
}
}
}
}
/// <summary>
/// Write invalid argument error.
/// </summary>
private void WriteInvalidArgumentError(PSRemotingErrorId errorId, string resourceString, object errorArgument)
{
string message = GetMessage(resourceString, errorArgument);
WriteError(new ErrorRecord(new ArgumentException(message), errorId.ToString(),
ErrorCategory.InvalidArgument, errorArgument));
}
#endregion Private / Protected Methods
#region Protected Members
/// <summary>
/// Runspace Id parameter set.
/// </summary>
protected const string InstanceIdParameterSet = "InstanceId";
/// <summary>
/// Session id parameter set.
/// </summary>
protected const string IdParameterSet = "Id";
/// <summary>
/// Name parameter set.
/// </summary>
protected const string NameParameterSet = "Name";
#endregion Protected Members
}
#region Helper Classes
/// <summary>
/// Base class for both the helpers. This is an abstract class
/// and the helpers need to derive from this.
/// </summary>
internal abstract class ExecutionCmdletHelper : IThrottleOperation
{
/// <summary>
/// Pipeline associated with this operation.
/// </summary>
internal Pipeline Pipeline
{
get
{
return pipeline;
}
}
protected Pipeline pipeline;
/// <summary>
/// Exception raised internally when any method of this class
/// is executed.
/// </summary>
internal Exception InternalException
{
get
{
return internalException;
}
}
protected Exception internalException;
/// <summary>
/// Internal access to Runspace and Computer helper runspace.
/// </summary>
internal Runspace PipelineRunspace
{
get;
set;
}
#region Runspace Debug
internal void ConfigureRunspaceDebugging(Runspace runspace)
{
if (!RunspaceDebuggingEnabled || (runspace == null) || (runspace.Debugger == null)) { return; }
runspace.Debugger.DebuggerStop += HandleDebuggerStop;
// Configure runspace debugger to preserve unhandled stops (wait for debugger attach)
runspace.Debugger.UnhandledBreakpointMode = UnhandledBreakpointProcessingMode.Wait;
if (RunspaceDebugStepInEnabled)
{
// Configure runspace debugger to run script in step mode
try
{
runspace.Debugger.SetDebuggerStepMode(true);
}
catch (PSInvalidOperationException) { }
}
}
internal void CleanupRunspaceDebugging(Runspace runspace)
{
if ((runspace == null) || (runspace.Debugger == null)) { return; }
runspace.Debugger.DebuggerStop -= HandleDebuggerStop;
}
private void HandleDebuggerStop(object sender, DebuggerStopEventArgs args)
{
PipelineRunspace.Debugger.DebuggerStop -= HandleDebuggerStop;
// Forward event
RaiseRunspaceDebugStopEvent(PipelineRunspace);
// Signal remote session to remain stopped in debuger
args.SuspendRemote = true;
}
#endregion
}
/// <summary>
/// Contains a pipeline and calls InvokeAsync on the pipeline
/// on StartOperation. On StopOperation it calls StopAsync.
/// The handler sends a StopComplete message in OperationComplete
/// for both the functions. This is because, there is only a
/// single state of the pipeline which raises an event on
/// a method call. There are no separate events raised as
/// part of method calls.
/// </summary>
internal class ExecutionCmdletHelperRunspace : ExecutionCmdletHelper
{
/// <summary>
/// Indicates whether or not the server should be using the steppable pipeline.
/// </summary>
internal bool ShouldUseSteppablePipelineOnServer;
/// <summary>
/// Internal constructor.
/// </summary>
/// <param name="pipeline">Pipeline object associated with this operation.</param>
internal ExecutionCmdletHelperRunspace(Pipeline pipeline)
{
this.pipeline = pipeline;
PipelineRunspace = pipeline.Runspace;
this.pipeline.StateChanged += HandlePipelineStateChanged;
}
/// <summary>
/// Invokes the pipeline asynchronously.
/// </summary>
internal override void StartOperation()
{
ConfigureRunspaceDebugging(PipelineRunspace);
try
{
if (ShouldUseSteppablePipelineOnServer && pipeline is RemotePipeline rPipeline)
{
rPipeline.SetIsNested(true);
rPipeline.SetIsSteppable(true);
}
pipeline.InvokeAsync();
}
catch (InvalidRunspaceStateException e)
{
internalException = e;
RaiseOperationCompleteEvent();
}
catch (InvalidPipelineStateException e)
{
internalException = e;
RaiseOperationCompleteEvent();
}
catch (InvalidOperationException e)
{
internalException = e;
RaiseOperationCompleteEvent();
}
}
/// <summary>
/// Closes the pipeline asynchronously.
/// </summary>
internal override void StopOperation()
{
if (pipeline.PipelineStateInfo.State == PipelineState.Running ||
pipeline.PipelineStateInfo.State == PipelineState.Disconnected ||
pipeline.PipelineStateInfo.State == PipelineState.NotStarted)
{
// If the pipeline state has reached Complete/Failed/Stopped
// by the time control reaches here, then this operation
// becomes a no-op. However, an OperationComplete would have
// already been raised from the handler
pipeline.StopAsync();
}
else
{
// will have to raise OperationComplete from here,
// else ThrottleManager will have
RaiseOperationCompleteEvent();
}
}
internal override event EventHandler<OperationStateEventArgs> OperationComplete;
/// <summary>
/// Handles the state changed events for the pipeline. This is registered in both
/// StartOperation and StopOperation. Here nothing more is done excepting raising
/// the OperationComplete event appropriately which will be handled by the cmdlet.
/// </summary>
/// <param name="sender">Source of this event.</param>
/// <param name="stateEventArgs">object describing state information about the
/// pipeline</param>
private void HandlePipelineStateChanged(object sender, PipelineStateEventArgs stateEventArgs)
{
PipelineStateInfo stateInfo = stateEventArgs.PipelineStateInfo;
switch (stateInfo.State)
{
case PipelineState.Running:
case PipelineState.NotStarted:
case PipelineState.Stopping:
case PipelineState.Disconnected:
return;
}
RaiseOperationCompleteEvent(stateEventArgs);
}
/// <summary>
/// Raise an OperationComplete Event. The base event will be
/// null in this case.
/// </summary>
private void RaiseOperationCompleteEvent()
{
RaiseOperationCompleteEvent(null);
}
/// <summary>
/// Raise an operation complete event.
/// </summary>
/// <param name="baseEventArgs">The event args which actually
/// raises this operation complete</param>
private void RaiseOperationCompleteEvent(EventArgs baseEventArgs)
{
CleanupRunspaceDebugging(PipelineRunspace);
if (pipeline != null)
{
// Dispose the pipeline object and release data and remoting resources.
// Pipeline object remains to provide information on final state and any errors incurred.
pipeline.StateChanged -= HandlePipelineStateChanged;
pipeline.Dispose();
}
OperationStateEventArgs operationStateEventArgs =
new OperationStateEventArgs();
operationStateEventArgs.OperationState =
OperationState.StopComplete;
operationStateEventArgs.BaseEvent = baseEventArgs;
OperationComplete?.SafeInvoke(this, operationStateEventArgs);
}
}
/// <summary>
/// This helper class contains a runspace and
/// an associated pipeline. On StartOperation it calls
/// OpenAsync on the runspace. In the handler for runspace,
/// when the runspace is successfully opened it calls
/// InvokeAsync on the pipeline. StartOperation
/// is assumed complete when both the operations complete.
/// StopOperation will call StopAsync first on the pipeline
/// and then close the associated runspace. StopOperation
/// is considered complete when both these operations
/// complete. The handler sends a StopComplete message in
/// OperationComplete for both the calls.
/// </summary>
internal class ExecutionCmdletHelperComputerName : ExecutionCmdletHelper
{
/// <summary>
/// Determines if the command should be invoked and then disconnect the
/// remote runspace from the client.
/// </summary>
private readonly bool _invokeAndDisconnect;
/// <summary>
/// The remote runspace created using the computer name
/// parameter set details.
/// </summary>
internal RemoteRunspace RemoteRunspace { get; private set; }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="remoteRunspace">RemoteRunspace that is associated
/// with this operation</param>
/// <param name="pipeline">Pipeline created from the remote runspace.</param>
/// <param name="invokeAndDisconnect">Indicates if pipeline should be disconnected after invoking command.</param>
internal ExecutionCmdletHelperComputerName(RemoteRunspace remoteRunspace, Pipeline pipeline, bool invokeAndDisconnect = false)
{
Dbg.Assert(remoteRunspace != null,
"RemoteRunspace reference cannot be null");
PipelineRunspace = remoteRunspace;
_invokeAndDisconnect = invokeAndDisconnect;
RemoteRunspace = remoteRunspace;
remoteRunspace.StateChanged += HandleRunspaceStateChanged;
Dbg.Assert(pipeline != null,
"Pipeline cannot be null or empty");
this.pipeline = pipeline;
pipeline.StateChanged += HandlePipelineStateChanged;
}
/// <summary>
/// Call OpenAsync() on the RemoteRunspace.
/// </summary>
internal override void StartOperation()
{
try
{
RemoteRunspace.OpenAsync();
}
catch (PSRemotingTransportException e)
{
internalException = e;
RaiseOperationCompleteEvent();
}
}
/// <summary>
/// StopAsync on the pipeline.
/// </summary>
internal override void StopOperation()
{
bool needToStop = false; // indicates whether to call StopAsync
if (pipeline.PipelineStateInfo.State == PipelineState.Running ||
pipeline.PipelineStateInfo.State == PipelineState.NotStarted)
{
needToStop = true;
}
if (needToStop)
{
// If the pipeline state has reached Complete/Failed/Stopped
// by the time control reaches here, then this operation
// becomes a no-op. However, an OperationComplete would have
// already been raised from the handler
pipeline.StopAsync();
}
else
{
// raise an OperationComplete event here. Else the
// throttle manager will not respond as it will be waiting for
// this StopOperation to complete
RaiseOperationCompleteEvent();
}
}
internal override event EventHandler<OperationStateEventArgs> OperationComplete;
/// <summary>
/// Handles the state changed event for runspace operations.
/// </summary>
/// <param name="sender">Sender of this information.</param>
/// <param name="stateEventArgs">Object describing this event.</param>
private void HandleRunspaceStateChanged(object sender,
RunspaceStateEventArgs stateEventArgs)
{
RunspaceState state = stateEventArgs.RunspaceStateInfo.State;
switch (state)
{
case RunspaceState.BeforeOpen:
case RunspaceState.Opening:
case RunspaceState.Closing:
return;
case RunspaceState.Opened:
{
ConfigureRunspaceDebugging(RemoteRunspace);
// if successfully opened
// Call InvokeAsync() on the pipeline
try
{
if (_invokeAndDisconnect)
{
pipeline.InvokeAsyncAndDisconnect();
}
else
{
pipeline.InvokeAsync();
}
}
catch (InvalidPipelineStateException)
{
RemoteRunspace.CloseAsync();
}
catch (InvalidRunspaceStateException e)
{
internalException = e;
RemoteRunspace.CloseAsync();
}
}
break;
case RunspaceState.Broken:
{
RaiseOperationCompleteEvent(stateEventArgs);
}
break;
case RunspaceState.Closed:
{
// raise a OperationComplete event with
// StopComplete message
if (stateEventArgs.RunspaceStateInfo.Reason != null)
{
RaiseOperationCompleteEvent(stateEventArgs);
}
else
{
RaiseOperationCompleteEvent();
}
}
break;
}
}
/// <summary>
/// Handles the state changed event for the pipeline.
/// </summary>
/// <param name="sender">Sender of this information.</param>
/// <param name="stateEventArgs">Object describing this event.</param>
private void HandlePipelineStateChanged(object sender,
PipelineStateEventArgs stateEventArgs)
{
PipelineState state = stateEventArgs.PipelineStateInfo.State;
switch (state)
{
case PipelineState.Running:
case PipelineState.NotStarted:
case PipelineState.Stopping:
return;
case PipelineState.Completed:
case PipelineState.Stopped:
case PipelineState.Failed:
RemoteRunspace?.CloseAsync();
break;
}
}
/// <summary>
/// Raise an OperationComplete Event. The base event will be
/// null in this case.
/// </summary>
private void RaiseOperationCompleteEvent()
{
RaiseOperationCompleteEvent(null);
}
/// <summary>
/// Raise an operation complete event.
/// </summary>
/// <param name="baseEventArgs">The event args which actually
/// raises this operation complete</param>
private void RaiseOperationCompleteEvent(EventArgs baseEventArgs)
{
if (pipeline != null)
{
// Dispose the pipeline object and release data and remoting resources.
// Pipeline object remains to provide information on final state and any errors incurred.
pipeline.StateChanged -= HandlePipelineStateChanged;
pipeline.Dispose();
}
if (RemoteRunspace != null)
{
// Dispose of the runspace object.
RemoteRunspace.Dispose();
RemoteRunspace = null;
}
OperationStateEventArgs operationStateEventArgs =
new OperationStateEventArgs();
operationStateEventArgs.OperationState =
OperationState.StopComplete;
operationStateEventArgs.BaseEvent = baseEventArgs;
OperationComplete.SafeInvoke(this, operationStateEventArgs);
}
}
#region Path Resolver
/// <summary>
/// A helper class to resolve the path.
/// </summary>
internal static class PathResolver
{
/// <summary>
/// Resolves the specified path and verifies the path belongs to
/// FileSystemProvider.
/// </summary>
/// <param name="path">Path to resolve.</param>
/// <param name="isLiteralPath">True if wildcard expansion should be suppressed for this path.</param>
/// <param name="cmdlet">reference to calling cmdlet. This will be used for
/// for writing errors</param>
/// <param name="allowNonexistingPaths"></param>
/// <param name="resourceString">Resource string for error when path is not from filesystem provider.</param>
/// <returns>A fully qualified string representing filename.</returns>
internal static string ResolveProviderAndPath(string path, bool isLiteralPath, PSCmdlet cmdlet, bool allowNonexistingPaths, string resourceString)
{
// First resolve path
PathInfo resolvedPath = ResolvePath(path, isLiteralPath, allowNonexistingPaths, cmdlet);
if (resolvedPath.Provider.ImplementingType == typeof(FileSystemProvider))
{
return resolvedPath.ProviderPath;
}
throw PSTraceSource.NewInvalidOperationException(resourceString, resolvedPath.Provider.Name);
}
/// <summary>
/// Resolves the specified path to PathInfo objects.
/// </summary>
/// <param name="pathToResolve">
/// The path to be resolved. Each path may contain glob characters.
/// </param>
/// <param name="isLiteralPath">
/// True if wildcard expansion should be suppressed for pathToResolve.
/// </param>
/// <param name="allowNonexistingPaths">
/// If true, resolves the path even if it doesn't exist.
/// </param>
/// <param name="cmdlet">
/// Calling cmdlet
/// </param>
/// <returns>
/// A string representing the resolved path.
/// </returns>
private static PathInfo ResolvePath(
string pathToResolve,
bool isLiteralPath,
bool allowNonexistingPaths,
PSCmdlet cmdlet)
{
// Construct cmdletprovidercontext
CmdletProviderContext cmdContext = new CmdletProviderContext(cmdlet);
cmdContext.SuppressWildcardExpansion = isLiteralPath;
Collection<PathInfo> results = new Collection<PathInfo>();
try
{
// First resolve path
Collection<PathInfo> pathInfos =
cmdlet.SessionState.Path.GetResolvedPSPathFromPSPath(
pathToResolve,
cmdContext);
foreach (PathInfo pathInfo in pathInfos)
{
results.Add(pathInfo);
}
}
catch (PSNotSupportedException notSupported)
{
cmdlet.ThrowTerminatingError(
new ErrorRecord(
notSupported.ErrorRecord,
notSupported));
}
catch (System.Management.Automation.DriveNotFoundException driveNotFound)
{
cmdlet.ThrowTerminatingError(
new ErrorRecord(
driveNotFound.ErrorRecord,
driveNotFound));
}
catch (ProviderNotFoundException providerNotFound)
{
cmdlet.ThrowTerminatingError(
new ErrorRecord(
providerNotFound.ErrorRecord,
providerNotFound));
}
catch (ItemNotFoundException pathNotFound)
{
if (allowNonexistingPaths)
{
ProviderInfo provider = null;
System.Management.Automation.PSDriveInfo drive = null;
string unresolvedPath =
cmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath(
pathToResolve,
cmdContext,
out provider,
out drive);
PathInfo pathInfo =
new PathInfo(
drive,
provider,
unresolvedPath,
cmdlet.SessionState);
results.Add(pathInfo);
}
else
{
cmdlet.ThrowTerminatingError(
new ErrorRecord(
pathNotFound.ErrorRecord,
pathNotFound));
}
}
if (results.Count == 1)
{
return results[0];
}
else // if (results.Count > 1)
{
Exception e = PSTraceSource.NewNotSupportedException();
cmdlet.ThrowTerminatingError(
new ErrorRecord(e,
"NotSupported",
ErrorCategory.NotImplemented,
results));
return null;
}
}
}
#endregion
#region QueryRunspaces
internal class QueryRunspaces
{
#region Constructor
internal QueryRunspaces()
{
_stopProcessing = false;
}
#endregion
#region Internal Methods
/// <summary>
/// Queries all remote computers specified in collection of WSManConnectionInfo objects
/// and returns disconnected PSSession objects ready for connection to server.
/// Returned sessions can be matched to Guids or Names.
/// </summary>
/// <param name="connectionInfos">Collection of WSManConnectionInfo objects.</param>
/// <param name="host">Host for PSSession objects.</param>
/// <param name="stream">Out stream object.</param>
/// <param name="runspaceRepository">Runspace repository.</param>
/// <param name="throttleLimit">Throttle limit.</param>
/// <param name="filterState">Runspace state filter value.</param>
/// <param name="matchIds">Array of session Guids to match to.</param>
/// <param name="matchNames">Array of session Names to match to.</param>
/// <param name="configurationName">Configuration name to match to.</param>
/// <returns>Collection of disconnected PSSession objects.</returns>
internal Collection<PSSession> GetDisconnectedSessions(Collection<WSManConnectionInfo> connectionInfos, PSHost host,
ObjectStream stream, RunspaceRepository runspaceRepository,
int throttleLimit, SessionFilterState filterState,
Guid[] matchIds, string[] matchNames, string configurationName)
{
Collection<PSSession> filteredPSSessions = new Collection<PSSession>();
// Create a query operation for each connection information object.
foreach (WSManConnectionInfo connectionInfo in connectionInfos)
{
Runspace[] runspaces = null;
try
{
runspaces = Runspace.GetRunspaces(connectionInfo, host, BuiltInTypesTable);
}
catch (System.Management.Automation.RuntimeException e)
{
if (e.InnerException is InvalidOperationException)
{
// The Get-WSManInstance cmdlet used to query remote computers for runspaces will throw
// an Invalid Operation (inner) exception if the connectInfo object is invalid, including
// invalid computer names.
// We don't want to propagate the exception so just write error here.
if (stream.ObjectWriter != null && stream.ObjectWriter.IsOpen)
{
int errorCode;
string msg = StringUtil.Format(RemotingErrorIdStrings.QueryForRunspacesFailed, connectionInfo.ComputerName, ExtractMessage(e.InnerException, out errorCode));
string FQEID = WSManTransportManagerUtils.GetFQEIDFromTransportError(errorCode, "RemotePSSessionQueryFailed");
Exception reason = new RuntimeException(msg, e.InnerException);
ErrorRecord errorRecord = new ErrorRecord(reason, FQEID, ErrorCategory.InvalidOperation, connectionInfo);
stream.ObjectWriter.Write((Action<Cmdlet>)(cmdlet => cmdlet.WriteError(errorRecord)));
}
}
else
{
throw;
}
}
if (_stopProcessing)
{
break;
}
// Add all runspaces meeting filter criteria to collection.
if (runspaces != null)
{
// Convert configuration name into shell Uri for comparison.
string shellUri = null;
if (!string.IsNullOrEmpty(configurationName))
{
shellUri = configurationName.Contains(WSManNativeApi.ResourceURIPrefix, StringComparison.OrdinalIgnoreCase)
? configurationName
: WSManNativeApi.ResourceURIPrefix + configurationName;
}
foreach (Runspace runspace in runspaces)
{
// Filter returned runspaces by ConfigurationName if provided.
if (shellUri != null)
{
// Compare with returned shell Uri in connection info.
WSManConnectionInfo wsmanConnectionInfo = runspace.ConnectionInfo as WSManConnectionInfo;
if (wsmanConnectionInfo != null &&
!shellUri.Equals(wsmanConnectionInfo.ShellUri, StringComparison.OrdinalIgnoreCase))
{
continue;
}
}
// Check the repository for an existing viable PSSession for
// this runspace (based on instanceId). Use the existing
// local runspace instead of the one returned from the server
// query.
PSSession existingPSSession = null;
if (runspaceRepository != null)
{
existingPSSession = runspaceRepository.GetItem(runspace.InstanceId);
}
if (existingPSSession != null &&
UseExistingRunspace(existingPSSession.Runspace, runspace))
{
if (TestRunspaceState(existingPSSession.Runspace, filterState))
{
filteredPSSessions.Add(existingPSSession);
}
}
else if (TestRunspaceState(runspace, filterState))
{
filteredPSSessions.Add(new PSSession(runspace as RemoteRunspace));
}
}
}
}
// Return only PSSessions that match provided Ids or Names.
if ((matchIds != null) && (filteredPSSessions.Count > 0))
{
Collection<PSSession> matchIdsSessions = new Collection<PSSession>();
foreach (Guid id in matchIds)
{
bool matchFound = false;
foreach (PSSession psSession in filteredPSSessions)
{
if (_stopProcessing)
{
break;
}
if (psSession.Runspace.InstanceId.Equals(id))
{
matchFound = true;
matchIdsSessions.Add(psSession);
break;
}
}
if (!matchFound && stream.ObjectWriter != null && stream.ObjectWriter.IsOpen)
{
string msg = StringUtil.Format(RemotingErrorIdStrings.SessionIdMatchFailed, id);
Exception reason = new RuntimeException(msg);
ErrorRecord errorRecord = new ErrorRecord(reason, "PSSessionIdMatchFail", ErrorCategory.InvalidOperation, id);
stream.ObjectWriter.Write((Action<Cmdlet>)(cmdlet => cmdlet.WriteError(errorRecord)));
}
}
// Return all found sessions.
return matchIdsSessions;
}
else if ((matchNames != null) && (filteredPSSessions.Count > 0))
{
Collection<PSSession> matchNamesSessions = new Collection<PSSession>();
foreach (string name in matchNames)
{
WildcardPattern namePattern = WildcardPattern.Get(name, WildcardOptions.IgnoreCase);
bool matchFound = false;
foreach (PSSession psSession in filteredPSSessions)
{
if (_stopProcessing)
{
break;
}
if (namePattern.IsMatch(((RemoteRunspace)psSession.Runspace).RunspacePool.RemoteRunspacePoolInternal.Name))
{
matchFound = true;
matchNamesSessions.Add(psSession);
}
}
if (!matchFound && stream.ObjectWriter != null && stream.ObjectWriter.IsOpen)
{
string msg = StringUtil.Format(RemotingErrorIdStrings.SessionNameMatchFailed, name);
Exception reason = new RuntimeException(msg);
ErrorRecord errorRecord = new ErrorRecord(reason, "PSSessionNameMatchFail", ErrorCategory.InvalidOperation, name);
stream.ObjectWriter.Write((Action<Cmdlet>)(cmdlet => cmdlet.WriteError(errorRecord)));
}
}
return matchNamesSessions;
}
else
{
// Return all collected sessions.
return filteredPSSessions;
}
}
/// <summary>
/// Returns true if the existing runspace should be returned to the user
/// a. If the existing runspace is not broken
/// b. If the queried runspace is not connected to a different user.
/// </summary>
/// <param name="existingRunspace"></param>
/// <param name="queriedrunspace"></param>
/// <returns></returns>
private static bool UseExistingRunspace(
Runspace existingRunspace,
Runspace queriedrunspace)
{
Dbg.Assert(existingRunspace != null, "Invalid parameter.");
Dbg.Assert(queriedrunspace != null, "Invalid parameter.");
if (existingRunspace.RunspaceStateInfo.State == RunspaceState.Broken)
{
return false;
}
if (existingRunspace.RunspaceStateInfo.State == RunspaceState.Disconnected &&
queriedrunspace.RunspaceAvailability == RunspaceAvailability.Busy)
{
return false;
}
// Update existing runspace to have latest DisconnectedOn/ExpiresOn data.
existingRunspace.DisconnectedOn = queriedrunspace.DisconnectedOn;
existingRunspace.ExpiresOn = queriedrunspace.ExpiresOn;
return true;
}
/// <summary>
/// Returns Exception message. If message is WSMan Xml then
/// the WSMan message and error code is extracted and returned.
/// </summary>
/// <param name="e">Exception.</param>
/// <param name="errorCode">Returned WSMan error code.</param>
/// <returns>WSMan message.</returns>
internal static string ExtractMessage(
Exception e,
out int errorCode)
{
errorCode = 0;
if (e == null ||
e.Message == null)
{
return string.Empty;
}
string rtnMsg = null;
try
{
System.Xml.XmlReaderSettings xmlReaderSettings = InternalDeserializer.XmlReaderSettingsForUntrustedXmlDocument.Clone();
xmlReaderSettings.MaxCharactersInDocument = 4096;
xmlReaderSettings.MaxCharactersFromEntities = 1024;
xmlReaderSettings.DtdProcessing = System.Xml.DtdProcessing.Prohibit;
using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(
new System.IO.StringReader(e.Message), xmlReaderSettings))
{
while (reader.Read())
{
if (reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (reader.LocalName.Equals("Message", StringComparison.OrdinalIgnoreCase))
{
rtnMsg = reader.ReadElementContentAsString();
}
else if (reader.LocalName.Equals("WSManFault", StringComparison.OrdinalIgnoreCase))
{
string errorCodeString = reader.GetAttribute("Code");
if (errorCodeString != null)
{
try
{
// WinRM returns both signed and unsigned 32 bit string values. Convert to signed 32 bit integer.
Int64 eCode = Convert.ToInt64(errorCodeString, System.Globalization.NumberFormatInfo.InvariantInfo);
unchecked
{
errorCode = (int)eCode;
}
}
catch (FormatException)
{ }
catch (OverflowException)
{ }
}
}
}
}
}
}
catch (System.Xml.XmlException)
{ }
return rtnMsg ?? e.Message;
}
/// <summary>
/// Discontinue all remote server query operations.
/// </summary>
internal void StopAllOperations()
{
_stopProcessing = true;
}
/// <summary>
/// Compares the runspace filter state with the runspace state.
/// </summary>
/// <param name="runspace">Runspace object to test.</param>
/// <param name="filterState">Filter state to compare.</param>
/// <returns>Result of test.</returns>
public static bool TestRunspaceState(Runspace runspace, SessionFilterState filterState)
{
bool result;
switch (filterState)
{
case SessionFilterState.All:
result = true;
break;
case SessionFilterState.Opened:
result = (runspace.RunspaceStateInfo.State == RunspaceState.Opened);
break;
case SessionFilterState.Closed:
result = (runspace.RunspaceStateInfo.State == RunspaceState.Closed);
break;
case SessionFilterState.Disconnected:
result = (runspace.RunspaceStateInfo.State == RunspaceState.Disconnected);
break;
case SessionFilterState.Broken:
result = (runspace.RunspaceStateInfo.State == RunspaceState.Broken);
break;
default:
Dbg.Assert(false, "Invalid SessionFilterState value.");
result = false;
break;
}
return result;
}
/// <summary>
/// Returns the default type table for built-in PowerShell types.
/// </summary>
internal static TypeTable BuiltInTypesTable
{
get
{
if (s_TypeTable == null)
{
lock (s_SyncObject)
{
s_TypeTable ??= TypeTable.LoadDefaultTypeFiles();
}
}
return s_TypeTable;
}
}
#endregion
#region Private Members
private bool _stopProcessing;
private static readonly object s_SyncObject = new object();
private static TypeTable s_TypeTable;
#endregion
}
#endregion
#region SessionFilterState Enum
/// <summary>
/// Runspace states that can be used as filters for querying remote runspaces.
/// </summary>
public enum SessionFilterState
{
/// <summary>
/// Return runspaces in any state.
/// </summary>
All = 0,
/// <summary>
/// Return runspaces in Opened state.
/// </summary>
Opened = 1,
/// <summary>
/// Return runspaces in Disconnected state.
/// </summary>
Disconnected = 2,
/// <summary>
/// Return runspaces in Closed state.
/// </summary>
Closed = 3,
/// <summary>
/// Return runspaces in Broken state.
/// </summary>
Broken = 4
}
#endregion
#endregion Helper Classes
}
namespace System.Management.Automation.Remoting
{
/// <summary>
/// IMPORTANT: proxy configuration is supported for HTTPS only; for HTTP, the direct
/// connection to the server is used.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags")]
public enum ProxyAccessType
{
/// <summary>
/// ProxyAccessType is not specified. That means Proxy information (ProxyAccessType, ProxyAuthenticationMechanism
/// and ProxyCredential)is not passed to WSMan at all.
/// </summary>
None = 0,
/// <summary>
/// Use the Internet Explorer proxy configuration for the current user.
/// Internet Explorer proxy settings for the current active network connection.
/// This option requires the user profile to be loaded, so the option can
/// be directly used when called within a process that is running under
/// an interactive user account identity; if the client application is running
/// under a user context different than the interactive user, the client
/// application has to explicitly load the user profile prior to using this option.
/// </summary>
IEConfig = 1,
/// <summary>
/// Proxy settings configured for WinHTTP, using the ProxyCfg.exe utility.
/// </summary>
WinHttpConfig = 2,
/// <summary>
/// Force autodetection of proxy.
/// </summary>
AutoDetect = 4,
/// <summary>
/// Do not use a proxy server - resolves all host names locally.
/// </summary>
NoProxyServer = 8
}
/// <summary>
/// Options for a remote PSSession.
/// </summary>
public sealed class PSSessionOption
{
/// <summary>
/// Creates a new instance of <see cref="PSSessionOption"/>
/// </summary>
public PSSessionOption()
{
}
/// <summary>
/// The MaximumConnectionRedirectionCount parameter enables the implicit redirection functionality.
/// -1 = no limit
/// 0 = no redirection.
/// </summary>
public int MaximumConnectionRedirectionCount { get; set; } = WSManConnectionInfo.defaultMaximumConnectionRedirectionCount;
/// <summary>
/// If false, underlying WSMan infrastructure will compress data sent on the network.
/// If true, data will not be compressed. Compression improves performance by
/// reducing the amount of data sent on the network. Compression my require extra
/// memory consumption and CPU usage. In cases where available memory / CPU is less,
/// set this property to "true".
/// By default the value of this property is "false".
/// </summary>
public bool NoCompression { get; set; } = false;
/// <summary>
/// If <see langword="true"/> then Operating System won't load the user profile (i.e. registry keys under HKCU) on the remote server
/// which can result in a faster session creation time. This option won't have any effect if the remote machine has
/// already loaded the profile (i.e. in another session).
/// </summary>
public bool NoMachineProfile { get; set; } = false;
/// <summary>
/// By default, ProxyAccessType is None, that means Proxy information (ProxyAccessType,
/// ProxyAuthenticationMechanism and ProxyCredential)is not passed to WSMan at all.
/// </summary>
public ProxyAccessType ProxyAccessType { get; set; } = ProxyAccessType.None;
/// <summary>
/// The following is the definition of the input parameter "ProxyAuthentication".
/// This parameter takes a set of authentication methods the user can select
/// from. The available options should be as follows:
/// - Negotiate: Use the default authentication (as defined by the underlying
/// protocol) for establishing a remote connection.
/// - Basic: Use basic authentication for establishing a remote connection
/// - Digest: Use Digest authentication for establishing a remote connection
///
/// Default is Negotiate.
/// </summary>
public AuthenticationMechanism ProxyAuthentication
{
get
{
return _proxyAuthentication;
}
set
{
switch (value)
{
case AuthenticationMechanism.Basic:
case AuthenticationMechanism.Negotiate:
case AuthenticationMechanism.Digest:
_proxyAuthentication = value;
break;
default:
string message = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.ProxyAmbiguousAuthentication,
value,
nameof(AuthenticationMechanism.Basic),
nameof(AuthenticationMechanism.Negotiate),
nameof(AuthenticationMechanism.Digest));
throw new ArgumentException(message);
}
}
}
private AuthenticationMechanism _proxyAuthentication = AuthenticationMechanism.Negotiate;
/// <summary>
/// The following is the definition of the input parameter "ProxyCredential".
/// </summary>
public PSCredential ProxyCredential { get; set; }
/// <summary>
/// When connecting over HTTPS, the client does not validate that the server
/// certificate is signed by a trusted certificate authority (CA). Use only when
/// the remote computer is trusted by other means, for example, if the remote
/// computer is part of a network that is physically secure and isolated or the
/// remote computer is listed as a trusted host in WinRM configuration.
/// </summary>
public bool SkipCACheck { get; set; }
/// <summary>
/// Indicates that certificate common name (CN) of the server need not match the
/// hostname of the server. Used only in remote operations using https. This
/// option should only be used for trusted machines.
/// </summary>
public bool SkipCNCheck { get; set; }
/// <summary>
/// Indicates that certificate common name (CN) of the server need not match the
/// hostname of the server. Used only in remote operations using https. This
/// option should only be used for trusted machines.
/// </summary>
public bool SkipRevocationCheck { get; set; }
/// <summary>
/// The duration for which PowerShell remoting waits before timing out
/// for any operation. The user would like to tweak this timeout
/// depending on whether he/she is connecting to a machine in the data
/// center or across a slow WAN.
///
/// Default: 3*60*1000 == 3minutes.
/// </summary>
public TimeSpan OperationTimeout { get; set; } = TimeSpan.FromMilliseconds(BaseTransportManager.ClientDefaultOperationTimeoutMs);
/// <summary>
/// Specifies that no encryption will be used when doing remote operations over
/// http. Unencrypted traffic is not allowed by default and must be enabled in
/// the local configuration.
/// </summary>
public bool NoEncryption { get; set; }
/// <summary>
/// Indicates the request is encoded in UTF16 format rather than UTF8 format;
/// UTF8 is the default.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "UTF")]
public bool UseUTF16 { get; set; }
/// <summary>
/// Uses Service Principal Name (SPN) along with the Port number during authentication.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SPN")]
public bool IncludePortInSPN { get; set; }
/// <summary>
/// Determines how server in disconnected state deals with cached output
/// data when the cache becomes filled.
/// Default value is 'block mode' where command execution is blocked after
/// the server side data cache becomes filled.
/// </summary>
public OutputBufferingMode OutputBufferingMode { get; set; } = WSManConnectionInfo.DefaultOutputBufferingMode;
/// <summary>
/// Number of times a connection will be re-attempted when a connection fails due to network
/// issues.
/// </summary>
public int MaxConnectionRetryCount { get; set; } = WSManConnectionInfo.DefaultMaxConnectionRetryCount;
/// <summary>
/// Culture that the remote session should use.
/// </summary>
public CultureInfo Culture { get; set; }
/// <summary>
/// UI culture that the remote session should use.
/// </summary>
public CultureInfo UICulture { get; set; }
/// <summary>
/// Total data (in bytes) that can be received from a remote machine
/// targeted towards a command. If null, then the size is unlimited.
/// Default is unlimited data.
/// </summary>
public int? MaximumReceivedDataSizePerCommand { get; set; }
/// <summary>
/// Maximum size (in bytes) of a deserialized object received from a remote machine.
/// If null, then the size is unlimited. Default is 200MB object size.
/// </summary>
public int? MaximumReceivedObjectSize { get; set; } = 200 << 20;
/// <summary>
/// Application arguments the server can see in <see cref="System.Management.Automation.Remoting.PSSenderInfo.ApplicationArguments"/>
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public PSPrimitiveDictionary ApplicationArguments { get; set; }
/// <summary>
/// The duration for which PowerShell remoting waits before timing out on a connection to a remote machine.
/// Simply put, the timeout for a remote runspace creation.
/// The user would like to tweak this timeout depending on whether
/// he/she is connecting to a machine in the data center or across a slow WAN.
///
/// Default: 3 * 60 * 1000 = 3 minutes.
/// </summary>
public TimeSpan OpenTimeout { get; set; } = TimeSpan.FromMilliseconds(RunspaceConnectionInfo.DefaultOpenTimeout);
/// <summary>
/// The duration for which PowerShell should wait before it times out on cancel operations
/// (close runspace or stop powershell). For instance, when the user hits ctrl-C,
/// New-PSSession cmdlet tries to call a stop on all remote runspaces which are in the Opening state.
/// The user wouldn't mind waiting for 15 seconds, but this should be time bound and of a shorter duration.
/// A high timeout here like 3 minutes will give the user a feeling that the PowerShell client is not responding.
///
/// Default: 60 * 1000 = 1 minute.
/// </summary>
public TimeSpan CancelTimeout { get; set; } = TimeSpan.FromMilliseconds(RunspaceConnectionInfo.defaultCancelTimeout);
/// <summary>
/// The duration for which a Runspace on server needs to wait before it declares the client dead and closes itself down.
/// This is especially important as these values may have to be configured differently for enterprise administration
/// and exchange scenarios.
///
/// Default: -1 -> Use current server value for IdleTimeout.
/// </summary>
public TimeSpan IdleTimeout { get; set; } = TimeSpan.FromMilliseconds(RunspaceConnectionInfo.DefaultIdleTimeout);
}
}
|