File size: 93,716 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 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Management.Automation.Security;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace System.Management.Automation.Internal
{
/// <summary>
/// Serves as the base class for Metadata attributes.
/// </summary>
/// <remarks>
/// PSSnapins may not create custom attributes derived directly from <see cref="CmdletMetadataAttribute"/>,
/// since it has no public constructor. Only the public subclasses <see cref="ValidateArgumentsAttribute"/>
/// and <see cref="ArgumentTransformationAttribute"/> are available.
/// </remarks>
/// <seealso cref="CmdletMetadataAttribute"/>
/// <seealso cref="ValidateArgumentsAttribute"/>
/// <seealso cref="ArgumentTransformationAttribute"/>
[AttributeUsage(AttributeTargets.All)]
public abstract class CmdletMetadataAttribute : Attribute
{
/// <summary>
/// Default constructor.
/// </summary>
internal CmdletMetadataAttribute()
{
}
}
/// <summary>
/// Serves as the base class for Metadata attributes that serve as guidance to the parser and parameter binder.
/// </summary>
/// <remarks>
/// PSSnapins may not create custom attributes derived from <see cref="ParsingBaseAttribute"/>, since it
/// has no public constructor. Only the sealed public subclasses <see cref="ParameterAttribute"/> and
/// <see cref="AliasAttribute"/> are available.
/// </remarks>
/// <seealso cref="ParsingBaseAttribute"/>
/// <seealso cref="ParameterAttribute"/>
/// <seealso cref="AliasAttribute"/>
[AttributeUsage(AttributeTargets.All)]
public abstract class ParsingBaseAttribute : CmdletMetadataAttribute
{
/// <summary>
/// Constructor with no parameters.
/// </summary>
internal ParsingBaseAttribute()
{
}
}
}
namespace System.Management.Automation
{
#region Base Metadata Classes
/// <summary>
/// Serves as the base class for Validate attributes that validate parameter arguments.
/// </summary>
/// <remarks>
/// Argument validation attributes can be attached to <see cref="Cmdlet"/> and
/// <see cref="Provider.CmdletProvider"/> parameters to ensure that the Cmdlet or CmdletProvider will
/// not be invoked with invalid values of the parameter. Existing validation attributes include
/// <see cref="ValidateCountAttribute"/>,
/// <see cref="ValidateNotNullAttribute"/>,
/// <see cref="ValidateNotNullOrEmptyAttribute"/>,
/// <see cref="ValidateArgumentsAttribute"/>,
/// <see cref="ValidateLengthAttribute"/>,
/// <see cref="ValidateRangeAttribute"/>,
/// <see cref="ValidatePatternAttribute"/>, and
/// <see cref="ValidateSetAttribute"/>.
/// PSSnapins wishing to create custom argument validation attributes should derive from
/// <see cref="ValidateArgumentsAttribute"/> and override the
/// <see cref="ValidateArgumentsAttribute.Validate"/> abstract method, after which they can apply the
/// attribute to their parameters.
/// <see cref="ValidateArgumentsAttribute"/> validates the argument as a whole. If the argument value may
/// be an enumerable, you can derive from <see cref="ValidateEnumeratedArgumentsAttribute"/>
/// which will take care of unrolling the enumerable and validate each element individually.
/// It is also recommended to override <see cref="object.ToString"/> to return a readable string
/// similar to the attribute declaration, for example "[ValidateRangeAttribute(5,10)]".
/// If this attribute is applied to a string parameter, the string command argument will be validated.
/// If this attribute is applied to a string[] parameter, the string[] command argument will be validated.
/// </remarks>
/// <seealso cref="ValidateEnumeratedArgumentsAttribute"/>
/// <seealso cref="ValidateCountAttribute"/>
/// <seealso cref="ValidateNotNullAttribute"/>
/// <seealso cref="ValidateNotNullOrEmptyAttribute"/>
/// <seealso cref="ValidateArgumentsAttribute"/>
/// <seealso cref="ValidateLengthAttribute"/>
/// <seealso cref="ValidateRangeAttribute"/>
/// <seealso cref="ValidatePatternAttribute"/>
/// <seealso cref="ValidateSetAttribute"/>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public abstract class ValidateArgumentsAttribute : CmdletMetadataAttribute
{
/// <summary>
/// Verify that the value of <paramref name="arguments"/> is valid.
/// </summary>
/// <param name="arguments">Argument value to validate.</param>
/// <param name="engineIntrinsics">
/// The engine APIs for the context under which the prerequisite is being evaluated.
/// </param>
/// <exception cref="ValidationMetadataException">Should be thrown for any validation failure.</exception>
protected abstract void Validate(object arguments, EngineIntrinsics engineIntrinsics);
/// <summary>
/// Method that the command processor calls for data validate processing.
/// </summary>
/// <param name="o">Object to validate.</param>
/// <param name="engineIntrinsics">
/// The engine APIs for the context under which the prerequisite is being evaluated.
/// </param>
/// <returns>True if the validation succeeded.</returns>
/// <exception cref="ValidationMetadataException">
/// Whenever any exception occurs during data validation.
/// Additionally, all the system exceptions are wrapped in ValidationMetadataException.
/// </exception>
/// <exception cref="ArgumentException">For invalid arguments.</exception>
internal void InternalValidate(object o, EngineIntrinsics engineIntrinsics) => Validate(o, engineIntrinsics);
/// <summary>
/// Initializes a new instance of a class derived from <see cref="ValidateArgumentsAttribute"/>.
/// </summary>
protected ValidateArgumentsAttribute()
{
}
}
/// <summary>
/// A variant of <see cref="ValidateArgumentsAttribute"/> which unrolls enumeration values and validates
/// each element individually.
/// </summary>
/// <remarks>
/// <see cref="ValidateEnumeratedArgumentsAttribute"/> is like <see cref="ValidateArgumentsAttribute"/>,
/// except that if the argument value is enumerable, <see cref="ValidateEnumeratedArgumentsAttribute"/>
/// will unroll the enumeration and validate each item individually.
/// Existing enumerated validation attributes include
/// <see cref="ValidateLengthAttribute"/>,
/// <see cref="ValidateRangeAttribute"/>,
/// <see cref="ValidatePatternAttribute"/>, and
/// <see cref="ValidateSetAttribute"/>.
/// PSSnapins wishing to create custom enumerated argument validation attributes should derive from
/// <seealso cref="ValidateEnumeratedArgumentsAttribute"/> and override the
/// <seealso cref="ValidateEnumeratedArgumentsAttribute.ValidateElement"/>
/// abstract method, after which they can apply the attribute to their parameters.
/// It is also recommended to override <see cref="object.ToString"/> to return a readable string
/// similar to the attribute declaration, for example "[ValidateRangeAttribute(5,10)]".
/// If this attribute is applied to a string parameter, the string command argument will be validated.
/// If this attribute is applied to a string[] parameter, each string command argument will be validated.
/// </remarks>
/// <seealso cref="ValidateArgumentsAttribute"/>
/// <seealso cref="ValidateLengthAttribute"/>
/// <seealso cref="ValidateRangeAttribute"/>
/// <seealso cref="ValidatePatternAttribute"/>
/// <seealso cref="ValidateSetAttribute"/>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public abstract class ValidateEnumeratedArgumentsAttribute : ValidateArgumentsAttribute
{
/// <summary>
/// Initializes a new instance of a class derived from <see cref="ValidateEnumeratedArgumentsAttribute"/>.
/// </summary>
protected ValidateEnumeratedArgumentsAttribute() : base()
{
}
/// <summary>
/// Abstract method to be overridden by subclasses, implementing the validation of each parameter argument.
/// </summary>
/// <remarks>
/// Validate that the value of <paramref name="element"/> is valid, and throw
/// <see cref="ValidationMetadataException"/> if it is invalid.
/// </remarks>
/// <param name="element">One of the parameter arguments.</param>
/// <exception cref="ValidationMetadataException">Should be thrown for any validation failure.</exception>
protected abstract void ValidateElement(object element);
/// <summary>
/// Calls ValidateElement in each element in the enumeration argument value.
/// </summary>
/// <param name="arguments">Object to validate.</param>
/// <param name="engineIntrinsics">
/// The engine APIs for the context under which the prerequisite is being evaluated.
/// </param>
/// <remarks>
/// PSSnapins should override <see cref="ValidateElement"/> instead.
/// </remarks>
/// <exception cref="ValidationMetadataException">Should be thrown for any validation failure.</exception>
protected sealed override void Validate(object arguments, EngineIntrinsics engineIntrinsics)
{
if (LanguagePrimitives.IsNull(arguments))
{
throw new ValidationMetadataException(
"ArgumentIsEmpty",
null,
Metadata.ValidateNotNullOrEmptyCollectionFailure);
}
var enumerator = _getEnumeratorSite.Target.Invoke(_getEnumeratorSite, arguments);
if (enumerator == null)
{
ValidateElement(arguments);
return;
}
// arguments is IEnumerator
while (enumerator.MoveNext())
{
ValidateElement(enumerator.Current);
}
enumerator.Reset();
}
private readonly CallSite<Func<CallSite, object, IEnumerator>> _getEnumeratorSite =
CallSite<Func<CallSite, object, IEnumerator>>.Create(PSEnumerableBinder.Get());
}
#endregion Base Metadata Classes
#region Misc Attributes
/// <summary>
/// To specify RunAs behavior for the class
/// /// </summary>
public enum DSCResourceRunAsCredential
{
/// <summary>Default is same as optional.</summary>
Default,
/// <summary>
/// PsDscRunAsCredential can not be used for this DSC Resource.
/// </summary>
NotSupported,
/// <summary>
/// PsDscRunAsCredential is mandatory for resource.
/// </summary>
Mandatory,
/// <summary>
/// PsDscRunAsCredential can or can not be specified.
/// </summary>
Optional = Default,
}
/// <summary>
/// Indicates the class defines a DSC resource.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class DscResourceAttribute : CmdletMetadataAttribute
{
/// <summary>
/// To specify RunAs Behavior for the resource.
/// </summary>
public DSCResourceRunAsCredential RunAsCredential { get; set; }
}
/// <summary>
/// When specified on a property or field of a DSC Resource, the property
/// can or must be specified in a configuration, unless it is marked
/// <see cref="DscPropertyAttribute.NotConfigurable"/>, in which case it is
/// returned by the Get() method of the resource.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class DscPropertyAttribute : CmdletMetadataAttribute
{
/// <summary>
/// Indicates the property is a required key property for a DSC resource.
/// </summary>
public bool Key { get; set; }
/// <summary>
/// Indicates the property is a required property for a DSC resource.
/// </summary>
public bool Mandatory { get; set; }
/// <summary>
/// Indicates the property is not a parameter to the DSC resource, but the
/// property will contain a value after the Get() method of the resource is called.
/// </summary>
public bool NotConfigurable { get; set; }
}
/// <summary>
/// Indication the configuration is for local configuration manager, also known as meta configuration.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class DscLocalConfigurationManagerAttribute : CmdletMetadataAttribute
{
}
/// <summary>
/// Contains information about a cmdlet's metadata.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public abstract class CmdletCommonMetadataAttribute : CmdletMetadataAttribute
{
/// <summary>
/// Gets or sets the cmdlet default parameter set.
/// </summary>
public string DefaultParameterSetName { get; set; }
/// <summary>
/// Gets or sets a Boolean value that indicates the Cmdlet supports ShouldProcess. By default
/// the value is false, meaning the cmdlet doesn't support ShouldProcess.
/// </summary>
public bool SupportsShouldProcess { get; set; } = false;
/// <summary>
/// Gets or sets a Boolean value that indicates the Cmdlet supports Paging. By default
/// the value is false, meaning the cmdlet doesn't support Paging.
/// </summary>
public bool SupportsPaging { get; set; } = false;
/// <summary>
/// Gets or sets a Boolean value that indicates the Cmdlet supports Transactions. By default
/// the value is false, meaning the cmdlet doesn't support Transactions.
/// </summary>
public bool SupportsTransactions
{
get
{
return _supportsTransactions;
}
set
{
#if !CORECLR
_supportsTransactions = value;
#else
// Disable 'SupportsTransactions' in CoreCLR
// No transaction supported on CSS due to the lack of System.Transactions namespace
_supportsTransactions = false;
#endif
}
}
private bool _supportsTransactions = false;
private ConfirmImpact _confirmImpact = ConfirmImpact.Medium;
/// <summary>
/// Gets or sets a ConfirmImpact value that indicates the "destructiveness" of the operation
/// and when it should be confirmed. This should only be used when SupportsShouldProcess is
/// specified.
/// </summary>
public ConfirmImpact ConfirmImpact
{
get => SupportsShouldProcess ? _confirmImpact : ConfirmImpact.None;
set => _confirmImpact = value;
}
/// <summary>
/// Gets or sets a HelpUri value that indicates the location of online help. This is used by
/// Get-Help to retrieve help content when -Online is specified.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")]
public string HelpUri { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the RemotingBehavior value that declares how this cmdlet should interact
/// with ambient remoting.
/// </summary>
public RemotingCapability RemotingCapability { get; set; } = RemotingCapability.PowerShell;
}
/// <summary>
/// Identifies a class as a cmdlet and specifies the verb and noun identifying this cmdlet.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public sealed class CmdletAttribute : CmdletCommonMetadataAttribute
{
/// <summary>
/// Gets the cmdlet noun.
/// </summary>
public string NounName { get; }
/// <summary>
/// Gets the cmdlet verb.
/// </summary>
public string VerbName { get; }
/// <summary>
/// Initializes a new instance of the CmdletAttribute class.
/// </summary>
/// <param name="verbName">Verb for the command.</param>
/// <param name="nounName">Noun for the command.</param>
/// <exception cref="ArgumentException">For invalid arguments.</exception>
public CmdletAttribute(string verbName, string nounName)
{
// NounName,VerbName have to be Non-Null strings
if (string.IsNullOrEmpty(nounName))
{
throw PSTraceSource.NewArgumentException(nameof(nounName));
}
if (string.IsNullOrEmpty(verbName))
{
throw PSTraceSource.NewArgumentException(nameof(verbName));
}
NounName = nounName;
VerbName = verbName;
}
}
/// <summary>
/// Identifies PowerShell script code as behaving like a cmdlet and hence uses cmdlet parameter binding
/// instead of script parameter binding.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class CmdletBindingAttribute : CmdletCommonMetadataAttribute
{
/// <summary>
/// When true, the script will auto-generate appropriate parameter metadata to support positional
/// parameters if the script hasn't already specified multiple parameter sets or specified positions
/// explicitly via the <see cref="ParameterAttribute"/>.
/// </summary>
public bool PositionalBinding { get; set; } = true;
}
/// <summary>
/// OutputTypeAttribute is used to specify the type of objects output by a cmdlet or script.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
[SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments")]
public sealed class OutputTypeAttribute : CmdletMetadataAttribute
{
/// <summary>
/// Construct the attribute from a <see>System.Type</see>
/// </summary>
internal OutputTypeAttribute(Type type)
{
Type = new[] { new PSTypeName(type) };
}
/// <summary>
/// Construct the attribute from a type name.
/// </summary>
internal OutputTypeAttribute(string typeName)
{
Type = new[] { new PSTypeName(typeName) };
}
/// <summary>
/// Construct the attribute from an array of <see>System.Type</see>
/// </summary>
/// <param name="type">The types output by the cmdlet.</param>
public OutputTypeAttribute(params Type[] type)
{
if (type?.Length > 0)
{
Type = new PSTypeName[type.Length];
for (int i = 0; i < type.Length; i++)
{
Type[i] = new PSTypeName(type[i]);
}
}
else
{
Type = Array.Empty<PSTypeName>();
}
}
/// <summary>
/// Construct the attribute from an array of names of types.
/// </summary>
/// <param name="type">The types output by the cmdlet.</param>
public OutputTypeAttribute(params string[] type)
{
if (type?.Length > 0)
{
Type = new PSTypeName[type.Length];
for (int i = 0; i < type.Length; i++)
{
Type[i] = new PSTypeName(type[i]);
}
}
else
{
Type = Array.Empty<PSTypeName>();
}
}
/// <summary>
/// The types specified by the attribute.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")]
public PSTypeName[] Type { get; }
/// <summary>
/// Attributes implemented by a provider can use:
/// [OutputType(ProviderCmdlet='cmdlet', typeof(...))]
/// To specify the provider specific objects returned for a given cmdlet.
/// </summary>
public string ProviderCmdlet { get; set; }
/// <summary>
/// The list of parameter sets this OutputType specifies.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] ParameterSetName
{
get => _parameterSetName ??= new[] { ParameterAttribute.AllParameterSets };
set => _parameterSetName = value;
}
private string[] _parameterSetName;
}
/// <summary>
/// This attribute is used on a dynamic assembly to mark it as one that is used to implement
/// a set of classes defined in a PowerShell script.
/// </summary>
[AttributeUsage(AttributeTargets.Assembly)]
public class DynamicClassImplementationAssemblyAttribute : Attribute
{
/// <summary>
/// The (possibly null) path to the file defining this class.
/// </summary>
public string ScriptFile { get; set; }
}
#endregion Misc Attributes
#region Parsing guidelines Attributes
/// <summary>
/// Declares an alternative name for a parameter, cmdlet, or function.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public sealed class AliasAttribute : ParsingBaseAttribute
{
internal string[] aliasNames;
/// <summary>
/// Gets the alias names passed to the constructor.
/// </summary>
public IList<string> AliasNames { get => this.aliasNames; }
/// <summary>
/// Initializes a new instance of the AliasAttribute class.
/// </summary>
/// <param name="aliasNames">The name for this alias.</param>
/// <exception cref="ArgumentException">For invalid arguments.</exception>
public AliasAttribute(params string[] aliasNames)
{
if (aliasNames == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(aliasNames));
}
this.aliasNames = aliasNames;
}
}
/// <summary>
/// Identifies parameters to Cmdlets.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)]
public sealed class ParameterAttribute : ParsingBaseAttribute
{
/// <summary>
/// ParameterSetName referring to all ParameterSets.
/// </summary>
public const string AllParameterSets = "__AllParameterSets";
/// <summary>
/// Initializes a new instance of the ParameterAttribute class.
/// </summary>
public ParameterAttribute()
{
}
/// <summary>
/// Initializes a new instance that is associated with an experimental feature.
/// </summary>
public ParameterAttribute(string experimentName, ExperimentAction experimentAction)
{
ExperimentalAttribute.ValidateArguments(experimentName, experimentAction);
ExperimentName = experimentName;
ExperimentAction = experimentAction;
}
private string _parameterSetName = ParameterAttribute.AllParameterSets;
private string _helpMessage;
private string _helpMessageBaseName;
private string _helpMessageResourceId;
#region Experimental Feature Related Properties
/// <summary>
/// Gets the name of the experimental feature this attribute is associated with.
/// </summary>
public string ExperimentName { get; }
/// <summary>
/// Gets the action for the engine to take when the experimental feature is enabled.
/// </summary>
public ExperimentAction ExperimentAction { get; }
internal bool ToHide => EffectiveAction == ExperimentAction.Hide;
internal bool ToShow => EffectiveAction == ExperimentAction.Show;
/// <summary>
/// Gets the effective action to take at run time.
/// </summary>
private ExperimentAction EffectiveAction
{
get
{
if (_effectiveAction == ExperimentAction.None)
{
_effectiveAction = ExperimentalFeature.GetActionToTake(ExperimentName, ExperimentAction);
}
return _effectiveAction;
}
}
private ExperimentAction _effectiveAction = default(ExperimentAction);
#endregion
/// <summary>
/// Gets or sets the parameter position.
/// If not set, the parameter is named.
/// </summary>
public int Position { get; set; } = int.MinValue;
/// <summary>
/// Gets or sets the name of the parameter set this parameter belongs to.
/// When it is not specified, <see cref="ParameterAttribute.AllParameterSets"/> is assumed.
/// </summary>
public string ParameterSetName
{
get => _parameterSetName;
set => _parameterSetName = string.IsNullOrEmpty(value) ? ParameterAttribute.AllParameterSets : value;
}
/// <summary>
/// Gets or sets a flag specifying if this parameter is Mandatory.
/// When it is not specified, false is assumed and the parameter is considered optional.
/// </summary>
public bool Mandatory { get; set; } = false;
/// <summary>
/// Gets or sets a flag that specifies that this parameter can take values from the incoming pipeline
/// object.
/// When it is not specified, false is assumed.
/// </summary>
public bool ValueFromPipeline { get; set; }
/// <summary>
/// Gets or sets a flag that specifies that this parameter can take values from a property in the
/// incoming pipeline object with the same name as the parameter or an alias of the parameter.
/// When it is not specified, false is assumed.
/// </summary>
public bool ValueFromPipelineByPropertyName { get; set; }
/// <summary>
/// Gets or sets a flag that specifies that the remaining command line parameters should be
/// associated with this parameter in the form of an array.
/// When it is not specified, false is assumed.
/// </summary>
public bool ValueFromRemainingArguments { get; set; } = false;
/// <summary>
/// Gets or sets a short description for this parameter, suitable for presentation as a tool tip.
/// </summary>
/// <exception cref="ArgumentException">For a null or empty value when setting.</exception>
public string HelpMessage
{
get => _helpMessage;
set
{
if (string.IsNullOrEmpty(value))
{
throw PSTraceSource.NewArgumentException(nameof(HelpMessage));
}
_helpMessage = value;
}
}
/// <summary>
/// Gets or sets the base name of the resource for a help message.
/// When this field is specified, HelpMessageResourceId must also be specified.
/// </summary>
/// <exception cref="ArgumentException">For a null or empty value when setting.</exception>
public string HelpMessageBaseName
{
get => _helpMessageBaseName;
set
{
if (string.IsNullOrEmpty(value))
{
throw PSTraceSource.NewArgumentException(nameof(HelpMessageBaseName));
}
_helpMessageBaseName = value;
}
}
/// <summary>
/// Gets or sets the Id of the resource for a help message.
/// When this field is specified, HelpMessageBaseName must also be specified.
/// </summary>
/// <exception cref="ArgumentException">For a null or empty value when setting.</exception>
public string HelpMessageResourceId
{
get => _helpMessageResourceId;
set
{
if (string.IsNullOrEmpty(value))
{
throw PSTraceSource.NewArgumentException(nameof(HelpMessageResourceId));
}
_helpMessageResourceId = value;
}
}
/// <summary>
/// Indicates that this parameter should not be shown to the user in this like intellisense
/// This is primarily to be used in functions that are implementing the logic for dynamic keywords.
/// </summary>
public bool DontShow { get; set; }
}
/// <summary>
/// Specifies PSTypeName of a cmdlet or function parameter.
/// </summary>
/// <remarks>
/// This attribute is used to restrict the type name of the parameter, when the type goes beyond the .NET type system.
/// For example one could say: [PSTypeName("System.Management.ManagementObject#root\cimv2\Win32_Process")]
/// to only allow Win32_Process objects to be bound to the parameter.
/// </remarks>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class PSTypeNameAttribute : Attribute
{
/// <summary>
/// </summary>
public string PSTypeName { get; }
/// <summary>
/// Creates a new PSTypeNameAttribute.
/// </summary>
/// <param name="psTypeName"></param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public PSTypeNameAttribute(string psTypeName)
{
if (string.IsNullOrEmpty(psTypeName))
{
throw PSTraceSource.NewArgumentException(nameof(psTypeName));
}
this.PSTypeName = psTypeName;
}
}
/// <summary>
/// Specifies that a parameter supports wildcards.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class SupportsWildcardsAttribute : ParsingBaseAttribute
{
}
/// <summary>
/// Specify a default value and/or help comment for a command parameter. This attribute
/// does not have any semantic meaning, it is simply an aid to tools to make it simpler
/// to know the true default value of a command parameter (which may or may not have
/// any correlation with, e.g., the backing store of the Parameter's property or field.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class PSDefaultValueAttribute : ParsingBaseAttribute
{
/// <summary>
/// Specify the default value of a command parameter. The PowerShell engine does not
/// use this value in any way, it exists for other tools that want to reflect on cmdlets.
/// </summary>
public object Value { get; set; }
/// <summary>
/// Specify the help string for the default value of a command parameter.
/// </summary>
public string Help { get; set; }
}
/// <summary>
/// Specify that the member is hidden for the purposes of cmdlets like Get-Member and that the
/// member is not displayed by default by Format-* cmdlets.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Event)]
public sealed class HiddenAttribute : ParsingBaseAttribute
{
}
#endregion Parsing guidelines Attributes
#region Data validate Attributes
/// <summary>
/// Validates that the length of each parameter argument's Length falls in the range specified by
/// <see cref="MinLength"/> and <see cref="MaxLength"/>.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class ValidateLengthAttribute : ValidateEnumeratedArgumentsAttribute
{
/// <summary>
/// Gets the attribute's minimum length.
/// </summary>
public int MinLength { get; }
/// <summary>
/// Gets the attribute's maximum length.
/// </summary>
public int MaxLength { get; }
/// <summary>
/// Validates that the length of each parameter argument's Length falls in the range specified
/// by <see cref="MinLength"/> and <see cref="MaxLength"/>.
/// </summary>
/// <param name="element">Object to validate.</param>
/// <exception cref="ValidationMetadataException">If <paramref name="element"/> is not a string
/// with length between minLength and maxLength</exception>
/// <exception cref="ArgumentException">For invalid arguments.</exception>
protected override void ValidateElement(object element)
{
if (element is not string objectString)
{
throw new ValidationMetadataException(
"ValidateLengthNotString",
null,
Metadata.ValidateLengthNotString);
}
int len = objectString.Length;
if (len < MinLength)
{
throw new ValidationMetadataException(
"ValidateLengthMinLengthFailure",
null,
Metadata.ValidateLengthMinLengthFailure,
MinLength, len);
}
if (len > MaxLength)
{
throw new ValidationMetadataException(
"ValidateLengthMaxLengthFailure",
null,
Metadata.ValidateLengthMaxLengthFailure,
MaxLength, len);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ValidateLengthAttribute"/> class.
/// </summary>
/// <param name="minLength">Minimum required length.</param>
/// <param name="maxLength">Maximum required length.</param>
/// <exception cref="ArgumentOutOfRangeException">For invalid arguments.</exception>
/// <exception cref="ValidationMetadataException">If maxLength is less than minLength.</exception>
public ValidateLengthAttribute(int minLength, int maxLength) : base()
{
if (minLength < 0)
{
throw PSTraceSource.NewArgumentOutOfRangeException(nameof(minLength), minLength);
}
if (maxLength <= 0)
{
throw PSTraceSource.NewArgumentOutOfRangeException(nameof(maxLength), maxLength);
}
if (maxLength < minLength)
{
throw new ValidationMetadataException(
"ValidateLengthMaxLengthSmallerThanMinLength",
null,
Metadata.ValidateLengthMaxLengthSmallerThanMinLength);
}
MinLength = minLength;
MaxLength = maxLength;
}
}
/// <summary>
/// Predefined range kind to use with ValidateRangeAttribute.
/// </summary>
public enum ValidateRangeKind
{
/// <summary>
/// Range is greater than 0.
/// </summary>
Positive,
/// <summary>
/// Range is greater than or equal to 0.
/// </summary>
NonNegative,
/// <summary>
/// Range is less than 0.
/// </summary>
Negative,
/// <summary>
/// Range is less than or equal to 0.
/// </summary>
NonPositive
}
/// <summary>
/// Validates that each parameter argument falls in the range specified by <see cref="MinRange"/>
/// and <see cref="MaxRange"/>.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class ValidateRangeAttribute : ValidateEnumeratedArgumentsAttribute
{
/// <summary>
/// Gets the attribute's minimum range.
/// </summary>
public object MinRange { get; }
private readonly IComparable _minComparable;
/// <summary>
/// Gets the attribute's maximum range.
/// </summary>
public object MaxRange { get; }
private readonly IComparable _maxComparable;
/// <summary>
/// The range values and the value to validate will all be converted to the promoted type.
/// If minRange and maxRange are the same type,
/// </summary>
private readonly Type _promotedType;
/// <summary>
/// Gets the name of the predefined range.
/// </summary>
internal ValidateRangeKind? RangeKind { get => _rangeKind; }
private readonly ValidateRangeKind? _rangeKind;
/// <summary>
/// Validates that each parameter argument falls in the range specified by <see cref="MinRange"/>
/// and <see cref="MaxRange"/>.
/// </summary>
/// <param name="element">Object to validate.</param>
/// <exception cref="ValidationMetadataException">
/// Thrown if the object to be validated does not implement <see cref="IComparable"/>,
/// if the element type is not the same as MinRange/MaxRange, or if the element is not between
/// MinRange and MaxRange.
/// </exception>
protected override void ValidateElement(object element)
{
if (element == null)
{
throw new ValidationMetadataException(
"ArgumentIsEmpty",
null,
Metadata.ValidateNotNullFailure);
}
var o = element as PSObject;
if (o != null)
{
element = o.BaseObject;
}
if (_rangeKind.HasValue)
{
ValidateRange(element, (ValidateRangeKind)_rangeKind);
}
else
{
ValidateRange(element);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ValidateRangeAttribute"/> class.
/// </summary>
/// <param name="minRange">Minimum value of the range allowed.</param>
/// <param name="maxRange">Maximum value of the range allowed.</param>
/// <exception cref="ArgumentNullException">For invalid arguments.</exception>
/// <exception cref="ValidationMetadataException">
/// if <paramref name="maxRange"/> has a different type than <paramref name="minRange"/>
/// if <paramref name="maxRange"/> is smaller than <paramref name="minRange"/>
/// if <paramref name="maxRange"/>, <paramref name="minRange"/> are not <see cref="IComparable"/>
/// </exception>
public ValidateRangeAttribute(object minRange, object maxRange) : base()
{
if (minRange == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(minRange));
}
if (maxRange == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(maxRange));
}
if (maxRange.GetType() != minRange.GetType())
{
bool failure = true;
_promotedType = GetCommonType(minRange.GetType(), maxRange.GetType());
if (_promotedType != null)
{
if (LanguagePrimitives.TryConvertTo(minRange, _promotedType, out object minResultValue)
&& LanguagePrimitives.TryConvertTo(maxRange, _promotedType, out object maxResultValue))
{
minRange = minResultValue;
maxRange = maxResultValue;
failure = false;
}
}
if (failure)
{
throw new ValidationMetadataException(
"MinRangeNotTheSameTypeOfMaxRange",
null,
Metadata.ValidateRangeMinRangeMaxRangeType,
minRange.GetType().Name, maxRange.GetType().Name);
}
}
else
{
_promotedType = minRange.GetType();
}
// minRange and maxRange have the same type, so we just need to check one of them
_minComparable = minRange as IComparable;
if (_minComparable == null)
{
throw new ValidationMetadataException(
"MinRangeNotIComparable",
null,
Metadata.ValidateRangeNotIComparable);
}
_maxComparable = maxRange as IComparable;
Diagnostics.Assert(_maxComparable != null, "maxComparable comes from a type that is IComparable");
// Thanks to the IComparable test above this will not throw. They have the same type and are IComparable.
if (_minComparable.CompareTo(maxRange) > 0)
{
throw new ValidationMetadataException(
"MaxRangeSmallerThanMinRange",
null,
Metadata.ValidateRangeMaxRangeSmallerThanMinRange);
}
MinRange = minRange;
MaxRange = maxRange;
}
/// <summary>
/// Initializes a new instance of the <see cref="ValidateRangeAttribute"/> class.
/// This constructor uses a predefined <see cref="ValidateRangeKind"/>.
/// </summary>
public ValidateRangeAttribute(ValidateRangeKind kind) : base()
{
_rangeKind = kind;
}
private static void ValidateRange(object element, ValidateRangeKind rangeKind)
{
if (element is TimeSpan ts)
{
ValidateTimeSpanRange(ts, rangeKind);
return;
}
Type commonType = GetCommonType(typeof(int), element.GetType());
if (commonType == null)
{
throw new ValidationMetadataException(
"ValidationRangeElementType",
innerException: null,
Metadata.ValidateRangeElementType,
element.GetType().Name,
nameof(Int32));
}
object resultValue;
IComparable dynamicZero = 0;
if (LanguagePrimitives.TryConvertTo(element, commonType, out resultValue))
{
element = resultValue;
if (LanguagePrimitives.TryConvertTo(0, commonType, out resultValue))
{
dynamicZero = (IComparable)resultValue;
}
}
else
{
throw new ValidationMetadataException(
"ValidationRangeElementType",
null,
Metadata.ValidateRangeElementType,
element.GetType().Name,
commonType.Name);
}
switch (rangeKind)
{
case ValidateRangeKind.Positive:
if (dynamicZero.CompareTo(element) >= 0)
{
throw new ValidationMetadataException(
"ValidateRangePositiveFailure",
null,
Metadata.ValidateRangePositiveFailure,
element.ToString());
}
break;
case ValidateRangeKind.NonNegative:
if (dynamicZero.CompareTo(element) > 0)
{
throw new ValidationMetadataException(
"ValidateRangeNonNegativeFailure",
null,
Metadata.ValidateRangeNonNegativeFailure,
element.ToString());
}
break;
case ValidateRangeKind.Negative:
if (dynamicZero.CompareTo(element) <= 0)
{
throw new ValidationMetadataException(
"ValidateRangeNegativeFailure",
null,
Metadata.ValidateRangeNegativeFailure,
element.ToString());
}
break;
case ValidateRangeKind.NonPositive:
if (dynamicZero.CompareTo(element) < 0)
{
throw new ValidationMetadataException(
"ValidateRangeNonPositiveFailure",
null,
Metadata.ValidateRangeNonPositiveFailure,
element.ToString());
}
break;
}
}
private void ValidateRange(object element)
{
// MinRange and MaxRange have the same type, so we just need to compare to one of them.
if (element.GetType() != _promotedType)
{
if (LanguagePrimitives.TryConvertTo(element, _promotedType, out object resultValue))
{
element = resultValue;
}
else
{
throw new ValidationMetadataException(
"ValidationRangeElementType",
null,
Metadata.ValidateRangeElementType,
element.GetType().Name,
MinRange.GetType().Name);
}
}
// They are the same type and are all IComparable, so this should not throw
if (_minComparable.CompareTo(element) > 0)
{
throw new ValidationMetadataException(
"ValidateRangeTooSmall",
null,
Metadata.ValidateRangeSmallerThanMinRangeFailure,
element.ToString(),
MinRange.ToString());
}
if (_maxComparable.CompareTo(element) < 0)
{
throw new ValidationMetadataException(
"ValidateRangeTooBig",
null,
Metadata.ValidateRangeGreaterThanMaxRangeFailure,
element.ToString(),
MaxRange.ToString());
}
}
private static void ValidateTimeSpanRange(TimeSpan element, ValidateRangeKind rangeKind)
{
TimeSpan zero = TimeSpan.Zero;
switch (rangeKind)
{
case ValidateRangeKind.Positive:
if (zero.CompareTo(element) >= 0)
{
throw new ValidationMetadataException(
"ValidateRangePositiveFailure",
null,
Metadata.ValidateRangePositiveFailure,
element.ToString());
}
break;
case ValidateRangeKind.NonNegative:
if (zero.CompareTo(element) > 0)
{
throw new ValidationMetadataException(
"ValidateRangeNonNegativeFailure",
null,
Metadata.ValidateRangeNonNegativeFailure,
element.ToString());
}
break;
case ValidateRangeKind.Negative:
if (zero.CompareTo(element) <= 0)
{
throw new ValidationMetadataException(
"ValidateRangeNegativeFailure",
null,
Metadata.ValidateRangeNegativeFailure,
element.ToString());
}
break;
case ValidateRangeKind.NonPositive:
if (zero.CompareTo(element) < 0)
{
throw new ValidationMetadataException(
"ValidateRangeNonPositiveFailure",
null,
Metadata.ValidateRangeNonPositiveFailure,
element.ToString());
}
break;
}
}
private static Type GetCommonType(Type minType, Type maxType)
{
Type resultType = null;
TypeCode minTypeCode = LanguagePrimitives.GetTypeCode(minType);
TypeCode maxTypeCode = LanguagePrimitives.GetTypeCode(maxType);
TypeCode opTypeCode = (int)minTypeCode >= (int)maxTypeCode ? minTypeCode : maxTypeCode;
if ((int)opTypeCode <= (int)TypeCode.Int32)
{
resultType = typeof(int);
}
else if ((int)opTypeCode <= (int)TypeCode.UInt32)
{
// If one of the operands is signed, we need to promote to double if the value is negative.
// We aren't checking the value, so we unconditionally promote to double.
resultType = LanguagePrimitives.IsSignedInteger(minTypeCode) || LanguagePrimitives.IsSignedInteger(maxTypeCode)
? typeof(double) : typeof(uint);
}
else if ((int)opTypeCode <= (int)TypeCode.Int64)
{
resultType = typeof(long);
}
else if ((int)opTypeCode <= (int)TypeCode.UInt64)
{
// If one of the operands is signed, we need to promote to double if the value is negative.
// We aren't checking the value, so we unconditionally promote to double.
resultType = LanguagePrimitives.IsSignedInteger(minTypeCode) || LanguagePrimitives.IsSignedInteger(maxTypeCode)
? typeof(double) : typeof(ulong);
}
else if (opTypeCode == TypeCode.Decimal)
{
resultType = typeof(decimal);
}
else if (opTypeCode == TypeCode.Single || opTypeCode == TypeCode.Double)
{
resultType = typeof(double);
}
return resultType;
}
/// <summary>
/// Returns only the elements that passed the attribute's validation.
/// </summary>
/// <param name="elementsToValidate">The objects to validate.</param>
internal IEnumerable GetValidatedElements(IEnumerable elementsToValidate)
{
foreach (var el in elementsToValidate)
{
try
{
ValidateElement(el);
}
catch (ValidationMetadataException)
{
// Element was not in range - drop
continue;
}
yield return el;
}
}
}
/// <summary>
/// Validates that each parameter argument matches the <see cref="RegexPattern"/>.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class ValidatePatternAttribute : ValidateEnumeratedArgumentsAttribute
{
/// <summary>
/// Gets the Regex pattern to be used in the validation.
/// </summary>
public string RegexPattern { get; }
/// <summary>
/// Gets or sets the Regex options to be used in the validation.
/// </summary>
public RegexOptions Options { get; set; } = RegexOptions.IgnoreCase;
/// <summary>
/// Gets or sets the custom error message pattern that is displayed to the user.
/// The text representation of the object being validated and the validating regex is passed as
/// the first and second formatting parameters to the ErrorMessage formatting pattern.
/// <c>
/// <code>
/// [ValidatePattern("\s+", ErrorMessage="The text '{0}' did not pass validation of regex '{1}'")]
/// </code>
/// </c>
/// </summary>
public string ErrorMessage { get; set; }
/// <summary>
/// Validates that each parameter argument matches the RegexPattern.
/// </summary>
/// <param name="element">Object to validate.</param>
/// <exception cref="ValidationMetadataException">
/// If <paramref name="element"/> is not a string that matches the pattern, and for invalid arguments.
/// </exception>
protected override void ValidateElement(object element)
{
if (element == null)
{
throw new ValidationMetadataException(
"ArgumentIsEmpty",
null,
Metadata.ValidateNotNullFailure);
}
string objectString = element.ToString();
var regex = new Regex(RegexPattern, Options);
Match match = regex.Match(objectString);
if (!match.Success)
{
var errorMessageFormat = string.IsNullOrEmpty(ErrorMessage)
? Metadata.ValidatePatternFailure
: ErrorMessage;
throw new ValidationMetadataException(
"ValidatePatternFailure",
null,
errorMessageFormat,
objectString, RegexPattern);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ValidatePatternAttribute"/> class.
/// </summary>
/// <param name="regexPattern">Pattern string to match.</param>
/// <exception cref="ArgumentException">For invalid arguments.</exception>
public ValidatePatternAttribute(string regexPattern)
{
if (string.IsNullOrEmpty(regexPattern))
{
throw PSTraceSource.NewArgumentException(nameof(regexPattern));
}
RegexPattern = regexPattern;
}
}
/// <summary>
/// Class for validating against a script block.
/// </summary>
public sealed class ValidateScriptAttribute : ValidateEnumeratedArgumentsAttribute
{
/// <summary>
/// Gets or sets the custom error message that is displayed to the user.
/// The item being validated and the validating scriptblock is passed as the first and second
/// formatting argument.
/// <c>
/// <code>
/// [ValidateScript("$_ % 2", ErrorMessage = "The item '{0}' did not pass validation of script '{1}'")]
/// </code>
/// </c>
/// </summary>
public string ErrorMessage { get; set; }
/// <summary>
/// Gets the scriptblock to be used in the validation.
/// </summary>
public ScriptBlock ScriptBlock { get; }
/// <summary>
/// Validates that each parameter argument matches the scriptblock.
/// </summary>
/// <param name="element">Object to validate.</param>
/// <exception cref="ValidationMetadataException">If <paramref name="element"/> is invalid.</exception>
protected override void ValidateElement(object element)
{
if (element == null)
{
throw new ValidationMetadataException(
"ArgumentIsEmpty",
null,
Metadata.ValidateNotNullFailure);
}
object result = ScriptBlock.DoInvokeReturnAsIs(
useLocalScope: true,
errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe,
dollarUnder: LanguagePrimitives.AsPSObjectOrNull(element),
input: AutomationNull.Value,
scriptThis: AutomationNull.Value,
args: Array.Empty<object>());
if (!LanguagePrimitives.IsTrue(result))
{
var errorMessageFormat = string.IsNullOrEmpty(ErrorMessage)
? Metadata.ValidateScriptFailure
: ErrorMessage;
throw new ValidationMetadataException(
"ValidateScriptFailure",
null,
errorMessageFormat,
element, ScriptBlock);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ValidateScriptAttribute"/> class.
/// </summary>
/// <param name="scriptBlock">Scriptblock to match.</param>
/// <exception cref="ArgumentException">For invalid arguments.</exception>
public ValidateScriptAttribute(ScriptBlock scriptBlock)
{
if (scriptBlock == null)
{
throw PSTraceSource.NewArgumentException(nameof(scriptBlock));
}
ScriptBlock = scriptBlock;
}
}
/// <summary>
/// Validates that the parameter argument count is in the specified range.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class ValidateCountAttribute : ValidateArgumentsAttribute
{
/// <summary>
/// Gets the minimum length of this attribute.
/// </summary>
public int MinLength { get; }
/// <summary>
/// Gets the maximum length of this attribute.
/// </summary>
public int MaxLength { get; }
/// <summary>
/// Validates that the parameter argument count is in the specified range.
/// </summary>
/// <param name="arguments">Object to validate.</param>
/// <param name="engineIntrinsics">
/// The engine APIs for the context under which the validation is being evaluated.
/// </param>
/// <exception cref="ValidationMetadataException">
/// if the element is none of <see cref="ICollection"/>, <see cref="IEnumerable"/>,
/// <see cref="IList"/>, <see cref="IEnumerator"/>
/// if the element's length is not between <see cref="MinLength"/> and <see cref="MaxLength"/>
/// </exception>
protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics)
{
int len = 0;
if (arguments == null || arguments == AutomationNull.Value)
{
// treat a nul list the same as an empty list
// with a count of zero.
len = 0;
}
else if (arguments is IList il)
{
len = il.Count;
}
else if (arguments is ICollection ic)
{
len = ic.Count;
}
else if (arguments is IEnumerable ie)
{
IEnumerator e = ie.GetEnumerator();
while (e.MoveNext())
{
len++;
}
}
else if (arguments is IEnumerator enumerator)
{
while (enumerator.MoveNext())
{
len++;
}
}
else
{
// No conversion succeeded so throw an exception...
throw new ValidationMetadataException(
"NotAnArrayParameter",
null,
Metadata.ValidateCountNotInArray);
}
if (MinLength == MaxLength && len != MaxLength)
{
throw new ValidationMetadataException(
"ValidateCountExactFailure",
null,
Metadata.ValidateCountExactFailure,
MaxLength, len);
}
if (len < MinLength || len > MaxLength)
{
throw new ValidationMetadataException(
"ValidateCountMinMaxFailure",
null,
Metadata.ValidateCountMinMaxFailure,
MinLength, MaxLength, len);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ValidateCountAttribute"/> class.
/// </summary>
/// <param name="minLength">Minimum number of values required.</param>
/// <param name="maxLength">Maximum number of values required.</param>
/// <exception cref="ArgumentOutOfRangeException">For invalid arguments.</exception>
/// <exception cref="ValidationMetadataException">
/// if <paramref name="minLength"/> is greater than <paramref name="maxLength"/>
/// </exception>
public ValidateCountAttribute(int minLength, int maxLength)
{
if (minLength < 0)
{
throw PSTraceSource.NewArgumentOutOfRangeException(nameof(minLength), minLength);
}
if (maxLength <= 0)
{
throw PSTraceSource.NewArgumentOutOfRangeException(nameof(maxLength), maxLength);
}
if (maxLength < minLength)
{
throw new ValidationMetadataException(
"ValidateRangeMaxLengthSmallerThanMinLength",
null,
Metadata.ValidateCountMaxLengthSmallerThanMinLength);
}
MinLength = minLength;
MaxLength = maxLength;
}
}
/// <summary>
/// Optional base class for <see cref="IValidateSetValuesGenerator"/> implementations that want a default
/// implementation to cache valid values.
/// </summary>
public abstract class CachedValidValuesGeneratorBase : IValidateSetValuesGenerator
{
// Cached valid values.
private string[] _validValues;
private readonly int _validValuesCacheExpiration;
/// <summary>
/// Initializes a new instance of the <see cref="CachedValidValuesGeneratorBase"/> class.
/// </summary>
/// <param name="cacheExpirationInSeconds">
/// Sets a time interval in seconds to reset the <see cref="_validValues"/> dynamic valid values cache.
/// </param>
protected CachedValidValuesGeneratorBase(int cacheExpirationInSeconds)
{
_validValuesCacheExpiration = cacheExpirationInSeconds;
}
/// <summary>
/// Abstract method to generate a valid values.
/// </summary>
public abstract string[] GenerateValidValues();
/// <summary>
/// Get a valid values.
/// </summary>
public string[] GetValidValues()
{
// Because we have a background task to clear the cache by '_validValues = null'
// we use the local variable to exclude a race condition.
var validValuesLocal = _validValues;
if (validValuesLocal != null)
{
return validValuesLocal;
}
var validValuesNoCache = GenerateValidValues();
if (validValuesNoCache == null)
{
throw new ValidationMetadataException(
"ValidateSetGeneratedValidValuesListIsNull",
null,
Metadata.ValidateSetGeneratedValidValuesListIsNull);
}
if (_validValuesCacheExpiration > 0)
{
_validValues = validValuesNoCache;
Task.Delay(_validValuesCacheExpiration * 1000).ContinueWith((task) => _validValues = null);
}
return validValuesNoCache;
}
}
/// <summary>
/// Validates that each parameter argument is present in a specified set.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class ValidateSetAttribute : ValidateEnumeratedArgumentsAttribute
{
// We can use either static '_validValues' or dynamic valid values list generated by instance
// of 'validValuesGenerator'.
private readonly string[] _validValues;
private readonly IValidateSetValuesGenerator validValuesGenerator = null;
// The valid values generator cache works across 'ValidateSetAttribute' instances.
private static readonly ConcurrentDictionary<Type, IValidateSetValuesGenerator> s_ValidValuesGeneratorCache =
new ConcurrentDictionary<Type, IValidateSetValuesGenerator>();
/// <summary>
/// Gets or sets the custom error message that is displayed to the user.
/// The item being validated and a text representation of the validation set is passed as the
/// first and second formatting argument to the <see cref="ErrorMessage"/> formatting pattern.
/// <c>
/// <code>
/// [ValidateSet("A","B","C", ErrorMessage="The item '{0}' is not part of the set '{1}'.")
/// </code>
/// </c>
/// </summary>
public string ErrorMessage { get; set; }
/// <summary>
/// Gets a flag specifying if we should ignore the case when performing string comparison.
/// The default is true.
/// </summary>
public bool IgnoreCase { get; set; } = true;
/// <summary>
/// Gets the valid values in the set.
/// </summary>
[SuppressMessage("Design", "CA1065:Do not raise exceptions in unexpected locations", Justification = "<Pending>")]
public IList<string> ValidValues
{
get
{
if (validValuesGenerator == null)
{
return _validValues;
}
var validValuesLocal = validValuesGenerator.GetValidValues();
if (validValuesLocal == null)
{
throw new ValidationMetadataException(
"ValidateSetGeneratedValidValuesListIsNull",
null,
Metadata.ValidateSetGeneratedValidValuesListIsNull);
}
return validValuesLocal;
}
}
/// <summary>
/// Validates that each parameter argument is present in the specified set.
/// </summary>
/// <param name="element">Object to validate.</param>
/// <exception cref="ValidationMetadataException">
/// if element is not in the set
/// for invalid argument
/// </exception>
protected override void ValidateElement(object element)
{
if (element == null)
{
throw new ValidationMetadataException(
"ArgumentIsEmpty",
null,
Metadata.ValidateNotNullFailure);
}
string objString = element.ToString();
foreach (string setString in ValidValues)
{
if (CultureInfo.InvariantCulture.CompareInfo.Compare(
setString,
objString,
IgnoreCase ? CompareOptions.IgnoreCase : CompareOptions.None) == 0)
{
return;
}
}
var errorMessageFormat = string.IsNullOrEmpty(ErrorMessage) ? Metadata.ValidateSetFailure : ErrorMessage;
throw new ValidationMetadataException(
"ValidateSetFailure",
null,
errorMessageFormat,
element.ToString(), SetAsString());
}
private string SetAsString() => string.Join(CultureInfo.CurrentUICulture.TextInfo.ListSeparator, ValidValues);
/// <summary>
/// Initializes a new instance of the <see cref="ValidateSetAttribute"/> class.
/// </summary>
/// <param name="validValues">List of valid values.</param>
/// <exception cref="ArgumentNullException">For null arguments.</exception>
/// <exception cref="ArgumentOutOfRangeException">For invalid arguments.</exception>
public ValidateSetAttribute(params string[] validValues)
{
if (validValues == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(validValues));
}
if (validValues.Length == 0)
{
throw PSTraceSource.NewArgumentOutOfRangeException(nameof(validValues), validValues);
}
_validValues = validValues;
}
/// <summary>
/// Initializes a new instance of the <see cref="ValidateSetAttribute"/> class.
/// Valid values are returned dynamically from a custom class implementing
/// <see cref="IValidateSetValuesGenerator"/>
/// </summary>
/// <param name="valuesGeneratorType">
/// Class that implements the <see cref="IValidateSetValuesGenerator"/> interface.
/// </param>
/// <exception cref="ArgumentException">For null arguments.</exception>
public ValidateSetAttribute(Type valuesGeneratorType)
{
// We check 'IsNotPublic' because we don't want allow 'Activator.CreateInstance' create an
// instance of non-public type.
if (!typeof(IValidateSetValuesGenerator).IsAssignableFrom(
valuesGeneratorType) || valuesGeneratorType.IsNotPublic)
{
throw PSTraceSource.NewArgumentException(nameof(valuesGeneratorType));
}
// Add a valid values generator to the cache.
// We don't cache valid values; we expect that valid values will be cached in the generator.
validValuesGenerator = s_ValidValuesGeneratorCache.GetOrAdd(
valuesGeneratorType, static (key) => (IValidateSetValuesGenerator)Activator.CreateInstance(key));
}
}
/// <summary>
/// Allows dynamically generate set of values for <see cref="ValidateSetAttribute"/>
/// </summary>
#nullable enable
public interface IValidateSetValuesGenerator
{
/// <summary>
/// Gets valid values.
/// </summary>
/// <returns>A non-null array of non-null strings.</returns>
string[] GetValidValues();
}
#nullable restore
/// <summary>
/// Validates that each parameter argument is Trusted data.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class ValidateTrustedDataAttribute : ValidateArgumentsAttribute
{
/// <summary>
/// Validates that the parameter argument is not untrusted.
/// </summary>
/// <param name="arguments">Object to validate.</param>
/// <param name="engineIntrinsics">
/// The engine APIs for the context under which the validation is being evaluated.
/// </param>
/// <exception cref="ValidationMetadataException">
/// if the argument is untrusted.
/// </exception>
protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics)
{
if (ExecutionContext.HasEverUsedConstrainedLanguage &&
engineIntrinsics.SessionState.Internal.ExecutionContext.LanguageMode == PSLanguageMode.FullLanguage)
{
if (ExecutionContext.IsMarkedAsUntrusted(arguments))
{
if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit)
{
throw new ValidationMetadataException(
"ValidateTrustedDataFailure",
null,
Metadata.ValidateTrustedDataFailure,
arguments);
}
SystemPolicy.LogWDACAuditMessage(
context: null,
title: Metadata.WDACParameterArgNotTrustedLogTitle,
message: StringUtil.Format(Metadata.WDACParameterArgNotTrustedMessage, arguments),
fqid: "ParameterArgumentNotTrusted",
dropIntoDebugger: true);
}
}
}
}
#region Allow
/// <summary>
/// Allows a NULL as the argument to a mandatory parameter.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class AllowNullAttribute : CmdletMetadataAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="AllowNullAttribute"/> class.
/// </summary>
public AllowNullAttribute() { }
}
/// <summary>
/// Allows an empty string as the argument to a mandatory string parameter.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class AllowEmptyStringAttribute : CmdletMetadataAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="AllowEmptyStringAttribute"/> class.
/// </summary>
public AllowEmptyStringAttribute() { }
}
/// <summary>
/// Allows an empty collection as the argument to a mandatory collection parameter.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class AllowEmptyCollectionAttribute : CmdletMetadataAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="AllowEmptyCollectionAttribute"/> class.
/// </summary>
public AllowEmptyCollectionAttribute() { }
}
#endregion Allow
#region Path validation attributes
/// <summary>
/// Validates that the path has an approved root drive.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class ValidateDriveAttribute : ValidateArgumentsAttribute
{
private readonly string[] _validRootDrives;
/// <summary>
/// Gets the values in the set.
/// </summary>
public IList<string> ValidRootDrives { get => _validRootDrives; }
/// <summary>
/// Initializes a new instance of the <see cref="ValidateDriveAttribute"/> class.
/// </summary>
/// <param name="validRootDrives">List of approved root drives for path.</param>
public ValidateDriveAttribute(params string[] validRootDrives)
{
if (validRootDrives == null)
{
throw PSTraceSource.NewArgumentException(nameof(validRootDrives));
}
_validRootDrives = validRootDrives;
}
/// <summary>
/// Validates path argument.
/// </summary>
/// <param name="arguments">Object to validate.</param>
/// <param name="engineIntrinsics">Engine intrinsics.</param>
protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics)
{
if (arguments == null)
{
throw new ValidationMetadataException(
"PathArgumentIsEmpty",
null,
Metadata.ValidateNotNullFailure);
}
if (arguments is not string path)
{
throw new ValidationMetadataException(
"PathArgumentIsNotValid",
null,
Metadata.ValidateDrivePathArgNotString);
}
var resolvedPath = engineIntrinsics.SessionState.Internal.Globber.GetProviderPath(
path: path,
context: new CmdletProviderContext(engineIntrinsics.SessionState.Internal.ExecutionContext),
isTrusted: true,
provider: out ProviderInfo providerInfo,
drive: out PSDriveInfo driveInfo);
string rootDrive = driveInfo.Name;
if (string.IsNullOrEmpty(rootDrive))
{
throw new ValidationMetadataException(
"PathArgumentNoRoot",
null,
Metadata.ValidateDrivePathNoRoot);
}
bool rootFound = false;
foreach (var validDrive in _validRootDrives)
{
if (rootDrive.Equals(validDrive, StringComparison.OrdinalIgnoreCase))
{
rootFound = true;
break;
}
}
if (!rootFound)
{
throw new ValidationMetadataException(
"PathRootInvalid",
null,
Metadata.ValidateDrivePathFailure,
rootDrive, ValidDriveListAsString());
}
}
private string ValidDriveListAsString()
{
return string.Join(CultureInfo.CurrentUICulture.TextInfo.ListSeparator, _validRootDrives);
}
}
/// <summary>
/// Validates that the path parameter is a User drive.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class ValidateUserDriveAttribute : ValidateDriveAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="ValidateUserDriveAttribute"/> class.
/// </summary>
public ValidateUserDriveAttribute()
: base(new string[] { "User" })
{
}
}
#endregion
#region NULL validation attributes
/// <summary>
/// Base type of Null Validation attributes.
/// </summary>
public abstract class NullValidationAttributeBase : ValidateArgumentsAttribute
{
/// <summary>
/// Check if the argument type is a collection.
/// </summary>
protected bool IsArgumentCollection(Type argumentType, out bool isElementValueType)
{
isElementValueType = false;
var information = new ParameterCollectionTypeInformation(argumentType);
switch (information.ParameterCollectionType)
{
// If 'arguments' is an array, or implement 'IList', or implement 'ICollection<>'
// then we continue to check each element of the collection.
case ParameterCollectionType.Array:
case ParameterCollectionType.IList:
case ParameterCollectionType.ICollectionGeneric:
Type elementType = information.ElementType;
isElementValueType = elementType != null && elementType.IsValueType;
return true;
default:
return false;
}
}
}
/// <summary>
/// Validates that the parameters's argument is not null.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class ValidateNotNullAttribute : NullValidationAttributeBase
{
/// <summary>
/// Verifies the argument is not null. If the argument is a collection, verifies that each
/// element in the collection is not null.
/// </summary>
/// <param name="arguments">The arguments to verify.</param>
/// <param name="engineIntrinsics">
/// The engine APIs for the context under which the validation is being evaluated.
/// </param>
/// <returns>
/// true if the argument is valid.
/// </returns>
/// <exception cref="ValidationMetadataException">
/// if element is null or a collection with a null element
/// </exception>
protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics)
{
if (LanguagePrimitives.IsNull(arguments))
{
throw new ValidationMetadataException(
"ArgumentIsNull",
null,
Metadata.ValidateNotNullFailure);
}
else if (IsArgumentCollection(arguments.GetType(), out bool isElementValueType))
{
// If the element of the collection is of value type, then no need to check for null
// because a value-type value cannot be null.
if (isElementValueType)
{
return;
}
IEnumerator enumerator = LanguagePrimitives.GetEnumerator(arguments);
while (enumerator.MoveNext())
{
object element = enumerator.Current;
if (LanguagePrimitives.IsNull(element))
{
throw new ValidationMetadataException(
"ArgumentIsNull",
null,
Metadata.ValidateNotNullCollectionFailure);
}
}
}
}
}
/// <summary>
/// Validates that the parameters's argument is not null, is not an empty string or a
/// string with white-space characters only, and is not an empty collection.
/// </summary>
public abstract class ValidateNotNullOrAttributeBase : NullValidationAttributeBase
{
/// <summary>
/// Used to check the type of string validation to perform.
/// </summary>
protected readonly bool _checkWhiteSpace;
/// <summary>
/// Validates that the parameters's argument is not null, is not an empty string or a
/// string with white-space characters only, and is not an empty collection.
/// </summary>
protected ValidateNotNullOrAttributeBase(bool checkWhiteSpace)
{
_checkWhiteSpace = checkWhiteSpace;
}
/// <summary>
/// Validates that the parameters's argument is not null, is not an empty string, and is
/// not an empty collection. If argument is a collection, each argument is verified.
/// It can also validate that the parameters's argument is not a string that consists
/// only of white-space characters.
/// </summary>
/// <param name="arguments">The arguments to verify.</param>
/// <param name="engineIntrinsics">
/// The engine APIs for the context under which the validation is being evaluated.
/// </param>
/// <exception cref="ValidationMetadataException">
/// if the arguments are not valid.
/// </exception>
protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics)
{
if (LanguagePrimitives.IsNull(arguments))
{
throw new ValidationMetadataException(
"ArgumentIsNull",
null,
Metadata.ValidateNotNullOrEmptyFailure);
}
else if (arguments is string str)
{
if (_checkWhiteSpace)
{
if (string.IsNullOrWhiteSpace(str))
{
throw new ValidationMetadataException(
"ArgumentIsEmptyOrWhiteSpace",
null,
Metadata.ValidateNotNullOrWhiteSpaceFailure);
}
}
else if (string.IsNullOrEmpty(str))
{
throw new ValidationMetadataException(
"ArgumentIsEmpty",
null,
Metadata.ValidateNotNullOrEmptyFailure);
}
}
else if (IsArgumentCollection(arguments.GetType(), out bool isElementValueType))
{
bool isEmpty = true;
IEnumerator enumerator = LanguagePrimitives.GetEnumerator(arguments);
if (enumerator.MoveNext())
{
isEmpty = false;
}
// If the element of the collection is of value type, then no need to check for null
// because a value-type value cannot be null.
if (!isEmpty && !isElementValueType)
{
do
{
object element = enumerator.Current;
if (LanguagePrimitives.IsNull(element))
{
throw new ValidationMetadataException(
"ArgumentIsNull",
null,
Metadata.ValidateNotNullOrEmptyCollectionFailure);
}
if (element is string elementAsString)
{
if (_checkWhiteSpace)
{
if (string.IsNullOrWhiteSpace(elementAsString))
{
throw new ValidationMetadataException(
"ArgumentCollectionContainsEmptyOrWhiteSpace",
null,
Metadata.ValidateNotNullOrWhiteSpaceCollectionFailure);
}
}
else if (string.IsNullOrEmpty(elementAsString))
{
throw new ValidationMetadataException(
"ArgumentCollectionContainsEmpty",
null,
Metadata.ValidateNotNullOrEmptyCollectionFailure);
}
}
} while (enumerator.MoveNext());
}
if (isEmpty)
{
throw new ValidationMetadataException(
"ArgumentIsEmpty",
null,
Metadata.ValidateNotNullOrEmptyCollectionFailure);
}
}
else if (arguments is IDictionary dict)
{
if (dict.Count == 0)
{
throw new ValidationMetadataException(
"ArgumentIsEmpty",
null,
Metadata.ValidateNotNullOrEmptyCollectionFailure);
}
}
}
}
/// <summary>
/// Validates that the parameters's argument is not null, is not an empty string, and is
/// not an empty collection. If argument is a collection, each argument is verified.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class ValidateNotNullOrEmptyAttribute : ValidateNotNullOrAttributeBase
{
/// <summary>
/// Validates that the parameters's argument is not null, is not an empty string, and is
/// not an empty collection. If argument is a collection, each argument is verified.
/// </summary>
public ValidateNotNullOrEmptyAttribute()
: base(checkWhiteSpace: false)
{
}
}
/// <summary>
/// Validates that the parameters's argument is not null, is not an empty string, is not a string that
/// consists only of white-space characters, and is not an empty collection. If argument is a collection,
/// each argument is verified.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class ValidateNotNullOrWhiteSpaceAttribute : ValidateNotNullOrAttributeBase
{
/// <summary>
/// Validates that the parameters's argument is not null, is not an empty string, is not a string that
/// consists only of white-space characters, and is not an empty collection. If argument is a collection,
/// each argument is verified.
/// </summary>
public ValidateNotNullOrWhiteSpaceAttribute()
: base(checkWhiteSpace: true)
{
}
}
#endregion NULL validation attributes
#endregion Data validate Attributes
#region Data Generation Attributes
/// <summary>
/// Serves as the base class for attributes that perform argument transformation.
/// </summary>
/// <remarks>
/// Argument transformation attributes can be attached to <see cref="Cmdlet"/> and
/// <see cref="Provider.CmdletProvider"/> parameters to automatically transform the argument
/// value in some fashion. The transformation might change the object, convert the type, or
/// even load a file or AD object based on the name. Existing argument transformation attributes
/// include <see cref="ArgumentTypeConverterAttribute"/>.
/// Custom argument transformation attributes should derive from
/// <see cref="ArgumentTransformationAttribute"/> and override the
/// <see cref="ArgumentTransformationAttribute.Transform"/> abstract method, after which they
/// can apply the attribute to their parameters.
/// It is also recommended to override <see cref="object.ToString"/> to return a readable
/// string similar to the attribute declaration, for example "[ValidateRangeAttribute(5,10)]".
/// If multiple transformations are defined on a parameter, they will be invoked in series,
/// each getting the output of the previous transformation.
/// </remarks>
/// <seealso cref="ArgumentTypeConverterAttribute"/>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public abstract class ArgumentTransformationAttribute : CmdletMetadataAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="ArgumentTransformationAttribute"/> class.
/// </summary>
protected ArgumentTransformationAttribute()
{
}
/// <summary>
/// Method that will be overridden by the subclasses to transform the <paramref name="inputData"/>
/// parameter argument into some other object that will be used for the parameter's value.
/// </summary>
/// <param name="engineIntrinsics">
/// The engine APIs for the context under which the transformation is being made.
/// </param>
/// <param name="inputData">Parameter argument to mutate.</param>
/// <returns>The transformed value(s) of <paramref name="inputData"/>.</returns>
/// <exception cref="ArgumentException">Should be thrown for invalid arguments.</exception>
/// <exception cref="ArgumentTransformationMetadataException">
/// Should be thrown for any problems during transformation.
/// </exception>
public abstract object Transform(EngineIntrinsics engineIntrinsics, object inputData);
/// <summary>
/// Transform <paramref name="inputData"/> and track the flow of untrusted object.
/// NOTE: All internal handling of <see cref="ArgumentTransformationAttribute"/> should use this method to
/// track the trustworthiness of the data input source by default.
/// </summary>
/// <remarks>
/// The default value for <paramref name="trackDataInputSource"/> is true.
/// You should stick to the default value for this parameter in most cases so that data input source is
/// tracked during the transformation. The only acceptable exception is when this method is used in
/// Compiler or Binder where you can generate extra code to track input source when it's necessary.
/// This is to minimize the overhead when tracking is not needed.
/// </remarks>
internal object TransformInternal(
EngineIntrinsics engineIntrinsics,
object inputData,
bool trackDataInputSource = true)
{
object result = Transform(engineIntrinsics, inputData);
if (trackDataInputSource && engineIntrinsics != null)
{
ExecutionContext.PropagateInputSource(
inputData,
result,
engineIntrinsics.SessionState.Internal.LanguageMode);
}
return result;
}
/// <summary>
/// The property is only checked when:
/// a) The parameter is not mandatory
/// b) The argument is null.
/// </summary>
public virtual bool TransformNullOptionalParameters { get => true; }
}
#endregion Data Generation Attributes
}
|