File size: 211,037 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 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
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.Host;
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Management.Automation.Runspaces;
using System.Text;
namespace System.Management.Automation
{
/// <summary>
/// This is the interface between the CommandProcessor and the various
/// parameter binders required to bind parameters to a cmdlet.
/// </summary>
internal class CmdletParameterBinderController : ParameterBinderController
{
#region tracer
[TraceSource("ParameterBinderController", "Controls the interaction between the command processor and the parameter binder(s).")]
private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("ParameterBinderController", "Controls the interaction between the command processor and the parameter binder(s).");
#endregion tracer
#region ctor
/// <summary>
/// Initializes the cmdlet parameter binder controller for
/// the specified cmdlet and engine context.
/// </summary>
/// <param name="cmdlet">
/// The cmdlet that the parameters will be bound to.
/// </param>
/// <param name="commandMetadata">
/// The metadata about the cmdlet.
/// </param>
/// <param name="parameterBinder">
/// The default parameter binder to use.
/// </param>
internal CmdletParameterBinderController(
Cmdlet cmdlet,
CommandMetadata commandMetadata,
ParameterBinderBase parameterBinder)
: base(
cmdlet.MyInvocation,
cmdlet.Context,
parameterBinder)
{
if (cmdlet == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(cmdlet));
}
if (commandMetadata == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(commandMetadata));
}
this.Command = cmdlet;
_commandRuntime = (MshCommandRuntime)cmdlet.CommandRuntime;
_commandMetadata = commandMetadata;
// Add the static parameter metadata to the bindable parameters
// And add them to the unbound parameters list
if (commandMetadata.ImplementsDynamicParameters)
{
// ReplaceMetadata makes a copy for us, so we can use that collection as is.
this.UnboundParameters = this.BindableParameters.ReplaceMetadata(commandMetadata.StaticCommandParameterMetadata);
}
else
{
_bindableParameters = commandMetadata.StaticCommandParameterMetadata;
// Must make a copy of the list because we'll modify it.
this.UnboundParameters = new List<MergedCompiledCommandParameter>(_bindableParameters.BindableParameters.Values);
}
}
#endregion ctor
#region helper_methods
/// <summary>
/// Binds the specified command-line parameters to the target.
/// </summary>
/// <param name="arguments">
/// Parameters to the command.
/// </param>
/// <exception cref="ParameterBindingException">
/// If any parameters fail to bind,
/// or
/// If any mandatory parameters are missing.
/// </exception>
/// <exception cref="MetadataException">
/// If there is an error generating the metadata for dynamic parameters.
/// </exception>
internal void BindCommandLineParameters(Collection<CommandParameterInternal> arguments)
{
s_tracer.WriteLine("Argument count: {0}", arguments.Count);
BindCommandLineParametersNoValidation(arguments);
// Is pipeline input expected?
bool isPipelineInputExpected = !(_commandRuntime.IsClosed && _commandRuntime.InputPipe.Empty);
int validParameterSetCount;
if (!isPipelineInputExpected)
{
// Since pipeline input is not expected, ensure that we have a single
// parameter set and that all the mandatory
// parameters for the working parameter set are specified, or prompt
validParameterSetCount = ValidateParameterSets(false, true);
}
else
{
// Use ValidateParameterSets to get the number of valid parameter
// sets.
// NTRAID#Windows Out Of Band Releases-2005/11/07-923917-JonN
validParameterSetCount = ValidateParameterSets(true, false);
}
// If the parameter set is determined and the default parameters are not used
// we try the default parameter binding again because it may contain some mandatory
// parameters
if (validParameterSetCount == 1 && !DefaultParameterBindingInUse)
{
ApplyDefaultParameterBinding("Mandatory Checking", false);
}
// If there are multiple valid parameter sets and we are expecting pipeline inputs,
// we should filter out those parameter sets that cannot take pipeline inputs anymore.
if (validParameterSetCount > 1 && isPipelineInputExpected)
{
uint filteredValidParameterSetFlags = FilterParameterSetsTakingNoPipelineInput();
if (filteredValidParameterSetFlags != _currentParameterSetFlag)
{
_currentParameterSetFlag = filteredValidParameterSetFlags;
// The valid parameter set flag is narrowed down, we get the new validParameterSetCount
validParameterSetCount = ValidateParameterSets(true, false);
}
}
using (ParameterBinderBase.bindingTracer.TraceScope(
"MANDATORY PARAMETER CHECK on cmdlet [{0}]",
_commandMetadata.Name))
{
try
{
// The missingMandatoryParameters out parameter is used for error reporting when binding from the pipeline.
// We're not binding from the pipeline here, and if a mandatory non-pipeline parameter is missing, it will
// be prompted for, or an exception will be raised, so we can ignore the missingMandatoryParameters out parameter.
Collection<MergedCompiledCommandParameter> missingMandatoryParameters;
// We shouldn't prompt for mandatory parameters if this command is private.
bool promptForMandatoryParameters = (Command.CommandInfo.Visibility == SessionStateEntryVisibility.Public);
HandleUnboundMandatoryParameters(validParameterSetCount, true, promptForMandatoryParameters, isPipelineInputExpected, out missingMandatoryParameters);
if (DefaultParameterBinder is ScriptParameterBinder)
{
BindUnboundScriptParameters();
}
}
catch (ParameterBindingException pbex)
{
if (!DefaultParameterBindingInUse)
{
throw;
}
ThrowElaboratedBindingException(pbex);
}
}
// If there is no more expected input, ensure there is a single
// parameter set selected
if (!isPipelineInputExpected)
{
VerifyParameterSetSelected();
}
// Set the prepipeline parameter set flags so that they can be restored
// between each pipeline object.
_prePipelineProcessingParameterSetFlags = _currentParameterSetFlag;
}
/// <summary>
/// Binds the unbound arguments to parameters but does not
/// perform mandatory parameter validation or parameter set validation.
/// </summary>
internal void BindCommandLineParametersNoValidation(Collection<CommandParameterInternal> arguments)
{
var psCompiledScriptCmdlet = this.Command as PSScriptCmdlet;
psCompiledScriptCmdlet?.PrepareForBinding(this.CommandLineParameters);
InitUnboundArguments(arguments);
CommandMetadata cmdletMetadata = _commandMetadata;
// Clear the warningSet at the beginning.
_warningSet.Clear();
// Parse $PSDefaultParameterValues to get all valid <parameter, value> pairs
_allDefaultParameterValuePairs = this.GetDefaultParameterValuePairs(true);
// Set to false at the beginning
DefaultParameterBindingInUse = false;
// Clear the bound default parameters at the beginning
BoundDefaultParameters.Clear();
// Reparse the arguments based on the merged metadata
ReparseUnboundArguments();
using (ParameterBinderBase.bindingTracer.TraceScope(
"BIND NAMED cmd line args [{0}]",
_commandMetadata.Name))
{
// Bind the actual arguments
UnboundArguments = BindNamedParameters(_currentParameterSetFlag, this.UnboundArguments);
}
ParameterBindingException reportedBindingException;
ParameterBindingException currentBindingException;
using (ParameterBinderBase.bindingTracer.TraceScope(
"BIND POSITIONAL cmd line args [{0}]",
_commandMetadata.Name))
{
// Now that we know the parameter set, bind the positional parameters
UnboundArguments =
BindPositionalParameters(
UnboundArguments,
_currentParameterSetFlag,
cmdletMetadata.DefaultParameterSetFlag,
out currentBindingException);
reportedBindingException = currentBindingException;
}
// Try applying the default parameter binding after POSITIONAL BIND so that the default parameter
// values can influence the parameter set selection earlier than the default parameter set.
ApplyDefaultParameterBinding("POSITIONAL BIND", false);
// We need to make sure there is at least one valid parameter set. Its
// OK to allow more than one as long as one of them takes pipeline input.
// NTRAID#Windows Out Of Band Releases-2006/02/14-928660-JonN
// Pipeline input fails to bind to pipeline enabled parameter
// second parameter changed from true to false
ValidateParameterSets(true, false);
// Always get the dynamic parameters as there may be mandatory parameters there
// Now try binding the dynamic parameters
HandleCommandLineDynamicParameters(out currentBindingException);
// Try binding the default parameters again. After dynamic binding, new parameter metadata are
// included, so it's possible a previously unsuccessful binding will succeed.
ApplyDefaultParameterBinding("DYNAMIC BIND", true);
// If this generated an exception (but we didn't have one from the non-dynamic
// parameters, report on this one.
reportedBindingException ??= currentBindingException;
// If the cmdlet implements a ValueFromRemainingArguments parameter (VarArgs)
// bind the unbound arguments to that parameter.
HandleRemainingArguments();
VerifyArgumentsProcessed(reportedBindingException);
}
/// <summary>
/// Process all valid parameter sets, and filter out those that don't take any pipeline input.
/// </summary>
/// <returns>
/// The new valid parameter set flags
/// </returns>
private uint FilterParameterSetsTakingNoPipelineInput()
{
uint parameterSetsTakingPipeInput = 0;
bool findPipeParameterInAllSets = false;
foreach (KeyValuePair<MergedCompiledCommandParameter, DelayedScriptBlockArgument> entry in _delayBindScriptBlocks)
{
parameterSetsTakingPipeInput |= entry.Key.Parameter.ParameterSetFlags;
}
foreach (MergedCompiledCommandParameter parameter in UnboundParameters)
{
// If a parameter doesn't take pipeline input at all, we can skip it
if (!parameter.Parameter.IsPipelineParameterInSomeParameterSet)
{
continue;
}
var matchingParameterSetMetadata =
parameter.Parameter.GetMatchingParameterSetData(_currentParameterSetFlag);
foreach (ParameterSetSpecificMetadata parameterSetMetadata in matchingParameterSetMetadata)
{
if (parameterSetMetadata.ValueFromPipeline || parameterSetMetadata.ValueFromPipelineByPropertyName)
{
if (parameterSetMetadata.ParameterSetFlag == 0 && parameterSetMetadata.IsInAllSets)
{
// The parameter takes pipeline input and is in all sets, we don't change the _currentParameterSetFlag
parameterSetsTakingPipeInput = 0;
findPipeParameterInAllSets = true;
break;
}
else
{
parameterSetsTakingPipeInput |= parameterSetMetadata.ParameterSetFlag;
}
}
}
if (findPipeParameterInAllSets)
break;
}
// If parameterSetsTakingPipeInput is 0, then no parameter set from the _currentParameterSetFlag can take piped objects.
// Then we just leave what it was, and the pipeline binding deal with the error later
if (parameterSetsTakingPipeInput != 0)
return _currentParameterSetFlag & parameterSetsTakingPipeInput;
else
return _currentParameterSetFlag;
}
/// <summary>
/// Apply the binding for the default parameter defined by the user.
/// </summary>
/// <param name="bindingStage">
/// Dictate which binding stage this default binding happens
/// </param>
/// <param name="isDynamic">
/// Special operation needed if the default binding happens at the dynamic binding stage
/// </param>
/// <returns></returns>
private void ApplyDefaultParameterBinding(string bindingStage, bool isDynamic)
{
if (!_useDefaultParameterBinding)
{
return;
}
if (isDynamic)
{
// Get user defined default parameter value pairs again, so that the
// dynamic parameter value pairs could be involved.
_allDefaultParameterValuePairs = GetDefaultParameterValuePairs(false);
}
Dictionary<MergedCompiledCommandParameter, object> qualifiedParameterValuePairs = GetQualifiedParameterValuePairs(_currentParameterSetFlag, _allDefaultParameterValuePairs);
if (qualifiedParameterValuePairs != null)
{
bool isSuccess = false;
using (ParameterBinderBase.bindingTracer.TraceScope(
"BIND DEFAULT <parameter, value> pairs after [{0}] for [{1}]",
bindingStage, _commandMetadata.Name))
{
isSuccess = BindDefaultParameters(_currentParameterSetFlag, qualifiedParameterValuePairs);
if (isSuccess && !DefaultParameterBindingInUse)
{
DefaultParameterBindingInUse = true;
}
}
s_tracer.WriteLine("BIND DEFAULT after [{0}] result [{1}]", bindingStage, isSuccess);
}
return;
}
/// <summary>
/// Bind the default parameter value pairs.
/// </summary>
/// <param name="validParameterSetFlag">ValidParameterSetFlag.</param>
/// <param name="defaultParameterValues">Default value pairs.</param>
/// <returns>
/// true if there is at least one default parameter bound successfully
/// false if there is no default parameter bound successfully
/// </returns>
private bool BindDefaultParameters(uint validParameterSetFlag, Dictionary<MergedCompiledCommandParameter, object> defaultParameterValues)
{
bool ret = false;
foreach (var pair in defaultParameterValues)
{
MergedCompiledCommandParameter parameter = pair.Key;
object argumentValue = pair.Value;
string parameterName = parameter.Parameter.Name;
try
{
ScriptBlock scriptBlockArg = argumentValue as ScriptBlock;
if (scriptBlockArg != null)
{
// Get the current binding state, and pass it to the ScriptBlock as the argument
// The 'arg' includes HashSet properties 'BoundParameters', 'BoundPositionalParameters',
// 'BoundDefaultParameters', and 'LastBindingStage'. So the user can set value
// to a parameter depending on the current binding state.
PSObject arg = WrapBindingState();
Collection<PSObject> results = scriptBlockArg.Invoke(arg);
if (results == null || results.Count == 0)
{
continue;
}
else if (results.Count == 1)
{
argumentValue = results[0];
}
else
{
argumentValue = results;
}
}
CommandParameterInternal bindableArgument =
CommandParameterInternal.CreateParameterWithArgument(
/*parameterAst*/null, parameterName, "-" + parameterName + ":",
/*argumentAst*/null, argumentValue, false);
bool bindResult =
BindParameter(
validParameterSetFlag,
bindableArgument,
parameter,
ParameterBindingFlags.ShouldCoerceType | ParameterBindingFlags.DelayBindScriptBlock);
if (bindResult && !ret)
{
ret = true;
}
if (bindResult)
{
BoundDefaultParameters.Add(parameterName);
}
}
catch (ParameterBindingException ex)
{
// We don't want the failures in default binding affect the command line binding,
// so we write out a warning and ignore this binding failure
if (!_warningSet.Contains(_commandMetadata.Name + Separator + parameterName))
{
string message = string.Format(CultureInfo.InvariantCulture,
ParameterBinderStrings.FailToBindDefaultParameter,
LanguagePrimitives.IsNull(argumentValue) ? "null" : argumentValue.ToString(),
parameterName, ex.Message);
_commandRuntime.WriteWarning(message);
_warningSet.Add(_commandMetadata.Name + Separator + parameterName);
}
continue;
}
}
return ret;
}
/// <summary>
/// Wrap up current binding state to provide more information to the user.
/// </summary>
/// <returns></returns>
private PSObject WrapBindingState()
{
HashSet<string> boundParameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
HashSet<string> boundPositionalParameterNames =
this.DefaultParameterBinder.CommandLineParameters.CopyBoundPositionalParameters();
HashSet<string> boundDefaultParameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string paramName in BoundParameters.Keys)
{
boundParameterNames.Add(paramName);
}
foreach (string paramName in BoundDefaultParameters)
{
boundDefaultParameterNames.Add(paramName);
}
PSObject result = new PSObject();
result.Properties.Add(new PSNoteProperty("BoundParameters", boundParameterNames));
result.Properties.Add(new PSNoteProperty("BoundPositionalParameters", boundPositionalParameterNames));
result.Properties.Add(new PSNoteProperty("BoundDefaultParameters", boundDefaultParameterNames));
return result;
}
/// <summary>
/// Get all qualified default parameter value pairs based on the
/// given currentParameterSetFlag.
/// </summary>
/// <param name="currentParameterSetFlag"></param>
/// <param name="availableParameterValuePairs"></param>
/// <returns>Null if no qualified pair found.</returns>
private Dictionary<MergedCompiledCommandParameter, object> GetQualifiedParameterValuePairs(
uint currentParameterSetFlag,
Dictionary<MergedCompiledCommandParameter, object> availableParameterValuePairs)
{
if (availableParameterValuePairs == null)
{
return null;
}
Dictionary<MergedCompiledCommandParameter, object> result = new Dictionary<MergedCompiledCommandParameter, object>();
uint possibleParameterFlag = uint.MaxValue;
foreach (var pair in availableParameterValuePairs)
{
MergedCompiledCommandParameter param = pair.Key;
if ((param.Parameter.ParameterSetFlags & currentParameterSetFlag) == 0 && !param.Parameter.IsInAllSets)
{
continue;
}
if (BoundArguments.ContainsKey(param.Parameter.Name))
{
continue;
}
// check if this param's set conflicts with other possible params.
if (param.Parameter.ParameterSetFlags != 0)
{
possibleParameterFlag &= param.Parameter.ParameterSetFlags;
if (possibleParameterFlag == 0)
{
return null;
}
}
result.Add(param, pair.Value);
}
if (result.Count > 0)
{
return result;
}
return null;
}
/// <summary>
/// Get the aliases of the current cmdlet.
/// </summary>
/// <returns></returns>
private List<string> GetAliasOfCurrentCmdlet()
{
var results = Context.SessionState.Internal.GetAliasesByCommandName(_commandMetadata.Name).ToList();
return results.Count > 0 ? results : null;
}
/// <summary>
/// Check if the passed-in aliasName matches an alias name in _aliasList.
/// </summary>
/// <param name="aliasName"></param>
/// <returns></returns>
private bool MatchAnyAlias(string aliasName)
{
if (_aliasList == null)
{
return false;
}
bool result = false;
WildcardPattern aliasPattern = WildcardPattern.Get(aliasName, WildcardOptions.IgnoreCase);
foreach (string alias in _aliasList)
{
if (aliasPattern.IsMatch(alias))
{
result = true;
break;
}
}
return result;
}
internal IDictionary DefaultParameterValues { get; set; }
/// <summary>
/// Get all available default parameter value pairs.
/// </summary>
/// <returns>Return the available parameter value pairs. Otherwise return null.</returns>
private Dictionary<MergedCompiledCommandParameter, object> GetDefaultParameterValuePairs(bool needToGetAlias)
{
if (DefaultParameterValues == null)
{
_useDefaultParameterBinding = false;
return null;
}
var availablePairs = new Dictionary<MergedCompiledCommandParameter, object>();
if (needToGetAlias && DefaultParameterValues.Count > 0)
{
// Get all aliases of the current cmdlet
_aliasList = GetAliasOfCurrentCmdlet();
}
// Set flag to true by default
_useDefaultParameterBinding = true;
string currentCmdletName = _commandMetadata.Name;
IDictionary<string, MergedCompiledCommandParameter> bindableParameters = BindableParameters.BindableParameters;
IDictionary<string, MergedCompiledCommandParameter> bindableAlias = BindableParameters.AliasedParameters;
// Contains parameters that are set with different values by settings in $PSDefaultParameterValues.
// We should ignore those settings and write out a warning
var parametersToRemove = new HashSet<MergedCompiledCommandParameter>();
var wildcardDefault = new Dictionary<string, object>();
// Contains keys that are in bad format. For every bad format key, we should write out a warning message
// the first time we encounter it, and remove it from the $PSDefaultParameterValues
var keysToRemove = new List<object>();
foreach (DictionaryEntry entry in DefaultParameterValues)
{
if (entry.Key is not string key)
{
continue;
}
key = key.Trim();
string cmdletName = null;
string parameterName = null;
// The key is not in valid format
if (!DefaultParameterDictionary.CheckKeyIsValid(key, ref cmdletName, ref parameterName))
{
if (key.Equals("Disabled", StringComparison.OrdinalIgnoreCase) &&
LanguagePrimitives.IsTrue(entry.Value))
{
_useDefaultParameterBinding = false;
return null;
}
// Write out a warning message if the key is not 'Disabled'
if (!key.Equals("Disabled", StringComparison.OrdinalIgnoreCase))
{
keysToRemove.Add(entry.Key);
}
continue;
}
Diagnostics.Assert(cmdletName != null && parameterName != null, "The cmdletName and parameterName should be set in CheckKeyIsValid");
if (WildcardPattern.ContainsWildcardCharacters(key))
{
wildcardDefault.Add(cmdletName + Separator + parameterName, entry.Value);
continue;
}
// Continue to process this entry only if the specified cmdletName is the name
// of the current cmdlet, or is an alias name of the current cmdlet.
if (!cmdletName.Equals(currentCmdletName, StringComparison.OrdinalIgnoreCase) && !MatchAnyAlias(cmdletName))
{
continue;
}
GetDefaultParameterValuePairsHelper(
cmdletName, parameterName, entry.Value,
bindableParameters, bindableAlias,
availablePairs, parametersToRemove);
}
foreach (KeyValuePair<string, object> wildcard in wildcardDefault)
{
string key = wildcard.Key;
string cmdletName = key.Substring(0, key.IndexOf(Separator, StringComparison.OrdinalIgnoreCase));
string parameterName = key.Substring(key.IndexOf(Separator, StringComparison.OrdinalIgnoreCase) + Separator.Length);
WildcardPattern cmdletPattern = WildcardPattern.Get(cmdletName, WildcardOptions.IgnoreCase);
// Continue to process this entry only if the cmdletName matches the name of the current
// cmdlet, or matches an alias name of the current cmdlet
if (!cmdletPattern.IsMatch(currentCmdletName) && !MatchAnyAlias(cmdletName))
{
continue;
}
if (!WildcardPattern.ContainsWildcardCharacters(parameterName))
{
GetDefaultParameterValuePairsHelper(
cmdletName, parameterName, wildcard.Value,
bindableParameters, bindableAlias,
availablePairs, parametersToRemove);
continue;
}
WildcardPattern parameterPattern = MemberMatch.GetNamePattern(parameterName);
var matches = new List<MergedCompiledCommandParameter>();
foreach (KeyValuePair<string, MergedCompiledCommandParameter> entry in bindableParameters)
{
if (parameterPattern.IsMatch(entry.Key))
{
matches.Add(entry.Value);
}
}
foreach (KeyValuePair<string, MergedCompiledCommandParameter> entry in bindableAlias)
{
if (parameterPattern.IsMatch(entry.Key))
{
matches.Add(entry.Value);
}
}
if (matches.Count > 1)
{
// The parameterPattern matches more than one parameters, so we write out a warning message and ignore this setting
if (!_warningSet.Contains(cmdletName + Separator + parameterName))
{
_commandRuntime.WriteWarning(
string.Format(CultureInfo.InvariantCulture, ParameterBinderStrings.MultipleParametersMatched, parameterName));
_warningSet.Add(cmdletName + Separator + parameterName);
}
continue;
}
if (matches.Count == 1)
{
if (!availablePairs.ContainsKey(matches[0]))
{
availablePairs.Add(matches[0], wildcard.Value);
continue;
}
if (!wildcard.Value.Equals(availablePairs[matches[0]]))
{
if (!_warningSet.Contains(cmdletName + Separator + parameterName))
{
_commandRuntime.WriteWarning(
string.Format(CultureInfo.InvariantCulture, ParameterBinderStrings.DifferentValuesAssignedToSingleParameter, parameterName));
_warningSet.Add(cmdletName + Separator + parameterName);
}
parametersToRemove.Add(matches[0]);
}
}
}
if (keysToRemove.Count > 0)
{
var keysInError = new StringBuilder();
foreach (object badFormatKey in keysToRemove)
{
if (DefaultParameterValues.Contains(badFormatKey))
DefaultParameterValues.Remove(badFormatKey);
keysInError.Append(badFormatKey.ToString() + ", ");
}
keysInError.Remove(keysInError.Length - 2, 2);
var multipleKeys = keysToRemove.Count > 1;
string formatString = multipleKeys
? ParameterBinderStrings.MultipleKeysInBadFormat
: ParameterBinderStrings.SingleKeyInBadFormat;
_commandRuntime.WriteWarning(
string.Format(CultureInfo.InvariantCulture, formatString, keysInError));
}
foreach (MergedCompiledCommandParameter param in parametersToRemove)
{
availablePairs.Remove(param);
}
if (availablePairs.Count > 0)
{
return availablePairs;
}
return null;
}
/// <summary>
/// A helper method for GetDefaultParameterValuePairs.
/// </summary>
/// <param name="cmdletName"></param>
/// <param name="paramName"></param>
/// <param name="paramValue"></param>
/// <param name="bindableParameters"></param>
/// <param name="bindableAlias"></param>
/// <param name="result"></param>
/// <param name="parametersToRemove"></param>
private void GetDefaultParameterValuePairsHelper(
string cmdletName, string paramName, object paramValue,
IDictionary<string, MergedCompiledCommandParameter> bindableParameters,
IDictionary<string, MergedCompiledCommandParameter> bindableAlias,
Dictionary<MergedCompiledCommandParameter, object> result,
HashSet<MergedCompiledCommandParameter> parametersToRemove)
{
// No exception should be thrown if we cannot find a match for the 'paramName',
// because the 'paramName' could be a dynamic parameter name, and this dynamic parameter
// hasn't been introduced at the current stage.
bool writeWarning = false;
MergedCompiledCommandParameter matchParameter;
object resultObject;
if (bindableParameters.TryGetValue(paramName, out matchParameter))
{
if (!result.TryGetValue(matchParameter, out resultObject))
{
result.Add(matchParameter, paramValue);
return;
}
if (!paramValue.Equals(resultObject))
{
writeWarning = true;
parametersToRemove.Add(matchParameter);
}
}
else
{
if (bindableAlias.TryGetValue(paramName, out matchParameter))
{
if (!result.TryGetValue(matchParameter, out resultObject))
{
result.Add(matchParameter, paramValue);
return;
}
if (!paramValue.Equals(resultObject))
{
writeWarning = true;
parametersToRemove.Add(matchParameter);
}
}
}
if (writeWarning && !_warningSet.Contains(cmdletName + Separator + paramName))
{
_commandRuntime.WriteWarning(
string.Format(CultureInfo.InvariantCulture, ParameterBinderStrings.DifferentValuesAssignedToSingleParameter, paramName));
_warningSet.Add(cmdletName + Separator + paramName);
}
}
/// <summary>
/// Verify if all arguments from the command line are bound.
/// </summary>
/// <param name="originalBindingException">
/// Previous binding exceptions that possibly causes the failure
/// </param>
private void VerifyArgumentsProcessed(ParameterBindingException originalBindingException)
{
// Now verify that all the arguments that were passed in were processed.
if (UnboundArguments.Count > 0)
{
ParameterBindingException bindingException;
CommandParameterInternal parameter = UnboundArguments[0];
// Get the argument type that was specified
Type specifiedType = null;
object argumentValue = parameter.ArgumentValue;
if (argumentValue != null && argumentValue != UnboundParameter.Value)
{
specifiedType = argumentValue.GetType();
}
if (parameter.ParameterNameSpecified)
{
bindingException =
new ParameterBindingException(
ErrorCategory.InvalidArgument,
this.Command.MyInvocation,
GetParameterErrorExtent(parameter),
parameter.ParameterName,
null,
specifiedType,
ParameterBinderStrings.NamedParameterNotFound,
"NamedParameterNotFound");
}
else
{
// If this was a positional parameter, and we have the original exception,
// report on the original error
if (originalBindingException != null)
{
bindingException = originalBindingException;
}
// Otherwise, give a generic error.
else
{
string argument = StringLiterals.DollarNull;
if (parameter.ArgumentValue != null)
{
try
{
argument = parameter.ArgumentValue.ToString();
}
catch (Exception e)
{
bindingException =
new ParameterBindingArgumentTransformationException(
e,
ErrorCategory.InvalidData,
this.InvocationInfo,
null,
null,
null,
parameter.ArgumentValue.GetType(),
ParameterBinderStrings.ParameterArgumentTransformationErrorMessageOnly,
"ParameterArgumentTransformationErrorMessageOnly",
e.Message);
if (!DefaultParameterBindingInUse)
{
throw bindingException;
}
else
{
ThrowElaboratedBindingException(bindingException);
}
}
}
bindingException =
new ParameterBindingException(
ErrorCategory.InvalidArgument,
this.Command.MyInvocation,
null,
argument,
null,
specifiedType,
ParameterBinderStrings.PositionalParameterNotFound,
"PositionalParameterNotFound");
}
}
if (!DefaultParameterBindingInUse)
{
throw bindingException;
}
else
{
ThrowElaboratedBindingException(bindingException);
}
}
}
/// <summary>
/// Verifies that a single parameter set is selected and throws an exception if
/// one of there are multiple and one of them is not the default parameter set.
/// </summary>
private void VerifyParameterSetSelected()
{
// Now verify that a parameter set has been selected if any parameter sets
// were defined.
if (this.BindableParameters.ParameterSetCount > 1)
{
if (_currentParameterSetFlag == uint.MaxValue)
{
if ((_currentParameterSetFlag &
_commandMetadata.DefaultParameterSetFlag) != 0 &&
_commandMetadata.DefaultParameterSetFlag != uint.MaxValue)
{
ParameterBinderBase.bindingTracer.WriteLine(
"{0} valid parameter sets, using the DEFAULT PARAMETER SET: [{0}]",
this.BindableParameters.ParameterSetCount.ToString(),
_commandMetadata.DefaultParameterSetName);
_currentParameterSetFlag =
_commandMetadata.DefaultParameterSetFlag;
}
else
{
ParameterBinderBase.bindingTracer.TraceError(
"ERROR: {0} valid parameter sets, but NOT DEFAULT PARAMETER SET.",
this.BindableParameters.ParameterSetCount);
// Throw an exception for ambiguous parameter set
ThrowAmbiguousParameterSetException(_currentParameterSetFlag, BindableParameters);
}
}
}
}
/// <summary>
/// Restores the specified parameter to the original value.
/// </summary>
/// <param name="argumentToBind">
/// The argument containing the value to restore.
/// </param>
/// <param name="parameter">
/// The metadata for the parameter to restore.
/// </param>
/// <returns>
/// True if the parameter was restored correctly, or false otherwise.
/// </returns>
private bool RestoreParameter(CommandParameterInternal argumentToBind, MergedCompiledCommandParameter parameter)
{
switch (parameter.BinderAssociation)
{
case ParameterBinderAssociation.DeclaredFormalParameters:
DefaultParameterBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter);
break;
case ParameterBinderAssociation.CommonParameters:
CommonParametersBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter);
break;
case ParameterBinderAssociation.ShouldProcessParameters:
Diagnostics.Assert(
_commandMetadata.SupportsShouldProcess,
"The metadata for the ShouldProcessParameters should only be available if the command supports ShouldProcess");
ShouldProcessParametersBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter);
break;
case ParameterBinderAssociation.PagingParameters:
Diagnostics.Assert(
_commandMetadata.SupportsPaging,
"The metadata for the PagingParameters should only be available if the command supports paging");
PagingParametersBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter);
break;
case ParameterBinderAssociation.TransactionParameters:
Diagnostics.Assert(
_commandMetadata.SupportsTransactions,
"The metadata for the TransactionParameters should only be available if the command supports Transactions");
TransactionParametersBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter);
break;
case ParameterBinderAssociation.DynamicParameters:
Diagnostics.Assert(
_commandMetadata.ImplementsDynamicParameters,
"The metadata for the dynamic parameters should only be available if the command supports IDynamicParameters");
_dynamicParameterBinder?.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter);
break;
}
return true;
}
/// <summary>
/// Validate the given named parameter against the specified parameter set,
/// and then bind the argument to the parameter.
/// </summary>
protected override void BindNamedParameter(
uint parameterSets,
CommandParameterInternal argument,
MergedCompiledCommandParameter parameter)
{
if ((parameter.Parameter.ParameterSetFlags & parameterSets) == 0 &&
!parameter.Parameter.IsInAllSets)
{
string parameterSetName = BindableParameters.GetParameterSetName(parameterSets);
ParameterBindingException bindingException =
new ParameterBindingException(
ErrorCategory.InvalidArgument,
this.Command.MyInvocation,
errorPosition: null,
argument.ParameterName,
parameterType: null,
typeSpecified: null,
ParameterBinderStrings.ParameterNotInParameterSet,
"ParameterNotInParameterSet",
parameterSetName);
// Might be caused by default parameter binding
if (!DefaultParameterBindingInUse)
{
throw bindingException;
}
else
{
ThrowElaboratedBindingException(bindingException);
}
}
try
{
BindParameter(parameterSets, argument, parameter,
ParameterBindingFlags.ShouldCoerceType | ParameterBindingFlags.DelayBindScriptBlock);
}
catch (ParameterBindingException pbex)
{
if (!DefaultParameterBindingInUse)
{
throw;
}
ThrowElaboratedBindingException(pbex);
}
}
/// <summary>
/// Determines if a ScriptBlock can be bound directly to the type of the specified parameter.
/// </summary>
/// <param name="parameter">
/// The metadata of the parameter to check the type of.
/// </param>
/// <returns>
/// true if the parameter type is Object, ScriptBlock, derived from ScriptBlock, a
/// collection of ScriptBlocks, a collection of Objects, or a collection of types derived from
/// ScriptBlock.
/// False otherwise.
/// </returns>
private static bool IsParameterScriptBlockBindable(MergedCompiledCommandParameter parameter)
{
bool result = false;
Type parameterType = parameter.Parameter.Type;
do // false loop
{
if (parameterType == typeof(object))
{
result = true;
break;
}
if (parameterType == typeof(ScriptBlock))
{
result = true;
break;
}
if (parameterType.IsSubclassOf(typeof(ScriptBlock)))
{
result = true;
break;
}
ParameterCollectionTypeInformation parameterCollectionTypeInfo = parameter.Parameter.CollectionTypeInformation;
if (parameterCollectionTypeInfo.ParameterCollectionType != ParameterCollectionType.NotCollection)
{
if (parameterCollectionTypeInfo.ElementType == typeof(object))
{
result = true;
break;
}
if (parameterCollectionTypeInfo.ElementType == typeof(ScriptBlock))
{
result = true;
break;
}
if (parameterCollectionTypeInfo.ElementType.IsSubclassOf(typeof(ScriptBlock)))
{
result = true;
break;
}
}
} while (false);
s_tracer.WriteLine("IsParameterScriptBlockBindable: result = {0}", result);
return result;
}
/// <summary>
/// Binds the specified argument to the specified parameter using the appropriate
/// parameter binder. If the argument is of type ScriptBlock and the parameter takes
/// pipeline input, then the ScriptBlock is saved off in the delay-bind ScriptBlock
/// container for further processing of pipeline input and is not bound as the argument
/// to the parameter.
/// </summary>
/// <param name="parameterSets">
/// The parameter set used to bind the arguments.
/// </param>
/// <param name="argument">
/// The argument to be bound.
/// </param>
/// <param name="parameter">
/// The metadata for the parameter to bind the argument to.
/// </param>
/// <param name="flags">
/// Flags for type coercion, validation, and script block binding.
///
/// ParameterBindingFlags.DelayBindScriptBlock:
/// If set, arguments that are of type ScriptBlock where the parameter is not of type ScriptBlock,
/// Object, or PSObject will be stored for execution during pipeline input and not bound as
/// an argument to the parameter.
/// </param>
/// <returns>
/// True if the parameter was successfully bound. False if <paramref name="flags"/>
/// has the flag <see cref="ParameterBindingFlags.ShouldCoerceType"/> set and the type does not match the parameter type.
/// </returns>
internal override bool BindParameter(
uint parameterSets,
CommandParameterInternal argument,
MergedCompiledCommandParameter parameter,
ParameterBindingFlags flags)
{
// Now we need to check to see if the argument value is
// a ScriptBlock. If it is and the parameter type is
// not ScriptBlock and not Object, then we need to delay
// binding until a pipeline object is provided to invoke
// the ScriptBlock.
// Note: we haven't yet determined that only a single parameter
// set is valid, so we have to take a best guess on pipeline input
// based on the current valid parameter sets.
bool continueWithBinding = true;
if ((flags & ParameterBindingFlags.DelayBindScriptBlock) != 0 &&
parameter.Parameter.DoesParameterSetTakePipelineInput(parameterSets) &&
argument.ArgumentSpecified)
{
object argumentValue = argument.ArgumentValue;
if ((argumentValue is ScriptBlock || argumentValue is DelayedScriptBlockArgument) &&
!IsParameterScriptBlockBindable(parameter))
{
// Now check to see if the command expects to have pipeline input.
// If not, we should throw an exception now to inform the
// user with more information than they would get if it was
// considered an unbound mandatory parameter.
if (_commandRuntime.IsClosed && _commandRuntime.InputPipe.Empty)
{
ParameterBindingException bindingException =
new ParameterBindingException(
ErrorCategory.MetadataError,
this.Command.MyInvocation,
GetErrorExtent(argument),
parameter.Parameter.Name,
parameter.Parameter.Type,
null,
ParameterBinderStrings.ScriptBlockArgumentNoInput,
"ScriptBlockArgumentNoInput");
throw bindingException;
}
ParameterBinderBase.bindingTracer.WriteLine(
"Adding ScriptBlock to delay-bind list for parameter '{0}'",
parameter.Parameter.Name);
// We need to delay binding of this argument to the parameter
DelayedScriptBlockArgument delayedArg = argumentValue as DelayedScriptBlockArgument ??
new DelayedScriptBlockArgument { _argument = argument, _parameterBinder = this };
if (!_delayBindScriptBlocks.ContainsKey(parameter))
{
_delayBindScriptBlocks.Add(parameter, delayedArg);
}
// We treat the parameter as bound, but really the
// script block gets run for each pipeline object and
// the result is bound.
if (parameter.Parameter.ParameterSetFlags != 0)
{
_currentParameterSetFlag &= parameter.Parameter.ParameterSetFlags;
}
UnboundParameters.Remove(parameter);
BoundParameters[parameter.Parameter.Name] = parameter;
BoundArguments[parameter.Parameter.Name] = argument;
if (DefaultParameterBinder.RecordBoundParameters &&
!DefaultParameterBinder.CommandLineParameters.ContainsKey(parameter.Parameter.Name))
{
DefaultParameterBinder.CommandLineParameters.Add(parameter.Parameter.Name, delayedArg);
}
continueWithBinding = false;
}
}
bool result = false;
if (continueWithBinding)
{
try
{
result = BindParameter(argument, parameter, flags);
}
catch (Exception e)
{
bool rethrow = true;
if ((flags & ParameterBindingFlags.ShouldCoerceType) == 0)
{
// Attributes are used to do type coercion and result in various exceptions.
// We assume that if we aren't trying to do type coercion, we should avoid
// propagating type conversion exceptions.
while (e != null)
{
if (e is PSInvalidCastException)
{
rethrow = false;
break;
}
e = e.InnerException;
}
}
if (rethrow)
{
throw;
}
}
}
return result;
}
/// <summary>
/// Binds the specified argument to the specified parameter using the appropriate
/// parameter binder.
/// </summary>
/// <param name="argument">
/// The argument to be bound.
/// </param>
/// <param name="parameter">
/// The metadata for the parameter to bind the argument to.
/// </param>
/// <param name="flags">
/// Flags for type coercion and validation.
/// </param>
/// <returns>
/// True if the parameter was successfully bound. False if <paramref name="flags"/>
/// has the flag <see cref="ParameterBindingFlags.ShouldCoerceType"/> set and the type does not match the parameter type.
/// </returns>
private bool BindParameter(
CommandParameterInternal argument,
MergedCompiledCommandParameter parameter,
ParameterBindingFlags flags)
{
bool result = false;
switch (parameter.BinderAssociation)
{
case ParameterBinderAssociation.DeclaredFormalParameters:
result =
DefaultParameterBinder.BindParameter(
argument,
parameter.Parameter,
flags);
break;
case ParameterBinderAssociation.CommonParameters:
result =
CommonParametersBinder.BindParameter(
argument,
parameter.Parameter,
flags);
break;
case ParameterBinderAssociation.ShouldProcessParameters:
Diagnostics.Assert(
_commandMetadata.SupportsShouldProcess,
"The metadata for the ShouldProcessParameters should only be available if the command supports ShouldProcess");
result =
ShouldProcessParametersBinder.BindParameter(
argument,
parameter.Parameter,
flags);
break;
case ParameterBinderAssociation.PagingParameters:
Diagnostics.Assert(
_commandMetadata.SupportsPaging,
"The metadata for the PagingParameters should only be available if the command supports paging");
result =
PagingParametersBinder.BindParameter(
argument,
parameter.Parameter,
flags);
break;
case ParameterBinderAssociation.TransactionParameters:
Diagnostics.Assert(
_commandMetadata.SupportsTransactions,
"The metadata for the TransactionsParameters should only be available if the command supports transactions");
result =
TransactionParametersBinder.BindParameter(
argument,
parameter.Parameter,
flags);
break;
case ParameterBinderAssociation.DynamicParameters:
Diagnostics.Assert(
_commandMetadata.ImplementsDynamicParameters,
"The metadata for the dynamic parameters should only be available if the command supports IDynamicParameters");
if (_dynamicParameterBinder != null)
{
result =
_dynamicParameterBinder.BindParameter(
argument,
parameter.Parameter,
flags);
}
break;
}
if (result && ((flags & ParameterBindingFlags.IsDefaultValue) == 0))
{
// Update the current valid parameter set flags
if (parameter.Parameter.ParameterSetFlags != 0)
{
_currentParameterSetFlag &= parameter.Parameter.ParameterSetFlags;
}
UnboundParameters.Remove(parameter);
if (!BoundParameters.ContainsKey(parameter.Parameter.Name))
{
BoundParameters.Add(parameter.Parameter.Name, parameter);
}
if (!BoundArguments.ContainsKey(parameter.Parameter.Name))
{
BoundArguments.Add(parameter.Parameter.Name, argument);
}
if (parameter.Parameter.ObsoleteAttribute != null &&
(flags & ParameterBindingFlags.IsDefaultValue) == 0 &&
!BoundObsoleteParameterNames.Contains(parameter.Parameter.Name))
{
string obsoleteWarning = string.Format(
CultureInfo.InvariantCulture,
ParameterBinderStrings.UseOfDeprecatedParameterWarning,
parameter.Parameter.Name,
parameter.Parameter.ObsoleteAttribute.Message);
var warningRecord = new WarningRecord(ParameterBinderBase.FQIDParameterObsolete, obsoleteWarning);
BoundObsoleteParameterNames.Add(parameter.Parameter.Name);
ObsoleteParameterWarningList ??= new List<WarningRecord>();
ObsoleteParameterWarningList.Add(warningRecord);
}
}
return result;
}
/// <summary>
/// Binds the remaining arguments to an unbound ValueFromRemainingArguments parameter (Varargs)
/// </summary>
/// <exception cref="ParameterBindingException">
/// If there was an error binding the arguments to the parameters.
/// </exception>
private void HandleRemainingArguments()
{
if (UnboundArguments.Count > 0)
{
// Find the parameters that take the remaining args, if there are more
// than one and the parameter set has not been defined, this is an error
MergedCompiledCommandParameter varargsParameter = null;
foreach (MergedCompiledCommandParameter parameter in UnboundParameters)
{
ParameterSetSpecificMetadata parameterSetData = parameter.Parameter.GetParameterSetData(_currentParameterSetFlag);
if (parameterSetData == null)
{
continue;
}
// If the parameter takes the remaining arguments, bind them.
if (parameterSetData.ValueFromRemainingArguments)
{
if (varargsParameter != null)
{
ParameterBindingException bindingException =
new ParameterBindingException(
ErrorCategory.MetadataError,
this.Command.MyInvocation,
null,
parameter.Parameter.Name,
parameter.Parameter.Type,
null,
ParameterBinderStrings.AmbiguousParameterSet,
"AmbiguousParameterSet");
// Might be caused by the default parameter binding
if (!DefaultParameterBindingInUse)
{
throw bindingException;
}
else
{
ThrowElaboratedBindingException(bindingException);
}
}
varargsParameter = parameter;
}
}
if (varargsParameter != null)
{
using (ParameterBinderBase.bindingTracer.TraceScope(
"BIND REMAININGARGUMENTS cmd line args to param: [{0}]",
varargsParameter.Parameter.Name))
{
// Accumulate the unbound arguments in to an list and then bind it to the parameter
List<object> valueFromRemainingArguments = new List<object>();
foreach (CommandParameterInternal argument in UnboundArguments)
{
if (argument.ParameterNameSpecified)
{
Diagnostics.Assert(!string.IsNullOrEmpty(argument.ParameterText), "Don't add a null argument");
valueFromRemainingArguments.Add(argument.ParameterText);
}
if (argument.ArgumentSpecified)
{
object argumentValue = argument.ArgumentValue;
if (argumentValue != AutomationNull.Value && argumentValue != UnboundParameter.Value)
{
valueFromRemainingArguments.Add(argumentValue);
}
}
}
// If there are multiple arguments, it's not clear how best to represent the extent as the extent
// may be disjoint, as in 'echo a -verbose b', we have 'a' and 'b' in UnboundArguments.
var argumentAst = UnboundArguments.Count == 1 ? UnboundArguments[0].ArgumentAst : null;
var cpi = CommandParameterInternal.CreateParameterWithArgument(
/*parameterAst*/null, varargsParameter.Parameter.Name, "-" + varargsParameter.Parameter.Name + ":",
argumentAst, valueFromRemainingArguments, false);
// To make all of the following work similarly (the first is handled elsewhere, but second and third are
// handled here):
// Set-ClusterOwnerNode -Owners foo,bar
// Set-ClusterOwnerNode foo bar
// Set-ClusterOwnerNode foo,bar
// we unwrap our List, but only if there is a single argument which is a collection.
if (valueFromRemainingArguments.Count == 1 && LanguagePrimitives.IsObjectEnumerable(valueFromRemainingArguments[0]))
{
cpi.SetArgumentValue(UnboundArguments[0].ArgumentAst, valueFromRemainingArguments[0]);
}
try
{
BindParameter(cpi, varargsParameter, ParameterBindingFlags.ShouldCoerceType);
}
catch (ParameterBindingException pbex)
{
if (!DefaultParameterBindingInUse)
{
throw;
}
else
{
ThrowElaboratedBindingException(pbex);
}
}
UnboundArguments.Clear();
}
}
}
}
/// <summary>
/// Determines if the cmdlet supports dynamic parameters. If it does,
/// the dynamic parameter bindable object is retrieved and the unbound
/// arguments are bound to it.
/// </summary>
/// <param name="outgoingBindingException">
/// Returns the underlying parameter binding exception if any was generated.
/// </param>
/// <exception cref="MetadataException">
/// If there was an error compiling the parameter metadata.
/// </exception>
/// <exception cref="ParameterBindingException">
/// If there was an error binding the arguments to the parameters.
/// </exception>
private void HandleCommandLineDynamicParameters(out ParameterBindingException outgoingBindingException)
{
outgoingBindingException = null;
if (_commandMetadata.ImplementsDynamicParameters)
{
using (ParameterBinderBase.bindingTracer.TraceScope(
"BIND cmd line args to DYNAMIC parameters."))
{
s_tracer.WriteLine("The Cmdlet supports the dynamic parameter interface");
IDynamicParameters dynamicParameterCmdlet = this.Command as IDynamicParameters;
if (dynamicParameterCmdlet != null)
{
if (_dynamicParameterBinder == null)
{
s_tracer.WriteLine("Getting the bindable object from the Cmdlet");
// Now get the dynamic parameter bindable object.
object dynamicParamBindableObject;
try
{
dynamicParamBindableObject = dynamicParameterCmdlet.GetDynamicParameters();
}
catch (Exception e) // Catch-all OK, this is a third-party callout
{
if (e is ProviderInvocationException)
{
throw;
}
ParameterBindingException bindingException =
new ParameterBindingException(
e,
ErrorCategory.InvalidArgument,
this.Command.MyInvocation,
null,
null,
null,
null,
ParameterBinderStrings.GetDynamicParametersException,
"GetDynamicParametersException",
e.Message);
// This exception is caused because failure happens when retrieving the dynamic parameters,
// this is not caused by introducing the default parameter binding.
throw bindingException;
}
if (dynamicParamBindableObject != null)
{
ParameterBinderBase.bindingTracer.WriteLine(
"DYNAMIC parameter object: [{0}]",
dynamicParamBindableObject.GetType());
s_tracer.WriteLine("Creating a new parameter binder for the dynamic parameter object");
InternalParameterMetadata dynamicParameterMetadata;
RuntimeDefinedParameterDictionary runtimeParamDictionary = dynamicParamBindableObject as RuntimeDefinedParameterDictionary;
if (runtimeParamDictionary != null)
{
// Generate the type metadata for the runtime-defined parameters
dynamicParameterMetadata =
InternalParameterMetadata.Get(runtimeParamDictionary, true, true);
_dynamicParameterBinder =
new RuntimeDefinedParameterBinder(
runtimeParamDictionary,
this.Command,
this.CommandLineParameters);
}
else
{
// Generate the type metadata or retrieve it from the cache
dynamicParameterMetadata =
InternalParameterMetadata.Get(dynamicParamBindableObject.GetType(), Context, true);
// Create the parameter binder for the dynamic parameter object
_dynamicParameterBinder =
new ReflectionParameterBinder(
dynamicParamBindableObject,
this.Command,
this.CommandLineParameters);
}
// Now merge the metadata with other metadata for the command
var dynamicParams =
BindableParameters.AddMetadataForBinder(
dynamicParameterMetadata,
ParameterBinderAssociation.DynamicParameters);
foreach (var param in dynamicParams)
{
UnboundParameters.Add(param);
}
// Now set the parameter set flags for the new type metadata.
_commandMetadata.DefaultParameterSetFlag =
this.BindableParameters.GenerateParameterSetMappingFromMetadata(_commandMetadata.DefaultParameterSetName);
}
}
if (_dynamicParameterBinder == null)
{
s_tracer.WriteLine("No dynamic parameter object was returned from the Cmdlet");
return;
}
if (UnboundArguments.Count > 0)
{
using (ParameterBinderBase.bindingTracer.TraceScope(
"BIND NAMED args to DYNAMIC parameters"))
{
// Try to bind the unbound arguments as static parameters to the
// dynamic parameter object.
ReparseUnboundArguments();
UnboundArguments = BindNamedParameters(_currentParameterSetFlag, UnboundArguments);
}
using (ParameterBinderBase.bindingTracer.TraceScope(
"BIND POSITIONAL args to DYNAMIC parameters"))
{
UnboundArguments =
BindPositionalParameters(
UnboundArguments,
_currentParameterSetFlag,
_commandMetadata.DefaultParameterSetFlag,
out outgoingBindingException);
}
}
}
}
}
}
/// <summary>
/// This method determines if the unbound mandatory parameters take pipeline input or
/// if we can use the default parameter set. If all the unbound mandatory parameters
/// take pipeline input and the default parameter set is valid, then the default parameter
/// set is set as the current parameter set and processing can continue. If there are
/// more than one valid parameter sets and the unbound mandatory parameters are not
/// consistent across parameter sets or there is no default parameter set then a
/// ParameterBindingException is thrown with an errorId of AmbiguousParameterSet.
/// </summary>
/// <param name="validParameterSetCount">
/// The number of valid parameter sets.
/// </param>
/// <param name="isPipelineInputExpected">
/// True if the pipeline is open to receive input.
/// </param>
/// <exception cref="ParameterBindingException">
/// If there are multiple valid parameter sets and the missing mandatory parameters are
/// not consistent across parameter sets, or there is no default parameter set.
/// </exception>
[SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmaintainableCode", Justification = "Consider Simplifying it.")]
private Collection<MergedCompiledCommandParameter> GetMissingMandatoryParameters(
int validParameterSetCount,
bool isPipelineInputExpected)
{
Collection<MergedCompiledCommandParameter> result = new Collection<MergedCompiledCommandParameter>();
uint defaultParameterSet = _commandMetadata.DefaultParameterSetFlag;
uint commandMandatorySets = 0;
Dictionary<uint, ParameterSetPromptingData> promptingData = new Dictionary<uint, ParameterSetPromptingData>();
bool missingAMandatoryParameter = false;
bool missingAMandatoryParameterInAllSet = false;
// See if any of the unbound parameters are mandatory
foreach (MergedCompiledCommandParameter parameter in UnboundParameters)
{
// If a parameter is never mandatory, we can skip lots of work here.
if (!parameter.Parameter.IsMandatoryInSomeParameterSet)
{
continue;
}
var matchingParameterSetMetadata = parameter.Parameter.GetMatchingParameterSetData(_currentParameterSetFlag);
uint parameterMandatorySets = 0;
bool thisParameterMissing = false;
foreach (ParameterSetSpecificMetadata parameterSetMetadata in matchingParameterSetMetadata)
{
uint newMandatoryParameterSetFlag = NewParameterSetPromptingData(promptingData, parameter, parameterSetMetadata, defaultParameterSet, isPipelineInputExpected);
if (newMandatoryParameterSetFlag != 0)
{
missingAMandatoryParameter = true;
thisParameterMissing = true;
if (newMandatoryParameterSetFlag != uint.MaxValue)
{
parameterMandatorySets |= (_currentParameterSetFlag & newMandatoryParameterSetFlag);
commandMandatorySets |= (_currentParameterSetFlag & parameterMandatorySets);
}
else
{
missingAMandatoryParameterInAllSet = true;
}
}
}
// We are not expecting pipeline input
if (!isPipelineInputExpected)
{
// The parameter is mandatory so we need to prompt for it
if (thisParameterMissing)
{
result.Add(parameter);
continue;
}
// The parameter was not mandatory in any parameter set
}
}
if (missingAMandatoryParameter && isPipelineInputExpected)
{
if (commandMandatorySets == 0)
{
commandMandatorySets = _currentParameterSetFlag;
}
if (missingAMandatoryParameterInAllSet)
{
uint availableParameterSetFlags = this.BindableParameters.AllParameterSetFlags;
if (availableParameterSetFlags == 0)
{
availableParameterSetFlags = uint.MaxValue;
}
commandMandatorySets = (_currentParameterSetFlag & availableParameterSetFlags);
}
// First we need to see if there are multiple valid parameter sets, and if one is
// the default parameter set, and it is not missing any mandatory parameters, then
// use the default parameter set.
if (validParameterSetCount > 1 &&
defaultParameterSet != 0 &&
(defaultParameterSet & commandMandatorySets) == 0 &&
(defaultParameterSet & _currentParameterSetFlag) != 0)
{
// If no other set takes pipeline input, then latch on to the default set
uint setThatTakesPipelineInput = 0;
foreach (ParameterSetPromptingData promptingSetData in promptingData.Values)
{
if ((promptingSetData.ParameterSet & _currentParameterSetFlag) != 0 &&
(promptingSetData.ParameterSet & defaultParameterSet) == 0 &&
!promptingSetData.IsAllSet)
{
if (promptingSetData.PipelineableMandatoryParameters.Count > 0)
{
setThatTakesPipelineInput = promptingSetData.ParameterSet;
break;
}
}
}
if (setThatTakesPipelineInput == 0)
{
// Old algorithm starts
// // latch on to the default parameter set
// commandMandatorySets = defaultParameterSet;
// _currentParameterSetFlag = defaultParameterSet;
// Command.SetParameterSetName(CurrentParameterSetName);
// Old algorithm ends
// At this point, we have the following information:
// 1. There are unbound mandatory parameter(s)
// 2. No unbound mandatory parameter is in AllSet
// 3. All unbound mandatory parameters don't take pipeline input
// 4. Default parameter set is valid
// 5. Default parameter set doesn't contain unbound mandatory parameters
//
// We ignore those parameter sets that contain unbound mandatory parameters, but leave
// all other parameter sets remain valid. The other parameter sets contains the default
// parameter set and have one characteristic: NONE of them contain unbound mandatory parameters
//
// Comparing to the old algorithm, we keep more possible parameter sets here, but
// we need to prioritize the default parameter set for pipeline binding, so as NOT to
// make breaking changes. This is to handle the following scenario:
// Old Algorithm New Algorithm (without prioritizing default) New Algorithm (with prioritizing default)
// Remaining Parameter Sets A(default) A(default), B A(default), B
// Pipeline parameter P1(string) A: P1(string); B: P2(System.DateTime) A: P1(string); B: P2(System.DateTime)
// Pipeline parameter type P1:By Value P1:By Value; P2:By Value P1:By Value; P2:By Value
// Pipeline input $a (System.DateTime) $a (System.DateTime) $a (System.DateTime)
// Pipeline binding result P1 --> $a.ToString() P2 --> $a P1 --> $a.ToString()
// Pipeline binding type ByValueWithCoercion ByValueWithoutCoercion ByValueWithCoercion
commandMandatorySets = _currentParameterSetFlag & (~commandMandatorySets);
_currentParameterSetFlag = commandMandatorySets;
if (_currentParameterSetFlag == defaultParameterSet)
Command.SetParameterSetName(CurrentParameterSetName);
else
_parameterSetToBePrioritizedInPipelineBinding = defaultParameterSet;
}
}
// We need to analyze the prompting data that was gathered to determine what parameter
// set to use, which parameters need prompting for, and which parameters take pipeline input.
int commandMandatorySetsCount = ValidParameterSetCount(commandMandatorySets);
if (commandMandatorySetsCount == 0)
{
ThrowAmbiguousParameterSetException(_currentParameterSetFlag, BindableParameters);
}
else if (commandMandatorySetsCount == 1)
{
// Since we have only one valid parameter set, add all
foreach (ParameterSetPromptingData promptingSetData in promptingData.Values)
{
if ((promptingSetData.ParameterSet & commandMandatorySets) != 0 ||
promptingSetData.IsAllSet)
{
foreach (MergedCompiledCommandParameter mandatoryParameter in promptingSetData.NonpipelineableMandatoryParameters.Keys)
{
result.Add(mandatoryParameter);
}
}
}
}
else if (_parameterSetToBePrioritizedInPipelineBinding == 0)
{
// We have more than one valid parameter set. Need to figure out which one to
// use.
// First we need to process the default parameter set if it can fill its parameters
// from the pipeline.
bool latchOnToDefault = false;
if (defaultParameterSet != 0 && (commandMandatorySets & defaultParameterSet) != 0)
{
// Determine if another set could be satisfied by pipeline input - that is, it
// has mandatory pipeline input parameters but no mandatory command-line only parameters.
bool anotherSetTakesPipelineInput = false;
foreach (ParameterSetPromptingData paramPromptingData in promptingData.Values)
{
if (!paramPromptingData.IsAllSet &&
!paramPromptingData.IsDefaultSet &&
paramPromptingData.PipelineableMandatoryParameters.Count > 0 &&
paramPromptingData.NonpipelineableMandatoryParameters.Count == 0)
{
anotherSetTakesPipelineInput = true;
break;
}
}
// Determine if another set takes pipeline input by property name
bool anotherSetTakesPipelineInputByPropertyName = false;
foreach (ParameterSetPromptingData paramPromptingData in promptingData.Values)
{
if (!paramPromptingData.IsAllSet &&
!paramPromptingData.IsDefaultSet &&
paramPromptingData.PipelineableMandatoryByPropertyNameParameters.Count > 0)
{
anotherSetTakesPipelineInputByPropertyName = true;
break;
}
}
// See if we should pick the default set if it can bind strongly to the incoming objects
ParameterSetPromptingData defaultSetPromptingData;
if (promptingData.TryGetValue(defaultParameterSet, out defaultSetPromptingData))
{
bool defaultSetTakesPipelineInput = defaultSetPromptingData.PipelineableMandatoryParameters.Count > 0;
bool defaultSetTakesPipelineInputByPropertyName = defaultSetPromptingData.PipelineableMandatoryByPropertyNameParameters.Count > 0;
if (defaultSetTakesPipelineInputByPropertyName && !anotherSetTakesPipelineInputByPropertyName)
{
latchOnToDefault = true;
}
else if (defaultSetTakesPipelineInput && !anotherSetTakesPipelineInput)
{
latchOnToDefault = true;
}
}
if (!latchOnToDefault)
{
// If only the all set takes pipeline input then latch on to the
// default set
if (!anotherSetTakesPipelineInput)
{
latchOnToDefault = true;
}
}
if (!latchOnToDefault)
{
// Need to see if there are nonpipelineable mandatory parameters in the
// all set.
ParameterSetPromptingData allSetPromptingData;
if (promptingData.TryGetValue(uint.MaxValue, out allSetPromptingData))
{
if (allSetPromptingData.NonpipelineableMandatoryParameters.Count > 0)
{
latchOnToDefault = true;
}
}
}
if (latchOnToDefault)
{
// latch on to the default parameter set
commandMandatorySets = defaultParameterSet;
_currentParameterSetFlag = defaultParameterSet;
Command.SetParameterSetName(CurrentParameterSetName);
// Add all missing mandatory parameters that don't take pipeline input
foreach (ParameterSetPromptingData promptingSetData in promptingData.Values)
{
if ((promptingSetData.ParameterSet & commandMandatorySets) != 0 ||
promptingSetData.IsAllSet)
{
foreach (MergedCompiledCommandParameter mandatoryParameter in promptingSetData.NonpipelineableMandatoryParameters.Keys)
{
result.Add(mandatoryParameter);
}
}
}
}
}
if (!latchOnToDefault)
{
// When we select a mandatory set to latch on, we should try to preserve other parameter sets that contain no mandatory parameters or contain only common mandatory parameters
// as much as possible, so as to support the binding for the following scenarios:
//
// (1) Scenario 1:
// Valid parameter sets when it comes to the mandatory checking: A, B
// Mandatory parameters in A, B:
// Set Nonpipelineable-Mandatory-InSet Pipelineable-Mandatory-InSet Common-Nonpipelineable-Mandatory Common-Pipelineable-Mandatory
// A N/A N/A N/A AllParam (of type DateTime)
// B N/A ParamB (of type TimeSpan) N/A AllParam (of type DateTime)
//
// Piped-in object: Get-Date
//
// (2) Scenario 2:
// Valid parameter sets when it comes to the mandatory checking: A, B, C, Default
// Mandatory parameters in A, B, C and Default:
// Set Nonpipelineable-Mandatory-InSet Pipelineable-Mandatory-InSet Common-Nonpipelineable-Mandatory Common-Pipelineable-Mandatory
// A N/A N/A N/A AllParam (of type DateTime)
// B N/A ParamB (of type TimeSpan) N/A AllParam (of type DateTime)
// C N/A N/A N/A AllParam (of type DateTime)
// Default N/A N/A N/A AllParam (of type DateTime)
//
// Piped-in object: Get-Date
//
// Before the fix, the mandatory checking will resolve the parameter set to be B in both scenario 1 and 2, which will fail in the subsequent pipeline binding.
// After the fix, the parameter set "A" in the scenario 1 and the set "A", "C", "Default" in the scenario 2 will be preserved, and the subsequent pipeline binding will succeed.
//
// (3) Scenario 3:
// Valid parameter sets when it comes to the mandatory checking: A, B, C
// Mandatory parameters in A, B and C:
// Set Nonpipelineable-Mandatory-InSet Pipelineable-Mandatory-InSet Pipelineable-Nonmandatory-InSet Common-Nonpipelineable-Mandatory Common-Pipelineable-Mandatory Common-Pipelineable-Nonmandatory
// A N/A ParamA (of type TimeSpan) N/A N/A N/A N/A
// B ParamB-1 N/A ParamB-2 (of type string[]) N/A N/A N/A
// C N/A N/A ParamC (of type DateTime) N/A N/A N/A
//
// (4) Scenario 4:
// Valid parameter sets when it comes to the mandatory checking: A, B, C, Default
// Mandatory parameters in A, B, C and Default:
// Set Nonpipelineable-Mandatory-InSet Pipelineable-Mandatory-InSet Pipelineable-Nonmandatory-InSet Common-Nonpipelineable-Mandatory Common-Pipelineable-Mandatory Common-Pipelineable-Nonmandatory
// A N/A ParamA (of type TimeSpan) N/A N/A N/A AllParam (of type DateTime)
// B ParamB-1 N/A ParamB-2 (of type string[]) N/A N/A AllParam (of type DateTime)
// C N/A N/A N/A N/A N/A AllParam (of type DateTime)
// Default N/A N/A N/A N/A N/A AllParam (of type DateTime)
//
// Piped-in object: Get-Date
//
// Before the fix, the mandatory checking will resolve the parameter set to be A in both scenario 3 and 4, which will fail in the subsequent pipeline binding.
// After the fix, the parameter set "C" in the scenario 1 and the set "C" and "Default" in the scenario 2 will be preserved, and the subsequent pipeline binding will succeed.
//
// Examples:
// (1) Scenario 1
// Function Get-Cmdlet
// {
// [CmdletBinding()]
// param(
// [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
// [System.DateTime]
// $Date,
// [Parameter(ParameterSetName="computer")]
// [Parameter(ParameterSetName="session")]
// $ComputerName,
// [Parameter(ParameterSetName="session", Mandatory=$true, ValueFromPipeline=$true)]
// [System.TimeSpan]
// $TimeSpan
// )
//
// Process
// {
// Write-Output $PsCmdlet.ParameterSetName
// }
// }
//
// PS:\> Get-Date | Get-Cmdlet
// PS:\> computer
//
// (2) Scenario 2
//
// Function Get-Cmdlet
// {
// [CmdletBinding(DefaultParameterSetName="computer")]
// param(
// [Parameter(ParameterSetName="new")]
// $NewName,
// [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
// [System.DateTime]
// $Date,
// [Parameter(ParameterSetName="computer")]
// [Parameter(ParameterSetName="session")]
// $ComputerName,
// [Parameter(ParameterSetName="session", Mandatory=$true, ValueFromPipeline=$true)]
// [System.TimeSpan]
// $TimeSpan
// )
//
// Process
// {
// Write-Output $PsCmdlet.ParameterSetName
// }
// }
//
// PS:\> Get-Date | Get-Cmdlet
// PS:\> computer
//
// (3) Scenario 3
//
// Function Get-Cmdlet
// {
// [CmdletBinding()]
// param(
// [Parameter(ParameterSetName="network", Mandatory=$true, ValueFromPipeline=$true)]
// [TimeSpan]
// $network,
//
// [Parameter(ParameterSetName="computer", ValueFromPipelineByPropertyName=$true)]
// [string[]]
// $ComputerName,
//
// [Parameter(ParameterSetName="computer", Mandatory=$true)]
// [switch]
// $DisableComputer,
//
// [Parameter(ParameterSetName="session", ValueFromPipeline=$true)]
// [DateTime]
// $Date
// )
//
// Process
// {
// Write-Output $PsCmdlet.ParameterSetName
// }
// }
//
// PS:\> Get-Date | Get-Cmdlet
// PS:\> session
//
// (4) Scenario 4
//
// Function Get-Cmdlet
// {
// [CmdletBinding(DefaultParameterSetName="server")]
// param(
// [Parameter(ParameterSetName="network", Mandatory=$true, ValueFromPipeline=$true)]
// [TimeSpan]
// $network,
//
// [Parameter(ParameterSetName="computer", ValueFromPipelineByPropertyName=$true)]
// [string[]]
// $ComputerName,
//
// [Parameter(ParameterSetName="computer", Mandatory=$true)]
// [switch]
// $DisableComputer,
//
// [Parameter(ParameterSetName="session")]
// [Parameter(ParameterSetName="server")]
// [string]
// $Param,
//
// [Parameter(ValueFromPipeline=$true)]
// [DateTime]
// $Date
// )
// Process
// {
// Write-Output $PsCmdlet.ParameterSetName
// }
// }
//
// PS:\> Get-Date | Get-Cmdlet
// PS:\> server
//
uint setThatTakesPipelineInputByValue = 0;
uint setThatTakesPipelineInputByPropertyName = 0;
// Find the single set that takes pipeline input by value
bool foundSetThatTakesPipelineInputByValue = false;
bool foundMultipleSetsThatTakesPipelineInputByValue = false;
foreach (ParameterSetPromptingData promptingSetData in promptingData.Values)
{
if ((promptingSetData.ParameterSet & commandMandatorySets) != 0 &&
!promptingSetData.IsAllSet)
{
if (promptingSetData.PipelineableMandatoryByValueParameters.Count > 0)
{
if (foundSetThatTakesPipelineInputByValue)
{
foundMultipleSetsThatTakesPipelineInputByValue = true;
setThatTakesPipelineInputByValue = 0;
break;
}
setThatTakesPipelineInputByValue = promptingSetData.ParameterSet;
foundSetThatTakesPipelineInputByValue = true;
}
}
}
// Find the single set that takes pipeline input by property name
bool foundSetThatTakesPipelineInputByPropertyName = false;
bool foundMultipleSetsThatTakesPipelineInputByPropertyName = false;
foreach (ParameterSetPromptingData promptingSetData in promptingData.Values)
{
if ((promptingSetData.ParameterSet & commandMandatorySets) != 0 &&
!promptingSetData.IsAllSet)
{
if (promptingSetData.PipelineableMandatoryByPropertyNameParameters.Count > 0)
{
if (foundSetThatTakesPipelineInputByPropertyName)
{
foundMultipleSetsThatTakesPipelineInputByPropertyName = true;
setThatTakesPipelineInputByPropertyName = 0;
break;
}
setThatTakesPipelineInputByPropertyName = promptingSetData.ParameterSet;
foundSetThatTakesPipelineInputByPropertyName = true;
}
}
}
// If we have one or the other, we can latch onto that set without difficulty
uint uniqueSetThatTakesPipelineInput = 0;
if (foundSetThatTakesPipelineInputByValue && foundSetThatTakesPipelineInputByPropertyName &&
(setThatTakesPipelineInputByValue == setThatTakesPipelineInputByPropertyName))
{
uniqueSetThatTakesPipelineInput = setThatTakesPipelineInputByValue;
}
if (foundSetThatTakesPipelineInputByValue ^ foundSetThatTakesPipelineInputByPropertyName)
{
uniqueSetThatTakesPipelineInput = foundSetThatTakesPipelineInputByValue ?
setThatTakesPipelineInputByValue : setThatTakesPipelineInputByPropertyName;
}
if (uniqueSetThatTakesPipelineInput != 0)
{
// latch on to the set that takes pipeline input
commandMandatorySets = uniqueSetThatTakesPipelineInput;
uint otherMandatorySetsToBeIgnored = 0;
bool chosenMandatorySetContainsNonpipelineableMandatoryParameters = false;
// Add all missing mandatory parameters that don't take pipeline input
foreach (ParameterSetPromptingData promptingSetData in promptingData.Values)
{
if ((promptingSetData.ParameterSet & commandMandatorySets) != 0 ||
promptingSetData.IsAllSet)
{
if (!promptingSetData.IsAllSet)
{
chosenMandatorySetContainsNonpipelineableMandatoryParameters =
promptingSetData.NonpipelineableMandatoryParameters.Count > 0;
}
foreach (MergedCompiledCommandParameter mandatoryParameter in promptingSetData.NonpipelineableMandatoryParameters.Keys)
{
result.Add(mandatoryParameter);
}
}
else
{
otherMandatorySetsToBeIgnored |= promptingSetData.ParameterSet;
}
}
// Preserve potential parameter sets as much as possible
PreservePotentialParameterSets(uniqueSetThatTakesPipelineInput,
otherMandatorySetsToBeIgnored,
chosenMandatorySetContainsNonpipelineableMandatoryParameters);
}
else
{
// Now if any valid parameter sets have nonpipelineable mandatory parameters we have
// an error
bool foundMissingParameters = false;
uint setsThatContainNonpipelineableMandatoryParameter = 0;
foreach (ParameterSetPromptingData promptingSetData in promptingData.Values)
{
if ((promptingSetData.ParameterSet & commandMandatorySets) != 0 ||
promptingSetData.IsAllSet)
{
if (promptingSetData.NonpipelineableMandatoryParameters.Count > 0)
{
foundMissingParameters = true;
if (!promptingSetData.IsAllSet)
{
setsThatContainNonpipelineableMandatoryParameter |= promptingSetData.ParameterSet;
}
}
}
}
if (foundMissingParameters)
{
// As a last-ditch effort, bind to the set that takes pipeline input by value
if (setThatTakesPipelineInputByValue != 0)
{
// latch on to the set that takes pipeline input
commandMandatorySets = setThatTakesPipelineInputByValue;
uint otherMandatorySetsToBeIgnored = 0;
bool chosenMandatorySetContainsNonpipelineableMandatoryParameters = false;
// Add all missing mandatory parameters that don't take pipeline input
foreach (ParameterSetPromptingData promptingSetData in promptingData.Values)
{
if ((promptingSetData.ParameterSet & commandMandatorySets) != 0 ||
promptingSetData.IsAllSet)
{
if (!promptingSetData.IsAllSet)
{
chosenMandatorySetContainsNonpipelineableMandatoryParameters =
promptingSetData.NonpipelineableMandatoryParameters.Count > 0;
}
foreach (MergedCompiledCommandParameter mandatoryParameter in promptingSetData.NonpipelineableMandatoryParameters.Keys)
{
result.Add(mandatoryParameter);
}
}
else
{
otherMandatorySetsToBeIgnored |= promptingSetData.ParameterSet;
}
}
// Preserve potential parameter sets as much as possible
PreservePotentialParameterSets(setThatTakesPipelineInputByValue,
otherMandatorySetsToBeIgnored,
chosenMandatorySetContainsNonpipelineableMandatoryParameters);
}
else
{
if ((!foundMultipleSetsThatTakesPipelineInputByValue) &&
(!foundMultipleSetsThatTakesPipelineInputByPropertyName))
{
ThrowAmbiguousParameterSetException(_currentParameterSetFlag, BindableParameters);
}
// Remove the data set that contains non-pipelineable mandatory parameters, since we are not
// prompting for them and they will not be bound later.
// If no data set left, throw ambiguous parameter set exception
if (setsThatContainNonpipelineableMandatoryParameter != 0)
{
IgnoreOtherMandatoryParameterSets(setsThatContainNonpipelineableMandatoryParameter);
if (_currentParameterSetFlag == 0)
{
ThrowAmbiguousParameterSetException(_currentParameterSetFlag, BindableParameters);
}
if (ValidParameterSetCount(_currentParameterSetFlag) == 1)
{
Command.SetParameterSetName(CurrentParameterSetName);
}
}
}
}
}
}
}
}
return result;
}
/// <summary>
/// Preserve potential parameter sets as much as possible.
/// </summary>
/// <param name="chosenMandatorySet">The mandatory set we choose to latch on.</param>
/// <param name="otherMandatorySetsToBeIgnored">Other mandatory parameter sets to be ignored.</param>
/// <param name="chosenSetContainsNonpipelineableMandatoryParameters">Indicate if the chosen mandatory set contains any non-pipelineable mandatory parameters.</param>
private void PreservePotentialParameterSets(uint chosenMandatorySet, uint otherMandatorySetsToBeIgnored, bool chosenSetContainsNonpipelineableMandatoryParameters)
{
// If the chosen set contains nonpipelineable mandatory parameters, then we set it as the only valid parameter set since we will prompt for those mandatory parameters
if (chosenSetContainsNonpipelineableMandatoryParameters)
{
_currentParameterSetFlag = chosenMandatorySet;
Command.SetParameterSetName(CurrentParameterSetName);
}
else
{
// Otherwise, we additionally preserve those valid parameter sets that contain no mandatory parameter, or contain only the common mandatory parameters
IgnoreOtherMandatoryParameterSets(otherMandatorySetsToBeIgnored);
Command.SetParameterSetName(CurrentParameterSetName);
if (_currentParameterSetFlag != chosenMandatorySet)
{
_parameterSetToBePrioritizedInPipelineBinding = chosenMandatorySet;
}
}
}
/// <summary>
/// Update _currentParameterSetFlag to ignore the specified mandatory sets.
/// </summary>
/// <remarks>
/// This method is used only when we try to preserve parameter sets during the mandatory parameter checking.
/// In cases where this method is used, there must be at least one parameter set declared.
/// </remarks>
/// <param name="otherMandatorySetsToBeIgnored">The mandatory parameter sets to be ignored.</param>
private void IgnoreOtherMandatoryParameterSets(uint otherMandatorySetsToBeIgnored)
{
if (otherMandatorySetsToBeIgnored == 0)
return;
if (_currentParameterSetFlag == uint.MaxValue)
{
// We cannot update the _currentParameterSetFlag to remove some parameter sets directly when it's AllSet as that will get it to an incorrect state.
uint availableParameterSets = this.BindableParameters.AllParameterSetFlags;
Diagnostics.Assert(availableParameterSets != 0, "At least one parameter set must be declared");
_currentParameterSetFlag = availableParameterSets & (~otherMandatorySetsToBeIgnored);
}
else
{
_currentParameterSetFlag &= (~otherMandatorySetsToBeIgnored);
}
}
private static uint NewParameterSetPromptingData(
Dictionary<uint, ParameterSetPromptingData> promptingData,
MergedCompiledCommandParameter parameter,
ParameterSetSpecificMetadata parameterSetMetadata,
uint defaultParameterSet,
bool pipelineInputExpected)
{
uint parameterMandatorySets = 0;
uint parameterSetFlag = parameterSetMetadata.ParameterSetFlag;
if (parameterSetFlag == 0)
{
parameterSetFlag = uint.MaxValue;
}
bool isDefaultSet = (defaultParameterSet != 0) && ((defaultParameterSet & parameterSetFlag) != 0);
bool isMandatory = false;
if (parameterSetMetadata.IsMandatory)
{
parameterMandatorySets |= parameterSetFlag;
isMandatory = true;
}
bool isPipelineable = false;
if (pipelineInputExpected)
{
if (parameterSetMetadata.ValueFromPipeline || parameterSetMetadata.ValueFromPipelineByPropertyName)
{
isPipelineable = true;
}
}
if (isMandatory)
{
ParameterSetPromptingData promptingDataForSet;
if (!promptingData.TryGetValue(parameterSetFlag, out promptingDataForSet))
{
promptingDataForSet = new ParameterSetPromptingData(parameterSetFlag, isDefaultSet);
promptingData.Add(parameterSetFlag, promptingDataForSet);
}
if (isPipelineable)
{
promptingDataForSet.PipelineableMandatoryParameters[parameter] = parameterSetMetadata;
if (parameterSetMetadata.ValueFromPipeline)
{
promptingDataForSet.PipelineableMandatoryByValueParameters[parameter] = parameterSetMetadata;
}
if (parameterSetMetadata.ValueFromPipelineByPropertyName)
{
promptingDataForSet.PipelineableMandatoryByPropertyNameParameters[parameter] = parameterSetMetadata;
}
}
else
{
promptingDataForSet.NonpipelineableMandatoryParameters[parameter] = parameterSetMetadata;
}
}
return parameterMandatorySets;
}
/// <summary>
/// Ensures that only one parameter set is valid or throws an appropriate exception.
/// </summary>
/// <param name="prePipelineInput">
/// If true, it is acceptable to have multiple valid parameter sets as long as one
/// of those parameter sets take pipeline input.
/// </param>
/// <param name="setDefault">
/// If true, the default parameter set will be selected if there is more than
/// one valid parameter set and one is the default set.
/// If false, the count of valid parameter sets will be returned but no error
/// will occur and the default parameter set will not be used.
/// </param>
/// <returns>
/// The number of valid parameter sets.
/// </returns>
/// <exception cref="ParameterBindingException">
/// If the more than one or zero parameter sets were resolved from the named
/// parameters.
/// </exception>
private int ValidateParameterSets(bool prePipelineInput, bool setDefault)
{
// Compute how many parameter sets are still valid
int validParameterSetCount = ValidParameterSetCount(_currentParameterSetFlag);
if (validParameterSetCount == 0 && _currentParameterSetFlag != uint.MaxValue)
{
ThrowAmbiguousParameterSetException(_currentParameterSetFlag, BindableParameters);
}
else if (validParameterSetCount > 1)
{
uint defaultParameterSetFlag = _commandMetadata.DefaultParameterSetFlag;
bool hasDefaultSetDefined = defaultParameterSetFlag != 0;
bool validSetIsAllSet = _currentParameterSetFlag == uint.MaxValue;
bool validSetIsDefault = _currentParameterSetFlag == defaultParameterSetFlag;
// If no default parameter set is defined and the valid set is the "all" set
// then use the all set.
if (validSetIsAllSet && !hasDefaultSetDefined)
{
// The current parameter set flags are valid.
// Note: this is the same as having a single valid parameter set flag.
validParameterSetCount = 1;
}
// If the valid parameter set is the default parameter set, or if the default
// parameter set has been defined and one of the valid parameter sets is
// the default parameter set, then use the default parameter set.
else if (!prePipelineInput &&
validSetIsDefault ||
(hasDefaultSetDefined && (_currentParameterSetFlag & defaultParameterSetFlag) != 0))
{
// NTRAID#Windows Out Of Band Releases-2006/02/14-928660-JonN
// Set currentParameterSetName regardless of setDefault
string currentParameterSetName = BindableParameters.GetParameterSetName(defaultParameterSetFlag);
Command.SetParameterSetName(currentParameterSetName);
if (setDefault)
{
_currentParameterSetFlag = _commandMetadata.DefaultParameterSetFlag;
validParameterSetCount = 1;
}
}
// There are multiple valid parameter sets but at least one parameter set takes
// pipeline input
else if (prePipelineInput &&
AtLeastOneUnboundValidParameterSetTakesPipelineInput(_currentParameterSetFlag))
{
// We haven't fixated on a valid parameter set yet, but will wait for pipeline input to
// determine which parameter set to use.
}
else
{
int resolvedParameterSetCount = ResolveParameterSetAmbiguityBasedOnMandatoryParameters();
if (resolvedParameterSetCount != 1)
{
ThrowAmbiguousParameterSetException(_currentParameterSetFlag, BindableParameters);
}
validParameterSetCount = resolvedParameterSetCount;
}
}
else // validParameterSetCount == 1
{
// If the valid parameter set is the "all" set, and a default set was defined,
// then set the current parameter set to the default set.
if (_currentParameterSetFlag == uint.MaxValue)
{
// Since this is the "all" set, default the parameter set count to the
// number of parameter sets that were defined for the cmdlet or 1 if
// none were defined.
validParameterSetCount =
(this.BindableParameters.ParameterSetCount > 0) ?
this.BindableParameters.ParameterSetCount : 1;
if (prePipelineInput &&
AtLeastOneUnboundValidParameterSetTakesPipelineInput(_currentParameterSetFlag))
{
// Don't fixate on the default parameter set yet. Wait until after
// we have processed pipeline input.
}
else if (_commandMetadata.DefaultParameterSetFlag != 0)
{
if (setDefault)
{
_currentParameterSetFlag = _commandMetadata.DefaultParameterSetFlag;
validParameterSetCount = 1;
}
}
// NTRAID#Windows Out Of Band Releases-2005/11/07-923917-JonN
else if (validParameterSetCount > 1)
{
int resolvedParameterSetCount = ResolveParameterSetAmbiguityBasedOnMandatoryParameters();
if (resolvedParameterSetCount != 1)
{
ThrowAmbiguousParameterSetException(_currentParameterSetFlag, BindableParameters);
}
validParameterSetCount = resolvedParameterSetCount;
}
}
Command.SetParameterSetName(CurrentParameterSetName);
}
return validParameterSetCount;
}
private int ResolveParameterSetAmbiguityBasedOnMandatoryParameters()
{
return ResolveParameterSetAmbiguityBasedOnMandatoryParameters(this.BoundParameters, this.UnboundParameters, this.BindableParameters, ref _currentParameterSetFlag, Command);
}
internal static int ResolveParameterSetAmbiguityBasedOnMandatoryParameters(
Dictionary<string, MergedCompiledCommandParameter> boundParameters,
ICollection<MergedCompiledCommandParameter> unboundParameters,
MergedCommandParameterMetadata bindableParameters,
ref uint _currentParameterSetFlag,
Cmdlet command
)
{
uint remainingParameterSetsWithNoMandatoryUnboundParameters = _currentParameterSetFlag;
IEnumerable<ParameterSetSpecificMetadata> allParameterSetMetadatas = boundParameters.Values
.Concat(unboundParameters)
.SelectMany(static p => p.Parameter.ParameterSetData.Values);
uint allParameterSetFlags = 0;
foreach (ParameterSetSpecificMetadata parameterSetMetadata in allParameterSetMetadatas)
{
allParameterSetFlags |= parameterSetMetadata.ParameterSetFlag;
}
remainingParameterSetsWithNoMandatoryUnboundParameters &= allParameterSetFlags;
Diagnostics.Assert(
ValidParameterSetCount(remainingParameterSetsWithNoMandatoryUnboundParameters) > 1,
"This method should only be called when there is an ambiguity wrt parameter sets");
IEnumerable<ParameterSetSpecificMetadata> parameterSetMetadatasForUnboundMandatoryParameters = unboundParameters
.SelectMany(static p => p.Parameter.ParameterSetData.Values)
.Where(static p => p.IsMandatory);
foreach (ParameterSetSpecificMetadata parameterSetMetadata in parameterSetMetadatasForUnboundMandatoryParameters)
{
remainingParameterSetsWithNoMandatoryUnboundParameters &= (~parameterSetMetadata.ParameterSetFlag);
}
int finalParameterSetCount = ValidParameterSetCount(remainingParameterSetsWithNoMandatoryUnboundParameters);
if (finalParameterSetCount == 1)
{
_currentParameterSetFlag = remainingParameterSetsWithNoMandatoryUnboundParameters;
if (command != null)
{
string currentParameterSetName = bindableParameters.GetParameterSetName(_currentParameterSetFlag);
command.SetParameterSetName(currentParameterSetName);
}
return finalParameterSetCount;
}
return -1;
}
private void ThrowAmbiguousParameterSetException(uint parameterSetFlags, MergedCommandParameterMetadata bindableParameters)
{
ParameterBindingException bindingException =
new ParameterBindingException(
ErrorCategory.InvalidArgument,
this.Command.MyInvocation,
null,
null,
null,
null,
ParameterBinderStrings.AmbiguousParameterSet,
"AmbiguousParameterSet");
// Trace the parameter sets still active
uint currentParameterSet = 1;
while (parameterSetFlags != 0)
{
uint currentParameterSetActive = parameterSetFlags & 0x1;
if (currentParameterSetActive == 1)
{
string parameterSetName = bindableParameters.GetParameterSetName(currentParameterSet);
if (!string.IsNullOrEmpty(parameterSetName))
{
ParameterBinderBase.bindingTracer.WriteLine("Remaining valid parameter set: {0}", parameterSetName);
}
}
parameterSetFlags >>= 1;
currentParameterSet <<= 1;
}
if (!DefaultParameterBindingInUse)
{
throw bindingException;
}
else
{
ThrowElaboratedBindingException(bindingException);
}
}
/// <summary>
/// Determines if there are any unbound parameters that take pipeline input
/// for the specified parameter sets.
/// </summary>
/// <param name="validParameterSetFlags">
/// The parameter sets that should be checked for each unbound parameter to see
/// if it accepts pipeline input.
/// </param>
/// <returns>
/// True if there is at least one parameter that takes pipeline input for the
/// specified parameter sets, or false otherwise.
/// </returns>
private bool AtLeastOneUnboundValidParameterSetTakesPipelineInput(uint validParameterSetFlags)
{
bool result = false;
// Loop through all the unbound parameters to see if there are any
// that take pipeline input for the specified parameter sets.
foreach (MergedCompiledCommandParameter parameter in UnboundParameters)
{
if (parameter.Parameter.DoesParameterSetTakePipelineInput(validParameterSetFlags))
{
result = true;
break;
}
}
return result;
}
/// <summary>
/// Checks for unbound mandatory parameters. If any are found, an exception is thrown.
/// </summary>
/// <param name="missingMandatoryParameters">
/// Returns the missing mandatory parameters, if any.
/// </param>
/// <returns>
/// True if there are no unbound mandatory parameters. False if there are unbound mandatory parameters.
/// </returns>
internal bool HandleUnboundMandatoryParameters(out Collection<MergedCompiledCommandParameter> missingMandatoryParameters)
{
return HandleUnboundMandatoryParameters(
ValidParameterSetCount(_currentParameterSetFlag),
false,
false,
false,
out missingMandatoryParameters);
}
/// <summary>
/// Checks for unbound mandatory parameters. If any are found and promptForMandatory is true,
/// the user will be prompted for the missing mandatory parameters.
/// </summary>
/// <param name="validParameterSetCount">
/// The number of valid parameter sets.
/// </param>
/// <param name="processMissingMandatory">
/// If true, unbound mandatory parameters will be processed via user prompting (if allowed by promptForMandatory).
/// If false, unbound mandatory parameters will cause false to be returned.
/// </param>
/// <param name="promptForMandatory">
/// If true, unbound mandatory parameters will cause the user to be prompted. If false, unbound
/// mandatory parameters will cause an exception to be thrown.
/// </param>
/// <param name="isPipelineInputExpected">
/// If true, then only parameters that don't take pipeline input will be prompted for.
/// If false, any mandatory parameter that has not been specified will be prompted for.
/// </param>
/// <param name="missingMandatoryParameters">
/// Returns the missing mandatory parameters, if any.
/// </param>
/// <returns>
/// True if there are no unbound mandatory parameters. False if there are unbound mandatory parameters
/// and promptForMandatory if false.
/// </returns>
/// <exception cref="ParameterBindingException">
/// If prompting didn't result in a value for the parameter (only when <paramref name="promptForMandatory"/> is true.)
/// </exception>
internal bool HandleUnboundMandatoryParameters(
int validParameterSetCount,
bool processMissingMandatory,
bool promptForMandatory,
bool isPipelineInputExpected,
out Collection<MergedCompiledCommandParameter> missingMandatoryParameters)
{
bool result = true;
missingMandatoryParameters = GetMissingMandatoryParameters(validParameterSetCount, isPipelineInputExpected);
if (missingMandatoryParameters.Count > 0)
{
if (processMissingMandatory)
{
// If the host interface wasn't specified or we were instructed not to prmopt, then throw
// an exception instead
if ((Context.EngineHostInterface == null) || (!promptForMandatory))
{
Diagnostics.Assert(
Context.EngineHostInterface != null,
"The EngineHostInterface should never be null");
ParameterBinderBase.bindingTracer.WriteLine(
"ERROR: host does not support prompting for missing mandatory parameters");
string missingParameters = BuildMissingParamsString(missingMandatoryParameters);
ParameterBindingException bindingException =
new ParameterBindingException(
ErrorCategory.InvalidArgument,
this.Command.MyInvocation,
null,
missingParameters,
null,
null,
ParameterBinderStrings.MissingMandatoryParameter,
"MissingMandatoryParameter");
throw bindingException;
}
// Create a collection to store the prompt descriptions of unbound mandatory parameters
Collection<FieldDescription> fieldDescriptionList = CreatePromptDataStructures(missingMandatoryParameters);
Dictionary<string, PSObject> parameters =
PromptForMissingMandatoryParameters(
fieldDescriptionList,
missingMandatoryParameters);
using (ParameterBinderBase.bindingTracer.TraceScope(
"BIND PROMPTED mandatory parameter args"))
{
// Now bind any parameters that were retrieved.
foreach (KeyValuePair<string, PSObject> entry in parameters)
{
var argument =
CommandParameterInternal.CreateParameterWithArgument(
/*parameterAst*/null, entry.Key, "-" + entry.Key + ":",
/*argumentAst*/null, entry.Value,
false);
// Ignore the result since any failure should cause an exception
result =
BindParameter(argument, ParameterBindingFlags.ShouldCoerceType | ParameterBindingFlags.ThrowOnParameterNotFound);
Diagnostics.Assert(
result,
"Any error in binding the parameter with type coercion should result in an exception");
}
result = true;
}
}
else
{
result = false;
}
}
return result;
}
private Dictionary<string, PSObject> PromptForMissingMandatoryParameters(
Collection<FieldDescription> fieldDescriptionList,
Collection<MergedCompiledCommandParameter> missingMandatoryParameters)
{
Dictionary<string, PSObject> parameters = null;
Exception error = null;
// Prompt
try
{
ParameterBinderBase.bindingTracer.WriteLine(
"PROMPTING for missing mandatory parameters using the host");
string msg = ParameterBinderStrings.PromptMessage;
InvocationInfo invoInfo = Command.MyInvocation;
string caption = StringUtil.Format(ParameterBinderStrings.PromptCaption,
invoInfo.MyCommand.Name,
invoInfo.PipelinePosition);
parameters = Context.EngineHostInterface.UI.Prompt(caption, msg, fieldDescriptionList);
}
catch (NotImplementedException notImplemented)
{
error = notImplemented;
}
catch (HostException hostException)
{
error = hostException;
}
catch (PSInvalidOperationException invalidOperation)
{
error = invalidOperation;
}
if (error != null)
{
ParameterBinderBase.bindingTracer.WriteLine(
"ERROR: host does not support prompting for missing mandatory parameters");
string missingParameters = BuildMissingParamsString(missingMandatoryParameters);
ParameterBindingException bindingException =
new ParameterBindingException(
ErrorCategory.InvalidArgument,
this.Command.MyInvocation,
null,
missingParameters,
null,
null,
ParameterBinderStrings.MissingMandatoryParameter,
"MissingMandatoryParameter");
throw bindingException;
}
if ((parameters == null) || (parameters.Count == 0))
{
ParameterBinderBase.bindingTracer.WriteLine(
"ERROR: still missing mandatory parameters after PROMPTING");
string missingParameters = BuildMissingParamsString(missingMandatoryParameters);
ParameterBindingException bindingException =
new ParameterBindingException(
ErrorCategory.InvalidArgument,
this.Command.MyInvocation,
null,
missingParameters,
null,
null,
ParameterBinderStrings.MissingMandatoryParameter,
"MissingMandatoryParameter");
throw bindingException;
}
return parameters;
}
internal static string BuildMissingParamsString(Collection<MergedCompiledCommandParameter> missingMandatoryParameters)
{
StringBuilder missingParameters = new StringBuilder();
foreach (MergedCompiledCommandParameter missingParameter in missingMandatoryParameters)
{
missingParameters.Append(CultureInfo.InvariantCulture, $" {missingParameter.Parameter.Name}");
}
return missingParameters.ToString();
}
private Collection<FieldDescription> CreatePromptDataStructures(
Collection<MergedCompiledCommandParameter> missingMandatoryParameters)
{
StringBuilder usedHotKeys = new StringBuilder();
Collection<FieldDescription> fieldDescriptionList = new Collection<FieldDescription>();
// See if any of the unbound parameters are mandatory
foreach (MergedCompiledCommandParameter parameter in missingMandatoryParameters)
{
ParameterSetSpecificMetadata parameterSetMetadata =
parameter.Parameter.GetParameterSetData(_currentParameterSetFlag);
FieldDescription fDesc = new FieldDescription(parameter.Parameter.Name);
string helpInfo = null;
try
{
helpInfo = parameterSetMetadata.GetHelpMessage(Command);
}
catch (InvalidOperationException)
{
}
catch (ArgumentException)
{
}
if (!string.IsNullOrEmpty(helpInfo))
{
fDesc.HelpMessage = helpInfo;
}
fDesc.SetParameterType(parameter.Parameter.Type);
fDesc.Label = BuildLabel(parameter.Parameter.Name, usedHotKeys);
foreach (ValidateArgumentsAttribute vaAttr in parameter.Parameter.ValidationAttributes)
{
fDesc.Attributes.Add(vaAttr);
}
foreach (ArgumentTransformationAttribute arAttr in parameter.Parameter.ArgumentTransformationAttributes)
{
fDesc.Attributes.Add(arAttr);
}
fDesc.IsMandatory = true;
fieldDescriptionList.Add(fDesc);
}
return fieldDescriptionList;
}
/// <summary>
/// Creates a label with a Hotkey from <paramref name="parameterName"/>. The Hotkey is
/// <paramref name="parameterName"/>'s first capital character not in <paramref name="usedHotKeys"/>.
/// If <paramref name="parameterName"/> does not have any capital character, the first lower
/// case character is used. The Hotkey is preceded by an ampersand in the label.
/// </summary>
/// <param name="parameterName">
/// The parameter name from which the Hotkey is created
/// </param>
/// <param name="usedHotKeys">
/// A list of used HotKeys
/// </param>
/// <returns>
/// A label made from parameterName with a HotKey indicated by an ampersand
/// </returns>
private static string BuildLabel(string parameterName, StringBuilder usedHotKeys)
{
Diagnostics.Assert(!string.IsNullOrEmpty(parameterName), "parameterName is not set");
const char hotKeyPrefix = '&';
bool built = false;
StringBuilder label = new StringBuilder(parameterName);
string usedHotKeysStr = usedHotKeys.ToString();
for (int i = 0; i < parameterName.Length; i++)
{
// try Upper case
if (char.IsUpper(parameterName[i]) && usedHotKeysStr.Contains(parameterName[i]))
{
label.Insert(i, hotKeyPrefix);
usedHotKeys.Append(parameterName[i]);
built = true;
break;
}
}
if (!built)
{
// try Lower case
for (int i = 0; i < parameterName.Length; i++)
{
if (char.IsLower(parameterName[i]) && usedHotKeysStr.Contains(parameterName[i]))
{
label.Insert(i, hotKeyPrefix);
usedHotKeys.Append(parameterName[i]);
built = true;
break;
}
}
}
if (!built)
{
// try non-letters
for (int i = 0; i < parameterName.Length; i++)
{
if (!char.IsLetter(parameterName[i]) && usedHotKeysStr.Contains(parameterName[i]))
{
label.Insert(i, hotKeyPrefix);
usedHotKeys.Append(parameterName[i]);
built = true;
break;
}
}
}
if (!built)
{
// use first char
label.Insert(0, hotKeyPrefix);
}
return label.ToString();
}
/// <summary>
/// Gets the parameter set name for the current parameter set.
/// </summary>
internal string CurrentParameterSetName
{
get
{
string currentParameterSetName = BindableParameters.GetParameterSetName(_currentParameterSetFlag);
s_tracer.WriteLine("CurrentParameterSetName = {0}", currentParameterSetName);
return currentParameterSetName;
}
}
/// <summary>
/// Binds the specified object or its properties to parameters
/// that accept pipeline input.
/// </summary>
/// <param name="inputToOperateOn">
/// The pipeline object to bind.
/// </param>
/// <returns>
/// True if the pipeline input was bound successfully or there was nothing
/// to bind, or false if there was an error.
/// </returns>
internal bool BindPipelineParameters(PSObject inputToOperateOn)
{
bool result;
try
{
using (ParameterBinderBase.bindingTracer.TraceScope(
"BIND PIPELINE object to parameters: [{0}]",
_commandMetadata.Name))
{
// First run any of the delay bind ScriptBlocks and bind the
// result to the appropriate parameter.
bool thereWasSomethingToBind;
bool invokeScriptResult = InvokeAndBindDelayBindScriptBlock(inputToOperateOn, out thereWasSomethingToBind);
bool continueBindingAfterScriptBlockProcessing = !thereWasSomethingToBind || invokeScriptResult;
bool bindPipelineParametersResult = false;
if (continueBindingAfterScriptBlockProcessing)
{
// If any of the parameters in the parameter set which are not yet bound
// accept pipeline input, process the input object and bind to those
// parameters
bindPipelineParametersResult = BindPipelineParametersPrivate(inputToOperateOn);
}
// We are successful at binding the pipeline input if there was a ScriptBlock to
// run and it ran successfully or if we successfully bound a parameter based on
// the pipeline input.
result = (thereWasSomethingToBind && invokeScriptResult) || bindPipelineParametersResult;
}
}
catch (ParameterBindingException)
{
// Reset the default values
// This prevents the last pipeline object from being bound during EndProcessing
// if it failed some post binding verification step.
this.RestoreDefaultParameterValues(ParametersBoundThroughPipelineInput);
// Let the parameter binding errors propagate out
throw;
}
try
{
// Now make sure we have latched on to a single parameter set.
VerifyParameterSetSelected();
}
catch (ParameterBindingException)
{
// Reset the default values
// This prevents the last pipeline object from being bound during EndProcessing
// if it failed some post binding verification step.
this.RestoreDefaultParameterValues(ParametersBoundThroughPipelineInput);
throw;
}
if (!result)
{
// Reset the default values
// This prevents the last pipeline object from being bound during EndProcessing
// if it failed some post binding verification step.
this.RestoreDefaultParameterValues(ParametersBoundThroughPipelineInput);
}
return result;
}
/// <summary>
/// Binds the pipeline parameters using the specified input and parameter set.
/// </summary>
/// <param name="inputToOperateOn">
/// The pipeline input to be bound to the parameters.
/// </param>
/// <exception cref="ParameterBindingException">
/// If argument transformation fails.
/// or
/// The argument could not be coerced to the appropriate type for the parameter.
/// or
/// The parameter argument transformation, prerequisite, or validation failed.
/// or
/// If the binding to the parameter fails.
/// or
/// If there is a failure resetting values prior to binding from the pipeline
/// </exception>
/// <remarks>
/// The algorithm for binding the pipeline object is as follows. If any
/// step is successful true gets returned immediately.
///
/// - If parameter supports ValueFromPipeline
/// - attempt to bind input value without type coercion
/// - If parameter supports ValueFromPipelineByPropertyName
/// - attempt to bind the value of the property with the matching name without type coercion
///
/// Now see if we have a single valid parameter set and reset the validParameterSets flags as
/// necessary. If there are still multiple valid parameter sets, then we need to use TypeDistance
/// to determine which parameters to do type coercion binding on.
///
/// - If parameter supports ValueFromPipeline
/// - attempt to bind input value using type coercion
/// - If parameter support ValueFromPipelineByPropertyName
/// - attempt to bind the vlue of the property with the matching name using type coercion
/// </remarks>
private bool BindPipelineParametersPrivate(PSObject inputToOperateOn)
{
if (ParameterBinderBase.bindingTracer.IsEnabled)
{
ConsolidatedString dontuseInternalTypeNames;
ParameterBinderBase.bindingTracer.WriteLine(
"PIPELINE object TYPE = [{0}]",
inputToOperateOn == null || inputToOperateOn == AutomationNull.Value
? "null"
: ((dontuseInternalTypeNames = inputToOperateOn.InternalTypeNames).Count > 0 && dontuseInternalTypeNames[0] != null)
? dontuseInternalTypeNames[0]
: inputToOperateOn.BaseObject.GetType().FullName);
ParameterBinderBase.bindingTracer.WriteLine("RESTORING pipeline parameter's original values");
}
bool result = false;
// Reset the default values
this.RestoreDefaultParameterValues(ParametersBoundThroughPipelineInput);
// Now clear the parameter names from the previous pipeline input
ParametersBoundThroughPipelineInput.Clear();
// Now restore the parameter set flags
_currentParameterSetFlag = _prePipelineProcessingParameterSetFlags;
uint validParameterSets = _currentParameterSetFlag;
bool needToPrioritizeOneSpecificParameterSet = _parameterSetToBePrioritizedInPipelineBinding != 0;
int steps = needToPrioritizeOneSpecificParameterSet ? 2 : 1;
if (needToPrioritizeOneSpecificParameterSet)
{
// _parameterSetToBePrioritizedInPipelineBinding is set, so we are certain that the specified parameter set must be valid,
// and it's not the only valid parameter set.
Diagnostics.Assert((_currentParameterSetFlag & _parameterSetToBePrioritizedInPipelineBinding) != 0, "_parameterSetToBePrioritizedInPipelineBinding should be valid if it's set");
validParameterSets = _parameterSetToBePrioritizedInPipelineBinding;
}
for (int i = 0; i < steps; i++)
{
for (CurrentlyBinding currentlyBinding = CurrentlyBinding.ValueFromPipelineNoCoercion; currentlyBinding <= CurrentlyBinding.ValueFromPipelineByPropertyNameWithCoercion; ++currentlyBinding)
{
// The parameterBoundForCurrentlyBindingState will be true as long as there is one parameter gets bound, even if it belongs to AllSet
bool parameterBoundForCurrentlyBindingState =
BindUnboundParametersForBindingState(
inputToOperateOn,
currentlyBinding,
validParameterSets);
if (parameterBoundForCurrentlyBindingState)
{
// Now validate the parameter sets again and update the valid sets.
// No need to validate the parameter sets and update the valid sets when dealing with the prioritized parameter set,
// this is because the prioritized parameter set is a single set, and when binding succeeds, _currentParameterSetFlag
// must be equal to the specific prioritized parameter set.
if (!needToPrioritizeOneSpecificParameterSet || i == 1)
{
ValidateParameterSets(true, true);
validParameterSets = _currentParameterSetFlag;
}
result = true;
}
}
// Update the validParameterSets after the binding attempt for the prioritized parameter set
if (needToPrioritizeOneSpecificParameterSet && i == 0)
{
// If the prioritized set can be bound successfully, there is no need to do the second round binding
if (_currentParameterSetFlag == _parameterSetToBePrioritizedInPipelineBinding)
{
break;
}
validParameterSets = _currentParameterSetFlag & (~_parameterSetToBePrioritizedInPipelineBinding);
}
}
// Now make sure we only have one valid parameter set
// Note, this will throw if we have more than one.
ValidateParameterSets(false, true);
if (!DefaultParameterBindingInUse)
{
ApplyDefaultParameterBinding("PIPELINE BIND", false);
}
return result;
}
private bool BindUnboundParametersForBindingState(
PSObject inputToOperateOn,
CurrentlyBinding currentlyBinding,
uint validParameterSets)
{
bool aParameterWasBound = false;
// First check to see if the default parameter set has been defined and if it
// is still valid.
uint defaultParameterSetFlag = _commandMetadata.DefaultParameterSetFlag;
if (defaultParameterSetFlag != 0 && (validParameterSets & defaultParameterSetFlag) != 0)
{
// Since we have a default parameter set and it is still valid, give preference to the
// parameters in the default set.
aParameterWasBound =
BindUnboundParametersForBindingStateInParameterSet(
inputToOperateOn,
currentlyBinding,
defaultParameterSetFlag);
if (!aParameterWasBound)
{
validParameterSets &= ~(defaultParameterSetFlag);
}
}
if (!aParameterWasBound)
{
// Since nothing was bound for the default parameter set, try all
// the other parameter sets that are still valid.
aParameterWasBound =
BindUnboundParametersForBindingStateInParameterSet(
inputToOperateOn,
currentlyBinding,
validParameterSets);
}
s_tracer.WriteLine("aParameterWasBound = {0}", aParameterWasBound);
return aParameterWasBound;
}
private bool BindUnboundParametersForBindingStateInParameterSet(
PSObject inputToOperateOn,
CurrentlyBinding currentlyBinding,
uint validParameterSets)
{
bool aParameterWasBound = false;
// For all unbound parameters in the parameter set, see if we can bind
// from the input object directly from pipeline without type coercion.
//
// We loop the unbound parameters in reversed order, so that we can move
// items from the unboundParameters collection to the boundParameters
// collection as we process, without the need to make a copy of the
// unboundParameters collection.
//
// We used to make a copy of UnboundParameters and loop from the head of the
// list. Now we are processing the unbound parameters from the end of the list.
// This change should NOT be a breaking change. The 'validParameterSets' in
// this method never changes, so no matter we start from the head or the end of
// the list, every unbound parameter in the list that takes pipeline input and
// satisfy the 'validParameterSets' will be bound. If parameters from more than
// one sets got bound, then "parameter set cannot be resolved" error will be thrown,
// which is expected.
for (int i = UnboundParameters.Count - 1; i >= 0; i--)
{
var parameter = UnboundParameters[i];
// if the parameter is never a pipeline parameter, don't consider it
if (!parameter.Parameter.IsPipelineParameterInSomeParameterSet)
continue;
// if the parameter is not in the specified parameter set, don't consider it
if ((validParameterSets & parameter.Parameter.ParameterSetFlags) == 0 &&
!parameter.Parameter.IsInAllSets)
{
continue;
}
// Get the appropriate parameter set data
var parameterSetData = parameter.Parameter.GetMatchingParameterSetData(validParameterSets);
bool bindResult = false;
foreach (ParameterSetSpecificMetadata parameterSetMetadata in parameterSetData)
{
// In the first phase we try to bind the value from the pipeline without
// type coercion
if (currentlyBinding == CurrentlyBinding.ValueFromPipelineNoCoercion &&
parameterSetMetadata.ValueFromPipeline)
{
bindResult = BindValueFromPipeline(inputToOperateOn, parameter, ParameterBindingFlags.None);
}
// In the next phase we try binding the value from the pipeline by matching
// the property name
else if (currentlyBinding == CurrentlyBinding.ValueFromPipelineByPropertyNameNoCoercion &&
parameterSetMetadata.ValueFromPipelineByPropertyName &&
inputToOperateOn != null)
{
bindResult = BindValueFromPipelineByPropertyName(inputToOperateOn, parameter, ParameterBindingFlags.None);
}
// The third step is to attempt to bind the value from the pipeline with
// type coercion.
else if (currentlyBinding == CurrentlyBinding.ValueFromPipelineWithCoercion &&
parameterSetMetadata.ValueFromPipeline)
{
bindResult = BindValueFromPipeline(inputToOperateOn, parameter, ParameterBindingFlags.ShouldCoerceType);
}
// The final step is to attempt to bind the value from the pipeline by matching
// the property name
else if (currentlyBinding == CurrentlyBinding.ValueFromPipelineByPropertyNameWithCoercion &&
parameterSetMetadata.ValueFromPipelineByPropertyName &&
inputToOperateOn != null)
{
bindResult = BindValueFromPipelineByPropertyName(inputToOperateOn, parameter, ParameterBindingFlags.ShouldCoerceType);
}
if (bindResult)
{
aParameterWasBound = true;
break;
}
}
}
return aParameterWasBound;
}
private bool BindValueFromPipeline(
PSObject inputToOperateOn,
MergedCompiledCommandParameter parameter,
ParameterBindingFlags flags)
{
bool bindResult = false;
// Attempt binding the value from the pipeline
// without type coercion
ParameterBinderBase.bindingTracer.WriteLine(
((flags & ParameterBindingFlags.ShouldCoerceType) != 0) ?
"Parameter [{0}] PIPELINE INPUT ValueFromPipeline WITH COERCION" :
"Parameter [{0}] PIPELINE INPUT ValueFromPipeline NO COERCION",
parameter.Parameter.Name);
ParameterBindingException parameterBindingException = null;
try
{
bindResult = BindPipelineParameter(inputToOperateOn, parameter, flags);
}
catch (ParameterBindingArgumentTransformationException e)
{
PSInvalidCastException invalidCast;
if (e.InnerException is ArgumentTransformationMetadataException)
{
invalidCast = e.InnerException.InnerException as PSInvalidCastException;
}
else
{
invalidCast = e.InnerException as PSInvalidCastException;
}
if (invalidCast == null)
{
parameterBindingException = e;
}
// Just ignore and continue;
bindResult = false;
}
catch (ParameterBindingValidationException e)
{
parameterBindingException = e;
}
catch (ParameterBindingParameterDefaultValueException e)
{
parameterBindingException = e;
}
catch (ParameterBindingException)
{
// Just ignore and continue;
bindResult = false;
}
if (parameterBindingException != null)
{
if (!DefaultParameterBindingInUse)
{
throw parameterBindingException;
}
else
{
ThrowElaboratedBindingException(parameterBindingException);
}
}
return bindResult;
}
private bool BindValueFromPipelineByPropertyName(
PSObject inputToOperateOn,
MergedCompiledCommandParameter parameter,
ParameterBindingFlags flags)
{
bool bindResult = false;
ParameterBinderBase.bindingTracer.WriteLine(
((flags & ParameterBindingFlags.ShouldCoerceType) != 0) ?
"Parameter [{0}] PIPELINE INPUT ValueFromPipelineByPropertyName WITH COERCION" :
"Parameter [{0}] PIPELINE INPUT ValueFromPipelineByPropertyName NO COERCION",
parameter.Parameter.Name);
PSMemberInfo member = inputToOperateOn.Properties[parameter.Parameter.Name];
if (member == null)
{
// Since a member matching the name of the parameter wasn't found,
// check the aliases.
foreach (string alias in parameter.Parameter.Aliases)
{
member = inputToOperateOn.Properties[alias];
if (member != null)
{
break;
}
}
}
if (member != null)
{
ParameterBindingException parameterBindingException = null;
try
{
bindResult =
BindPipelineParameter(
member.Value,
parameter,
flags);
}
catch (ParameterBindingArgumentTransformationException e)
{
parameterBindingException = e;
}
catch (ParameterBindingValidationException e)
{
parameterBindingException = e;
}
catch (ParameterBindingParameterDefaultValueException e)
{
parameterBindingException = e;
}
catch (ParameterBindingException)
{
// Just ignore and continue;
bindResult = false;
}
if (parameterBindingException != null)
{
if (!DefaultParameterBindingInUse)
{
throw parameterBindingException;
}
else
{
ThrowElaboratedBindingException(parameterBindingException);
}
}
}
return bindResult;
}
/// <summary>
/// Used for defining the state of the binding state machine.
/// </summary>
private enum CurrentlyBinding
{
ValueFromPipelineNoCoercion = 0,
ValueFromPipelineByPropertyNameNoCoercion = 1,
ValueFromPipelineWithCoercion = 2,
ValueFromPipelineByPropertyNameWithCoercion = 3
}
/// <summary>
/// Invokes any delay bind script blocks and binds the resulting value
/// to the appropriate parameter.
/// </summary>
/// <param name="inputToOperateOn">
/// The input to the script block.
/// </param>
/// <param name="thereWasSomethingToBind">
/// Returns True if there was a ScriptBlock to invoke and bind, or false if there
/// are no ScriptBlocks to invoke.
/// </param>
/// <returns>
/// True if the binding succeeds, or false otherwise.
/// </returns>
/// <exception cref="ArgumentNullException">
/// if <paramref name="inputToOperateOn"/> is null.
/// </exception>
/// <exception cref="ParameterBindingException">
/// If execution of the script block throws an exception or if it doesn't produce
/// any output.
/// </exception>
private bool InvokeAndBindDelayBindScriptBlock(PSObject inputToOperateOn, out bool thereWasSomethingToBind)
{
thereWasSomethingToBind = false;
bool result = true;
// NOTE: we are not doing backup and restore of default parameter
// values here. It is not needed because each script block will be
// invoked and each delay bind parameter bound for each pipeline object.
// This is unlike normal pipeline object processing which may bind
// different parameters depending on the type of the incoming pipeline
// object.
// Loop through each of the delay bind script blocks and invoke them.
// Bind the result to the associated parameter
foreach (KeyValuePair<MergedCompiledCommandParameter, DelayedScriptBlockArgument> delayedScriptBlock in _delayBindScriptBlocks)
{
thereWasSomethingToBind = true;
CommandParameterInternal argument = delayedScriptBlock.Value._argument;
MergedCompiledCommandParameter parameter = delayedScriptBlock.Key;
ScriptBlock script = argument.ArgumentValue as ScriptBlock;
Diagnostics.Assert(
script != null,
"An argument should only be put in the delayBindScriptBlocks collection if it is a ScriptBlock");
Collection<PSObject> output = null;
Exception error = null;
using (ParameterBinderBase.bindingTracer.TraceScope(
"Invoking delay-bind ScriptBlock"))
{
if (delayedScriptBlock.Value._parameterBinder == this)
{
try
{
output = script.DoInvoke(inputToOperateOn, inputToOperateOn, Array.Empty<object>());
delayedScriptBlock.Value._evaluatedArgument = output;
}
catch (RuntimeException runtimeException)
{
error = runtimeException;
}
}
else
{
output = delayedScriptBlock.Value._evaluatedArgument;
}
}
if (error != null)
{
ParameterBindingException bindingException =
new ParameterBindingException(
error,
ErrorCategory.InvalidArgument,
this.Command.MyInvocation,
GetErrorExtent(argument),
parameter.Parameter.Name,
null,
null,
ParameterBinderStrings.ScriptBlockArgumentInvocationFailed,
"ScriptBlockArgumentInvocationFailed",
error.Message);
throw bindingException;
}
if (output == null || output.Count == 0)
{
ParameterBindingException bindingException =
new ParameterBindingException(
null,
ErrorCategory.InvalidArgument,
this.Command.MyInvocation,
GetErrorExtent(argument),
parameter.Parameter.Name,
null,
null,
ParameterBinderStrings.ScriptBlockArgumentNoOutput,
"ScriptBlockArgumentNoOutput");
throw bindingException;
}
// Check the output. If it is only a single value, just pass the single value,
// if not, pass in the whole collection.
object newValue = output;
if (output.Count == 1)
{
newValue = output[0];
}
// Create a new CommandParameterInternal for the output of the script block.
var newArgument = CommandParameterInternal.CreateParameterWithArgument(
argument.ParameterAst, argument.ParameterName, "-" + argument.ParameterName + ":",
argument.ArgumentAst, newValue,
false);
if (!BindParameter(newArgument, parameter, ParameterBindingFlags.ShouldCoerceType))
{
result = false;
}
}
return result;
}
/// <summary>
/// Determines the number of valid parameter sets based on the valid parameter
/// set flags.
/// </summary>
/// <param name="parameterSetFlags">
/// The valid parameter set flags.
/// </param>
/// <returns>
/// The number of valid parameter sets in the parameterSetFlags.
/// </returns>
private static int ValidParameterSetCount(uint parameterSetFlags)
{
int result = 0;
if (parameterSetFlags == uint.MaxValue)
{
result = 1;
}
else
{
while (parameterSetFlags != 0)
{
result += (int)(parameterSetFlags & 0x1);
parameterSetFlags >>= 1;
}
}
return result;
}
#endregion helper_methods
#region private_members
/// <summary>
/// This method gets a backup of the default value of a parameter.
/// Derived classes may override this method to get the default parameter
/// value in a different way.
/// </summary>
/// <param name="name">
/// The name of the parameter to get the default value of.
/// </param>
/// <returns>
/// The value of the parameter specified by name.
/// </returns>
/// <exception cref="ParameterBindingParameterDefaultValueException">
/// If the parameter binder encounters an error getting the default value.
/// </exception>
internal object GetDefaultParameterValue(string name)
{
MergedCompiledCommandParameter matchingParameter =
BindableParameters.GetMatchingParameter(
name,
false,
true,
null);
object result = null;
try
{
switch (matchingParameter.BinderAssociation)
{
case ParameterBinderAssociation.DeclaredFormalParameters:
result = DefaultParameterBinder.GetDefaultParameterValue(name);
break;
case ParameterBinderAssociation.CommonParameters:
result = CommonParametersBinder.GetDefaultParameterValue(name);
break;
case ParameterBinderAssociation.ShouldProcessParameters:
result = ShouldProcessParametersBinder.GetDefaultParameterValue(name);
break;
case ParameterBinderAssociation.DynamicParameters:
if (_dynamicParameterBinder != null)
{
result = _dynamicParameterBinder.GetDefaultParameterValue(name);
}
break;
}
}
catch (GetValueException getValueException)
{
ParameterBindingParameterDefaultValueException bindingError =
new ParameterBindingParameterDefaultValueException(
getValueException,
ErrorCategory.ReadError,
this.Command.MyInvocation,
null,
name,
null,
null,
"ParameterBinderStrings",
"GetDefaultValueFailed",
getValueException.Message);
throw bindingError;
}
return result;
}
/// <summary>
/// Gets or sets the command that this parameter binder controller
/// will bind parameters to.
/// </summary>
internal Cmdlet Command { get; }
#region DefaultParameterBindingStructures
/// <summary>
/// The separator used in GetDefaultParameterValuePairs function.
/// </summary>
private const string Separator = ":::";
// Hold all aliases of the current cmdlet
private List<string> _aliasList;
// Method GetDefaultParameterValuePairs() will be invoked twice, one time before the Named Bind,
// one time after Dynamic Bind. We don't want the same warning message to be written out twice.
// Put the key(in case the key format is invalid), or cmdletName+separator+parameterName(in case
// setting resolves to multiple parameters or multiple different values are assigned to the same
// parameter) in warningSet when the corresponding warnings are written out, so they won't get
// written out the second time GetDefaultParameterValuePairs() is called.
private readonly HashSet<string> _warningSet = new HashSet<string>();
// Hold all user defined default parameter values
private Dictionary<MergedCompiledCommandParameter, object> _allDefaultParameterValuePairs;
private bool _useDefaultParameterBinding = true;
#endregion DefaultParameterBindingStructures
private uint _parameterSetToBePrioritizedInPipelineBinding = 0;
/// <summary>
/// The cmdlet metadata.
/// </summary>
private readonly CommandMetadata _commandMetadata;
/// <summary>
/// THe command runtime object for this cmdlet.
/// </summary>
private readonly MshCommandRuntime _commandRuntime;
/// <summary>
/// Keep the obsolete parameter warnings generated from parameter binding.
/// </summary>
internal List<WarningRecord> ObsoleteParameterWarningList { get; private set; }
/// <summary>
/// Keep names of the parameters for which we have generated obsolete warning messages.
/// </summary>
private HashSet<string> BoundObsoleteParameterNames
{
get
{
return _boundObsoleteParameterNames ??= new HashSet<string>(StringComparer.OrdinalIgnoreCase);
}
}
private HashSet<string> _boundObsoleteParameterNames;
/// <summary>
/// The parameter binder for the dynamic parameters. Currently this
/// can be either a ReflectionParameterBinder or a RuntimeDefinedParameterBinder.
/// </summary>
private ParameterBinderBase _dynamicParameterBinder;
/// <summary>
/// The parameter binder for the ShouldProcess parameters.
/// </summary>
internal ReflectionParameterBinder ShouldProcessParametersBinder
{
get
{
if (_shouldProcessParameterBinder == null)
{
// Construct a new instance of the should process parameters object
ShouldProcessParameters shouldProcessParameters = new ShouldProcessParameters(_commandRuntime);
// Create reflection binder for this object
_shouldProcessParameterBinder =
new ReflectionParameterBinder(
shouldProcessParameters,
this.Command,
this.CommandLineParameters);
}
return _shouldProcessParameterBinder;
}
}
private ReflectionParameterBinder _shouldProcessParameterBinder;
/// <summary>
/// The parameter binder for the Paging parameters.
/// </summary>
internal ReflectionParameterBinder PagingParametersBinder
{
get
{
if (_pagingParameterBinder == null)
{
// Construct a new instance of the should process parameters object
PagingParameters pagingParameters = new PagingParameters(_commandRuntime);
// Create reflection binder for this object
_pagingParameterBinder =
new ReflectionParameterBinder(
pagingParameters,
this.Command,
this.CommandLineParameters);
}
return _pagingParameterBinder;
}
}
private ReflectionParameterBinder _pagingParameterBinder;
/// <summary>
/// The parameter binder for the Transactions parameters.
/// </summary>
internal ReflectionParameterBinder TransactionParametersBinder
{
get
{
if (_transactionParameterBinder == null)
{
// Construct a new instance of the transactions parameters object
TransactionParameters transactionParameters = new TransactionParameters(_commandRuntime);
// Create reflection binder for this object
_transactionParameterBinder =
new ReflectionParameterBinder(
transactionParameters,
this.Command,
this.CommandLineParameters);
}
return _transactionParameterBinder;
}
}
private ReflectionParameterBinder _transactionParameterBinder;
/// <summary>
/// The parameter binder for the CommonParameters.
/// </summary>
internal ReflectionParameterBinder CommonParametersBinder
{
get
{
if (_commonParametersBinder == null)
{
// Construct a new instance of the user feedback parameters object
CommonParameters commonParameters = new CommonParameters(_commandRuntime);
// Create reflection binder for this object
_commonParametersBinder =
new ReflectionParameterBinder(
commonParameters,
this.Command,
this.CommandLineParameters);
}
return _commonParametersBinder;
}
}
private ReflectionParameterBinder _commonParametersBinder;
private sealed class DelayedScriptBlockArgument
{
// Remember the parameter binder so we know when to invoke the script block
// and when to use the evaluated argument.
internal CmdletParameterBinderController _parameterBinder;
internal CommandParameterInternal _argument;
internal Collection<PSObject> _evaluatedArgument;
public override string ToString()
{
return _argument.ArgumentValue.ToString();
}
}
/// <summary>
/// This dictionary is used to contain the arguments that were passed in as ScriptBlocks
/// but the parameter isn't a ScriptBlock. So we have to wait to bind the parameter
/// until there is a pipeline object available to invoke the ScriptBlock with.
/// </summary>
private readonly Dictionary<MergedCompiledCommandParameter, DelayedScriptBlockArgument> _delayBindScriptBlocks =
new Dictionary<MergedCompiledCommandParameter, DelayedScriptBlockArgument>();
/// <summary>
/// A collection of the default values of the parameters.
/// </summary>
private readonly Dictionary<string, CommandParameterInternal> _defaultParameterValues =
new Dictionary<string, CommandParameterInternal>(StringComparer.OrdinalIgnoreCase);
#endregion private_members
/// <summary>
/// Binds the specified value to the specified parameter.
/// </summary>
/// <param name="parameterValue">
/// The value to bind to the parameter
/// </param>
/// <param name="parameter">
/// The parameter to bind the value to.
/// </param>
/// <param name="flags">
/// Parameter binding flags for type coercion and validation.
/// </param>
/// <returns>
/// True if the parameter was successfully bound. False if <paramref name="flags"/>
/// specifies no coercion and the type does not match the parameter type.
/// </returns>
/// <exception cref="ParameterBindingParameterDefaultValueException">
/// If the parameter binder encounters an error getting the default value.
/// </exception>
private bool BindPipelineParameter(
object parameterValue,
MergedCompiledCommandParameter parameter,
ParameterBindingFlags flags)
{
bool result = false;
if (parameterValue != AutomationNull.Value)
{
s_tracer.WriteLine("Adding PipelineParameter name={0}; value={1}",
parameter.Parameter.Name, parameterValue ?? "null");
// Backup the default value
BackupDefaultParameter(parameter);
// Now bind the new value
CommandParameterInternal param = CommandParameterInternal.CreateParameterWithArgument(
/*parameterAst*/null, parameter.Parameter.Name, "-" + parameter.Parameter.Name + ":",
/*argumentAst*/null, parameterValue,
false);
flags &= ~ParameterBindingFlags.DelayBindScriptBlock;
result = BindParameter(_currentParameterSetFlag, param, parameter, flags);
if (result)
{
// Now make sure to remember that the default value needs to be restored
// if we get another pipeline object
ParametersBoundThroughPipelineInput.Add(parameter);
}
}
return result;
}
protected override void SaveDefaultScriptParameterValue(string name, object value)
{
_defaultParameterValues.Add(name,
CommandParameterInternal.CreateParameterWithArgument(
/*parameterAst*/null, name, "-" + name + ":",
/*argumentAst*/null, value,
false));
}
/// <summary>
/// Backs up the specified parameter value by calling the GetDefaultParameterValue
/// abstract method.
///
/// This method is called when binding a parameter value that came from a pipeline
/// object.
/// </summary>
/// <exception cref="ParameterBindingParameterDefaultValueException">
/// If the parameter binder encounters an error getting the default value.
/// </exception>
private void BackupDefaultParameter(MergedCompiledCommandParameter parameter)
{
if (!_defaultParameterValues.ContainsKey(parameter.Parameter.Name))
{
object defaultParameterValue = GetDefaultParameterValue(parameter.Parameter.Name);
_defaultParameterValues.Add(
parameter.Parameter.Name,
CommandParameterInternal.CreateParameterWithArgument(
/*parameterAst*/null, parameter.Parameter.Name, "-" + parameter.Parameter.Name + ":",
/*argumentAst*/null, defaultParameterValue,
false));
}
}
/// <summary>
/// Replaces the values of the parameters with their initial value for the
/// parameters specified.
/// </summary>
/// <param name="parameters">
/// The parameters that should have their default values restored.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="parameters"/> is null.
/// </exception>
private void RestoreDefaultParameterValues(IEnumerable<MergedCompiledCommandParameter> parameters)
{
if (parameters == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(parameters));
}
// Get all the matching arguments from the defaultParameterValues collection
// and bind those that had parameters that were bound via pipeline input
foreach (MergedCompiledCommandParameter parameter in parameters)
{
if (parameter == null)
{
continue;
}
CommandParameterInternal argumentToBind = null;
// If the argument was found then bind it to the parameter
// and manage the bound and unbound parameter list
if (_defaultParameterValues.TryGetValue(parameter.Parameter.Name, out argumentToBind))
{
// Don't go through the normal binding routine to run data generation,
// type coercion, validation, or prerequisites since we know the
// type is already correct, and we don't want data generation to
// run when resetting the default value.
Exception error = null;
try
{
// We shouldn't have to coerce the type here so its
// faster to pass false
bool bindResult = RestoreParameter(argumentToBind, parameter);
Diagnostics.Assert(
bindResult,
"Restoring the default value should not require type coercion");
}
catch (SetValueException setValueException)
{
error = setValueException;
}
if (error != null)
{
Type specifiedType = argumentToBind.ArgumentValue?.GetType();
ParameterBindingException bindingException =
new ParameterBindingException(
error,
ErrorCategory.WriteError,
this.InvocationInfo,
GetErrorExtent(argumentToBind),
parameter.Parameter.Name,
parameter.Parameter.Type,
specifiedType,
ParameterBinderStrings.ParameterBindingFailed,
"ParameterBindingFailed",
error.Message);
throw bindingException;
}
// Since the parameter was returned to its original value,
// ensure that it is not in the boundParameters list but
// is in the unboundParameters list
BoundParameters.Remove(parameter.Parameter.Name);
if (!UnboundParameters.Contains(parameter))
{
UnboundParameters.Add(parameter);
}
BoundArguments.Remove(parameter.Parameter.Name);
}
else
{
// Since the parameter was not reset, ensure that the parameter
// is in the bound parameters list and not in the unbound
// parameters list
if (!BoundParameters.ContainsKey(parameter.Parameter.Name))
{
BoundParameters.Add(parameter.Parameter.Name, parameter);
}
// Ensure the parameter is not in the unboundParameters list
UnboundParameters.Remove(parameter);
}
}
}
}
/// <summary>
/// A versionable hashtable, so the caching of UserInput -> ParameterBindingResult will work.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2237:MarkISerializableTypesWithSerializable", Justification = "DefaultParameterDictionary will only be used for $PSDefaultParameterValues.")]
public sealed class DefaultParameterDictionary : Hashtable
{
private bool _isChanged;
/// <summary>
/// Check to see if the hashtable has been changed since last check.
/// </summary>
/// <returns>True for changed; false for not changed.</returns>
public bool ChangeSinceLastCheck()
{
bool ret = _isChanged;
_isChanged = false;
return ret;
}
#region Constructor
/// <summary>
/// Default constructor.
/// </summary>
public DefaultParameterDictionary()
: base(StringComparer.OrdinalIgnoreCase)
{
_isChanged = true;
}
/// <summary>
/// Constructor takes a hash table.
/// </summary>
/// <remarks>
/// Check for the keys' formats and make it versionable
/// </remarks>
/// <param name="dictionary">A hashtable instance.</param>
public DefaultParameterDictionary(IDictionary dictionary)
: this()
{
if (dictionary == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(dictionary));
}
// Contains keys that are in bad format. For every bad format key, we should write out a warning message
// the first time we encounter it, and remove it from the $PSDefaultParameterValues
var keysInBadFormat = new List<object>();
foreach (DictionaryEntry entry in dictionary)
{
var entryKey = entry.Key as string;
if (entryKey != null)
{
string key = entryKey.Trim();
string cmdletName = null;
string parameterName = null;
bool isSpecialKey = false; // The key is 'Disabled'
// The key is not with valid format
if (!CheckKeyIsValid(key, ref cmdletName, ref parameterName))
{
isSpecialKey = key.Equals("Disabled", StringComparison.OrdinalIgnoreCase);
if (!isSpecialKey)
{
keysInBadFormat.Add(entryKey);
continue;
}
}
Diagnostics.Assert(isSpecialKey || (cmdletName != null && parameterName != null), "The cmdletName and parameterName should be set in CheckKeyIsValid");
if (keysInBadFormat.Count == 0 && !base.ContainsKey(key))
{
base.Add(key, entry.Value);
}
}
else
{
keysInBadFormat.Add(entry.Key);
}
}
var keysInError = new StringBuilder();
foreach (object badFormatKey in keysInBadFormat)
{
keysInError.Append(badFormatKey.ToString() + ", ");
}
if (keysInError.Length > 0)
{
keysInError.Remove(keysInError.Length - 2, 2);
string resourceString = keysInBadFormat.Count > 1
? ParameterBinderStrings.MultipleKeysInBadFormat
: ParameterBinderStrings.SingleKeyInBadFormat;
throw PSTraceSource.NewInvalidOperationException(resourceString, keysInError);
}
}
#endregion Constructor
/// <summary>
/// Override Contains.
/// </summary>
public override bool Contains(object key)
{
return this.ContainsKey(key);
}
/// <summary>
/// Override ContainsKey.
/// </summary>
public override bool ContainsKey(object key)
{
if (key == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(key));
}
if (key is not string strKey)
{
return false;
}
string keyAfterTrim = strKey.Trim();
return base.ContainsKey(keyAfterTrim);
}
/// <summary>
/// Override the Add to check for key's format and make it versionable.
/// </summary>
/// <param name="key">Key.</param>
/// <param name="value">Value.</param>
public override void Add(object key, object value)
{
AddImpl(key, value, isSelfIndexing: false);
}
/// <summary>
/// Actual implementation for Add.
/// </summary>
private void AddImpl(object key, object value, bool isSelfIndexing)
{
if (key == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(key));
}
if (key is not string strKey)
{
throw PSTraceSource.NewArgumentException(nameof(key), ParameterBinderStrings.StringValueKeyExpected, key, key.GetType().FullName);
}
string keyAfterTrim = strKey.Trim();
string cmdletName = null;
string parameterName = null;
if (base.ContainsKey(keyAfterTrim))
{
if (isSelfIndexing)
{
_isChanged = true;
base[keyAfterTrim] = value;
return;
}
throw PSTraceSource.NewArgumentException(nameof(key), ParameterBinderStrings.KeyAlreadyAdded, key);
}
if (!CheckKeyIsValid(keyAfterTrim, ref cmdletName, ref parameterName))
{
// The key is not in valid format
if (!keyAfterTrim.Equals("Disabled", StringComparison.OrdinalIgnoreCase))
{
throw PSTraceSource.NewInvalidOperationException(ParameterBinderStrings.SingleKeyInBadFormat, key);
}
}
_isChanged = true;
base.Add(keyAfterTrim, value);
}
/// <summary>
/// Override the indexing to check for key's format and make it versionable.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public override object this[object key]
{
get
{
if (key == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(key));
}
if (key is not string strKey)
{
return null;
}
string keyAfterTrim = strKey.Trim();
return base[keyAfterTrim];
}
set
{
AddImpl(key, value, isSelfIndexing: true);
}
}
/// <summary>
/// Override the Remove to make it versionable.
/// </summary>
/// <param name="key">Key.</param>
public override void Remove(object key)
{
if (key == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(key));
}
if (key is not string strKey)
{
return;
}
string keyAfterTrim = strKey.Trim();
if (base.ContainsKey(keyAfterTrim))
{
base.Remove(keyAfterTrim);
_isChanged = true;
}
}
/// <summary>
/// Override the Clear to make it versionable.
/// </summary>
public override void Clear()
{
base.Clear();
_isChanged = true;
}
#region KeyValidation
/// <summary>
/// Check if the key is in valid format. If it is, get the cmdlet name and parameter name.
/// </summary>
/// <param name="key"></param>
/// <param name="cmdletName"></param>
/// <param name="parameterName"></param>
/// <returns>Return true if the key is valid, false if not.</returns>
internal static bool CheckKeyIsValid(string key, ref string cmdletName, ref string parameterName)
{
if (key == string.Empty)
{
return false;
}
// The index returned should point to the separator or a character that is before the separator
int index = GetValueToken(0, key, ref cmdletName, true);
if (index == -1)
{
return false;
}
// The index returned should point to the first non-whitespace character, and it should be the separator
index = SkipWhiteSpace(index, key);
if (index == -1 || key[index] != ':')
{
return false;
}
// The index returned should point to the first non-whitespace character after the separator
index = SkipWhiteSpace(index + 1, key);
if (index == -1)
{
return false;
}
// The index returned should point to the last character in key
index = GetValueToken(index, key, ref parameterName, false);
if (index == -1 || index != key.Length)
{
return false;
}
return true;
}
/// <summary>
/// Get the cmdlet name and the parameter name.
/// </summary>
/// <param name="index">Point to a non-whitespace character.</param>
/// <param name="key">The key to iterate over.</param>
/// <param name="name"></param>
/// <param name="getCmdletName">Specify whether to get the cmdlet name or parameter name.</param>
/// <returns>
/// For cmdletName:
/// When the name is enclosed by quotes, the index returned should be the index of the character right after the second quote;
/// When the name is not enclosed by quotes, the index returned should be the index of the separator;
///
/// For parameterName:
/// When the name is enclosed by quotes, the index returned should be the index of the second quote plus 1 (the length of the key if the key is in a valid format);
/// When the name is not enclosed by quotes, the index returned should be the length of the key.
/// </returns>
private static int GetValueToken(int index, string key, ref string name, bool getCmdletName)
{
char quoteChar = '\0';
if (key[index].IsSingleQuote() || key[index].IsDoubleQuote())
{
quoteChar = key[index];
index++;
}
StringBuilder builder = new StringBuilder(string.Empty);
for (; index < key.Length; index++)
{
if (quoteChar != '\0')
{
if ((quoteChar.IsSingleQuote() && key[index].IsSingleQuote()) ||
(quoteChar.IsDoubleQuote() && key[index].IsDoubleQuote()))
{
name = builder.ToString().Trim();
// Make the index point to the character right after the quote
return name.Length == 0 ? -1 : index + 1;
}
builder.Append(key[index]);
continue;
}
if (getCmdletName)
{
if (key[index] != ':')
{
builder.Append(key[index]);
continue;
}
name = builder.ToString().Trim();
return name.Length == 0 ? -1 : index;
}
else
{
builder.Append(key[index]);
}
}
if (!getCmdletName && quoteChar == '\0')
{
name = builder.ToString().Trim();
Diagnostics.Assert(name.Length > 0, "name should not be empty at this point");
return index;
}
return -1;
}
/// <summary>
/// Skip whitespace characters.
/// </summary>
/// <param name="index">Start index.</param>
/// <param name="key">The string to iterate over.</param>
/// <returns>
/// Return -1 if we reach the end of the key, otherwise return the index of the first
/// non-whitespace character we encounter.
/// </returns>
private static int SkipWhiteSpace(int index, string key)
{
for (; index < key.Length; index++)
{
if (key[index].IsWhitespace() || key[index] == '\r' || key[index] == '\n')
continue;
return index;
}
return -1;
}
#endregion KeyValidation
}
}
|