File size: 83,943 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 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Management;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Provider;
using System.Management.Automation.Remoting;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Text;
using System.Threading;
using Microsoft.PowerShell.Commands.Internal;
using Dbg = System.Management.Automation;
namespace Microsoft.PowerShell.Commands
{
#region Helper Classes
/// <summary>
/// Base class for all WMI helper classes. This is an abstract class
/// and the helpers need to derive from this.
/// </summary>
internal abstract class AsyncCmdletHelper : IThrottleOperation
{
/// <summary>
/// Exception raised internally when any method of this class
/// is executed.
/// </summary>
internal Exception InternalException
{
get
{
return internalException;
}
}
protected Exception internalException = null;
}
/// <summary>
/// This class is responsible for creating WMI connection for getting objects and notifications
/// from WMI asynchronously. This spawns a new thread to connect to WMI on remote machine.
/// This allows the main thread to return faster and not blocked on network hops.
/// </summary>
internal class WmiAsyncCmdletHelper : AsyncCmdletHelper
{
/// <summary>
/// Internal Constructor.
/// </summary>
/// <param name="childJob">Job associated with this operation.</param>
/// <param name="wmiObject">Object associated with this operation.</param>
/// <param name="computerName">Computer on which the operation is invoked.</param>
/// <param name="results">Sink to get wmi objects.</param>
internal WmiAsyncCmdletHelper(PSWmiChildJob childJob, Cmdlet wmiObject, string computerName, ManagementOperationObserver results)
{
_wmiObject = wmiObject;
_computerName = computerName;
_results = results;
this.State = WmiState.NotStarted;
_job = childJob;
}
/// <summary>
/// Internal Constructor. This variant takes a count parameter that determines how many times
/// the WMI command is executed.
/// </summary>
/// <param name="childJob">Job associated with this operation.</param>
/// <param name="wmiObject">Object associated with this operation.</param>
/// <param name="computerName">Computer on which the operation is invoked.</param>
/// <param name="results">Sink to return wmi objects.</param>
/// <param name="count">Number of times the WMI command is executed.</param>
internal WmiAsyncCmdletHelper(PSWmiChildJob childJob, Cmdlet wmiObject, string computerName, ManagementOperationObserver results, int count)
: this(childJob, wmiObject, computerName, results)
{
_cmdCount = count;
}
private string _computerName;
internal event EventHandler<WmiJobStateEventArgs> WmiOperationState;
internal event EventHandler<EventArgs> ShutdownComplete;
private ManagementOperationObserver _results;
private int _cmdCount = 1;
private PSWmiChildJob _job;
/// <summary>
/// Current operation state.
/// </summary>
internal WmiState State
{
get { return _state; }
set { _state = value; }
}
private WmiState _state;
/// <summary>
/// Cancel WMI connection.
/// </summary>
internal override void StopOperation()
{
_results.Cancel();
_state = WmiState.Stopped;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
/// <summary>
/// Uses this.filter, this.wmiClass and this.property to retrieve the filter.
/// </summary>
private string GetWmiQueryString()
{
GetWmiObjectCommand getObject = (GetWmiObjectCommand)_wmiObject;
StringBuilder returnValue = new StringBuilder("select ");
returnValue.Append(string.Join(", ", getObject.Property));
returnValue.Append(" from ");
returnValue.Append(getObject.Class);
if (!string.IsNullOrEmpty(getObject.Filter))
{
returnValue.Append(" where ");
returnValue.Append(getObject.Filter);
}
return returnValue.ToString();
}
/// <summary>
/// Do WMI connection by creating another thread based on type of request and return immediately.
/// </summary>
internal override void StartOperation()
{
Thread thread;
if (_wmiObject.GetType() == typeof(GetWmiObjectCommand))
{
thread = new Thread(new ThreadStart(ConnectGetWMI));
}
else if (_wmiObject.GetType() == typeof(RemoveWmiObject))
{
thread = new Thread(new ThreadStart(ConnectRemoveWmi));
}
else if (_wmiObject is InvokeWmiMethod)
{
thread = new Thread(new ThreadStart(ConnectInvokeWmi));
}
else if (_wmiObject is SetWmiInstance)
{
thread = new Thread(new ThreadStart(ConnectSetWmi));
}
else
{
InvalidOperationException exception = new InvalidOperationException("This operation is not supported for this cmdlet.");
internalException = exception;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
return;
}
thread.IsBackground = true;
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
/// <summary>
/// </summary>
internal override event EventHandler<OperationStateEventArgs> OperationComplete;
private Cmdlet _wmiObject;
/// <summary>
/// Raise operation completion event.
/// </summary>
internal void RaiseOperationCompleteEvent(EventArgs baseEventArgs, OperationState state)
{
OperationStateEventArgs operationStateEventArgs = new OperationStateEventArgs();
operationStateEventArgs.OperationState = state;
OperationComplete.SafeInvoke(this, operationStateEventArgs);
}
/// <summary>
/// Raise WMI state changed event
/// </summary>
internal void RaiseWmiOperationState(EventArgs baseEventArgs, WmiState state)
{
WmiJobStateEventArgs wmiJobStateEventArgs = new WmiJobStateEventArgs();
wmiJobStateEventArgs.WmiState = state;
WmiOperationState.SafeInvoke(this, wmiJobStateEventArgs);
}
/// <summary>
/// Do the actual connection to remote machine for Set-WMIInstance cmdlet and raise operation complete event.
/// </summary>
private void ConnectSetWmi()
{
SetWmiInstance setObject = (SetWmiInstance)_wmiObject;
_state = WmiState.Running;
RaiseWmiOperationState(null, WmiState.Running);
if (setObject.InputObject != null)
{
ManagementObject mObj = null;
try
{
PutOptions pOptions = new PutOptions();
// Extra check
if (setObject.InputObject.GetType() == typeof(ManagementClass))
{
// Check if Flag specified is CreateOnly or not
if (setObject.flagSpecified && setObject.PutType != PutType.CreateOnly)
{
InvalidOperationException e = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath");
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
return;
}
mObj = ((ManagementClass)setObject.InputObject).CreateInstance();
setObject.PutType = PutType.CreateOnly;
}
else
{
// Check if Flag specified is Updateonly or UpdateOrCreateOnly or not
if (setObject.flagSpecified)
{
if (!(setObject.PutType == PutType.UpdateOnly || setObject.PutType == PutType.UpdateOrCreate))
{
InvalidOperationException e = new InvalidOperationException("NonUpdateFlagSpecifiedWithInstancePath");
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
return;
}
}
else
{
setObject.PutType = PutType.UpdateOrCreate;
}
mObj = (ManagementObject)setObject.InputObject.Clone();
}
if (setObject.Arguments != null)
{
IDictionaryEnumerator en = setObject.Arguments.GetEnumerator();
while (en.MoveNext())
{
mObj[en.Key as string] = en.Value;
}
}
pOptions.Type = setObject.PutType;
if (mObj != null)
{
mObj.Put(_results, pOptions);
}
else
{
InvalidOperationException exp = new InvalidOperationException();
internalException = exp;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
}
catch (ManagementException e)
{
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
catch (System.Runtime.InteropServices.COMException e)
{
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
catch (System.UnauthorizedAccessException e)
{
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
}
else
{
ManagementPath mPath = null;
// If Class is specified only CreateOnly flag is supported
if (setObject.Class != null)
{
if (setObject.flagSpecified && setObject.PutType != PutType.CreateOnly)
{
InvalidOperationException exp = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath");
internalException = exp;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
return;
}
setObject.PutType = PutType.CreateOnly;
}
else
{
mPath = new ManagementPath(setObject.Path);
if (string.IsNullOrEmpty(mPath.NamespacePath))
{
mPath.NamespacePath = setObject.Namespace;
}
else if (setObject.namespaceSpecified)
{
InvalidOperationException exp = new InvalidOperationException("NamespaceSpecifiedWithPath");
internalException = exp;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
return;
}
if (mPath.Server != "." && setObject.serverNameSpecified)
{
InvalidOperationException exp = new InvalidOperationException("ComputerNameSpecifiedWithPath");
internalException = exp;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
return;
}
if (mPath.IsClass)
{
if (setObject.flagSpecified && setObject.PutType != PutType.CreateOnly)
{
InvalidOperationException exp = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath");
internalException = exp;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
return;
}
setObject.PutType = PutType.CreateOnly;
}
else
{
if (setObject.flagSpecified)
{
if (!(setObject.PutType == PutType.UpdateOnly || setObject.PutType == PutType.UpdateOrCreate))
{
InvalidOperationException exp = new InvalidOperationException("NonUpdateFlagSpecifiedWithInstancePath");
internalException = exp;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
return;
}
}
else
{
setObject.PutType = PutType.UpdateOrCreate;
}
}
}
// If server name is specified loop through it.
if (mPath != null)
{
if (!(mPath.Server == "." && setObject.serverNameSpecified))
{
_computerName = mPath.Server;
}
}
ConnectionOptions options = setObject.GetConnectionOption();
ManagementObject mObject = null;
try
{
if (setObject.Path != null)
{
mPath.Server = _computerName;
ManagementScope mScope = new ManagementScope(mPath, options);
if (mPath.IsClass)
{
ManagementClass mClass = new ManagementClass(mPath);
mClass.Scope = mScope;
mObject = mClass.CreateInstance();
}
else
{
// This can throw if path does not exist caller should catch it.
ManagementObject mInstance = new ManagementObject(mPath);
mInstance.Scope = mScope;
try
{
mInstance.Get();
}
catch (ManagementException e)
{
if (e.ErrorCode != ManagementStatus.NotFound)
{
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
return;
}
int namespaceIndex = setObject.Path.IndexOf(':');
if (namespaceIndex == -1)
{
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
return;
}
int classIndex = (setObject.Path.Substring(namespaceIndex)).IndexOf('.');
if (classIndex == -1)
{
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
return;
}
// Get class object and create instance.
string newPath = setObject.Path.Substring(0, classIndex + namespaceIndex);
ManagementPath classPath = new ManagementPath(newPath);
ManagementClass mClass = new ManagementClass(classPath);
mClass.Scope = mScope;
mInstance = mClass.CreateInstance();
}
mObject = mInstance;
}
}
else
{
ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(_computerName, setObject.Namespace), options);
ManagementClass mClass = new ManagementClass(setObject.Class);
mClass.Scope = scope;
mObject = mClass.CreateInstance();
}
if (setObject.Arguments != null)
{
IDictionaryEnumerator en = setObject.Arguments.GetEnumerator();
while (en.MoveNext())
{
mObject[en.Key as string] = en.Value;
}
}
PutOptions pOptions = new PutOptions();
pOptions.Type = setObject.PutType;
if (mObject != null)
{
mObject.Put(_results, pOptions);
}
else
{
InvalidOperationException exp = new InvalidOperationException();
internalException = exp;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
}
catch (ManagementException e)
{
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
catch (System.Runtime.InteropServices.COMException e)
{
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
catch (System.UnauthorizedAccessException e)
{
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
}
}
/// <summary>
/// Do the actual connection to remote machine for Invoke-WMIMethod cmdlet and raise operation complete event.
/// </summary>
private void ConnectInvokeWmi()
{
InvokeWmiMethod invokeObject = (InvokeWmiMethod)_wmiObject;
_state = WmiState.Running;
RaiseWmiOperationState(null, WmiState.Running);
if (invokeObject.InputObject != null)
{
ManagementBaseObject inputParameters = null;
try
{
inputParameters = invokeObject.InputObject.GetMethodParameters(invokeObject.Name);
if (invokeObject.ArgumentList != null)
{
int inParamCount = invokeObject.ArgumentList.Length;
foreach (PropertyData property in inputParameters.Properties)
{
if (inParamCount == 0)
break;
property.Value = invokeObject.ArgumentList[invokeObject.ArgumentList.Length - inParamCount];
inParamCount--;
}
}
invokeObject.InputObject.InvokeMethod(_results, invokeObject.Name, inputParameters, null);
}
catch (ManagementException e)
{
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
catch (System.Runtime.InteropServices.COMException e)
{
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
catch (System.UnauthorizedAccessException e)
{
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
return;
}
else
{
ConnectionOptions options = invokeObject.GetConnectionOption();
ManagementPath mPath = null;
ManagementObject mObject = null;
if (invokeObject.Path != null)
{
mPath = new ManagementPath(invokeObject.Path);
if (string.IsNullOrEmpty(mPath.NamespacePath))
{
mPath.NamespacePath = invokeObject.Namespace;
}
else if (invokeObject.namespaceSpecified)
{
InvalidOperationException e = new InvalidOperationException("NamespaceSpecifiedWithPath");
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
return;
}
if (mPath.Server != "." && invokeObject.serverNameSpecified)
{
InvalidOperationException e = new InvalidOperationException("ComputerNameSpecifiedWithPath");
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
return;
}
// If server name is specified loop through it.
if (!(mPath.Server == "." && invokeObject.serverNameSpecified))
{
_computerName = mPath.Server;
}
}
bool isLocal = false, needToEnablePrivilege = false;
PlatformInvokes.TOKEN_PRIVILEGE currentPrivilegeState = new PlatformInvokes.TOKEN_PRIVILEGE();
try
{
needToEnablePrivilege = NeedToEnablePrivilege(_computerName, invokeObject.Name, ref isLocal);
if (needToEnablePrivilege)
{
if (!(isLocal && PlatformInvokes.EnableTokenPrivilege(ComputerWMIHelper.SE_SHUTDOWN_NAME, ref currentPrivilegeState)) &&
!(!isLocal && PlatformInvokes.EnableTokenPrivilege(ComputerWMIHelper.SE_REMOTE_SHUTDOWN_NAME, ref currentPrivilegeState)))
{
string message =
StringUtil.Format(ComputerResources.PrivilegeNotEnabled, _computerName,
isLocal ? ComputerWMIHelper.SE_SHUTDOWN_NAME : ComputerWMIHelper.SE_REMOTE_SHUTDOWN_NAME);
InvalidOperationException e = new InvalidOperationException(message);
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
return;
}
}
if (invokeObject.Path != null)
{
mPath.Server = _computerName;
if (mPath.IsClass)
{
ManagementClass mClass = new ManagementClass(mPath);
mObject = mClass;
}
else
{
ManagementObject mInstance = new ManagementObject(mPath);
mObject = mInstance;
}
ManagementScope mScope = new ManagementScope(mPath, options);
mObject.Scope = mScope;
}
else
{
ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(_computerName, invokeObject.Namespace), options);
ManagementClass mClass = new ManagementClass(invokeObject.Class);
mObject = mClass;
mObject.Scope = scope;
}
ManagementBaseObject inputParameters = mObject.GetMethodParameters(invokeObject.Name);
if (invokeObject.ArgumentList != null)
{
int inParamCount = invokeObject.ArgumentList.Length;
foreach (PropertyData property in inputParameters.Properties)
{
if (inParamCount == 0)
break;
property.Value = invokeObject.ArgumentList[invokeObject.ArgumentList.Length - inParamCount];
inParamCount--;
}
}
if (needToEnablePrivilege)
{
ManagementBaseObject result = mObject.InvokeMethod(invokeObject.Name, inputParameters, null);
Dbg.Diagnostics.Assert(result != null, "result cannot be null if the Join method is invoked");
int returnCode = Convert.ToInt32(result["ReturnValue"], CultureInfo.CurrentCulture);
if (returnCode != 0)
{
var e = new Win32Exception(returnCode);
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
else
{
ShutdownComplete.SafeInvoke(this, null);
}
}
else
{
mObject.InvokeMethod(_results, invokeObject.Name, inputParameters, null);
}
}
catch (ManagementException e)
{
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
catch (System.Runtime.InteropServices.COMException e)
{
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
catch (System.UnauthorizedAccessException e)
{
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
finally
{
// Restore the previous privilege state if something unexpected happened
if (needToEnablePrivilege)
{
PlatformInvokes.RestoreTokenPrivilege(
isLocal ? ComputerWMIHelper.SE_SHUTDOWN_NAME : ComputerWMIHelper.SE_REMOTE_SHUTDOWN_NAME, ref currentPrivilegeState);
}
}
}
}
/// <summary>
/// Check if we need to enable the shutdown privilege.
/// </summary>
/// <param name="computer"></param>
/// <param name="methodName"></param>
/// <param name="isLocal"></param>
/// <returns></returns>
private bool NeedToEnablePrivilege(string computer, string methodName, ref bool isLocal)
{
bool result = false;
if (methodName.Equals("Win32Shutdown", StringComparison.OrdinalIgnoreCase))
{
result = true;
// CLR 4.0 Port note - use https://msdn.microsoft.com/library/system.net.networkinformation.ipglobalproperties.hostname(v=vs.110).aspx
string localName = System.Net.Dns.GetHostName();
// And for this, use PsUtils.GetHostname()
string localFullName = System.Net.Dns.GetHostEntry(string.Empty).HostName;
if (computer.Equals(".") || computer.Equals("localhost", StringComparison.OrdinalIgnoreCase) ||
computer.Equals(localName, StringComparison.OrdinalIgnoreCase) ||
computer.Equals(localFullName, StringComparison.OrdinalIgnoreCase))
{
isLocal = true;
}
}
return result;
}
/// <summary>
/// Do the actual connection to remote machine for Remove-WMIObject cmdlet and raise operation complete event.
/// </summary>
private void ConnectRemoveWmi()
{
RemoveWmiObject removeObject = (RemoveWmiObject)_wmiObject;
_state = WmiState.Running;
RaiseWmiOperationState(null, WmiState.Running);
if (removeObject.InputObject != null)
{
try
{
removeObject.InputObject.Delete(_results);
}
catch (ManagementException e)
{
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
catch (System.Runtime.InteropServices.COMException e)
{
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
catch (System.UnauthorizedAccessException e)
{
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
return;
}
else
{
ConnectionOptions options = removeObject.GetConnectionOption();
ManagementPath mPath = null;
ManagementObject mObject = null;
if (removeObject.Path != null)
{
mPath = new ManagementPath(removeObject.Path);
if (string.IsNullOrEmpty(mPath.NamespacePath))
{
mPath.NamespacePath = removeObject.Namespace;
}
else if (removeObject.namespaceSpecified)
{
InvalidOperationException e = new InvalidOperationException("NamespaceSpecifiedWithPath");
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
return;
}
if (mPath.Server != "." && removeObject.serverNameSpecified)
{
InvalidOperationException e = new InvalidOperationException("ComputerNameSpecifiedWithPath");
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
return;
}
if (!(mPath.Server == "." && removeObject.serverNameSpecified))
{
_computerName = mPath.Server;
}
}
try
{
if (removeObject.Path != null)
{
mPath.Server = _computerName;
if (mPath.IsClass)
{
ManagementClass mClass = new ManagementClass(mPath);
mObject = mClass;
}
else
{
ManagementObject mInstance = new ManagementObject(mPath);
mObject = mInstance;
}
ManagementScope mScope = new ManagementScope(mPath, options);
mObject.Scope = mScope;
}
else
{
ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(_computerName, removeObject.Namespace), options);
ManagementClass mClass = new ManagementClass(removeObject.Class);
mObject = mClass;
mObject.Scope = scope;
}
mObject.Delete(_results);
}
catch (ManagementException e)
{
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
catch (System.Runtime.InteropServices.COMException e)
{
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
catch (System.UnauthorizedAccessException e)
{
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
}
}
/// <summary>
/// Do the actual connection to remote machine for Get-WMIObject cmdlet and raise operation complete event.
/// </summary>
private void ConnectGetWMI()
{
GetWmiObjectCommand getObject = (GetWmiObjectCommand)_wmiObject;
_state = WmiState.Running;
RaiseWmiOperationState(null, WmiState.Running);
ConnectionOptions options = getObject.GetConnectionOption();
if (getObject.List.IsPresent)
{
if (!getObject.ValidateClassFormat())
{
ArgumentException e = new ArgumentException(
string.Format(
Thread.CurrentThread.CurrentCulture,
"Class", getObject.Class));
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
return;
}
try
{
if (getObject.Recurse.IsPresent)
{
ArrayList namespaceArray = new ArrayList();
ArrayList sinkArray = new ArrayList();
ArrayList connectArray = new ArrayList(); // Optimization for remote namespace
int currentNamespaceCount = 0;
namespaceArray.Add(getObject.Namespace);
bool topNamespace = true;
while (currentNamespaceCount < namespaceArray.Count)
{
string connectNamespace = (string)namespaceArray[currentNamespaceCount];
ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(_computerName, connectNamespace), options);
scope.Connect();
ManagementClass namespaceClass = new ManagementClass(scope, new ManagementPath("__Namespace"), new ObjectGetOptions());
foreach (ManagementBaseObject obj in namespaceClass.GetInstances())
{
if (!getObject.IsLocalizedNamespace((string)obj["Name"]))
{
namespaceArray.Add(connectNamespace + "\\" + obj["Name"]);
}
}
if (topNamespace)
{
topNamespace = false;
sinkArray.Add(_results);
}
else
{
sinkArray.Add(_job.GetNewSink());
}
connectArray.Add(scope);
currentNamespaceCount++;
}
if ((sinkArray.Count != namespaceArray.Count) || (connectArray.Count != namespaceArray.Count)) // not expected throw exception
{
internalException = new InvalidOperationException();
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
return;
}
currentNamespaceCount = 0;
while (currentNamespaceCount < namespaceArray.Count)
{
string connectNamespace = (string)namespaceArray[currentNamespaceCount];
ManagementObjectSearcher searcher = getObject.GetObjectList((ManagementScope)connectArray[currentNamespaceCount]);
if (searcher == null)
{
currentNamespaceCount++;
continue;
}
if (topNamespace)
{
topNamespace = false;
searcher.Get(_results);
}
else
{
searcher.Get((ManagementOperationObserver)sinkArray[currentNamespaceCount]);
}
currentNamespaceCount++;
}
}
else
{
ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(_computerName, getObject.Namespace), options);
scope.Connect();
ManagementObjectSearcher searcher = getObject.GetObjectList(scope);
if (searcher == null)
throw new ManagementException();
searcher.Get(_results);
}
}
catch (ManagementException e)
{
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
catch (System.Runtime.InteropServices.COMException e)
{
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
catch (System.UnauthorizedAccessException e)
{
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
return;
}
string queryString = string.IsNullOrEmpty(getObject.Query) ? GetWmiQueryString() : getObject.Query;
ObjectQuery query = new ObjectQuery(queryString.ToString());
try
{
ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(_computerName, getObject.Namespace), options);
EnumerationOptions enumOptions = new EnumerationOptions();
enumOptions.UseAmendedQualifiers = getObject.Amended;
enumOptions.DirectRead = getObject.DirectRead;
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query, enumOptions);
// Execute the WMI command for each count value.
for (int i = 0; i < _cmdCount; ++i)
{
searcher.Get(_results);
}
}
catch (ManagementException e)
{
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
catch (System.Runtime.InteropServices.COMException e)
{
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
catch (System.UnauthorizedAccessException e)
{
internalException = e;
_state = WmiState.Failed;
RaiseOperationCompleteEvent(null, OperationState.StopComplete);
}
}
}
/// <summary>
/// Event which will be triggered when WMI state is changed.
/// Currently it is to notify Jobs that state has changed to running.
/// Other states are notified via OperationComplete.
/// </summary>
internal sealed class WmiJobStateEventArgs : EventArgs
{
/// <summary>
/// WMI state
/// </summary>
internal WmiState WmiState { get; set; }
}
/// <summary>
/// Enumerated type defining the state of the WMI operation.
/// </summary>
public enum WmiState
{
/// <summary>
/// The operation has not been started.
/// </summary>
NotStarted = 0,
/// <summary>
/// The operation is executing.
/// </summary>
Running = 1,
/// <summary>
/// The operation is stoping execution.
/// </summary>
Stopping = 2,
/// <summary>
/// The operation is completed due to a stop request.
/// </summary>
Stopped = 3,
/// <summary>
/// The operation has completed.
/// </summary>
Completed = 4,
/// <summary>
/// The operation completed abnormally due to an error.
/// </summary>
Failed = 5,
}
internal static class WMIHelper
{
internal static string GetScopeString(string computer, string namespaceParameter)
{
StringBuilder returnValue = new StringBuilder("\\\\");
returnValue.Append(computer);
returnValue.Append('\\');
returnValue.Append(namespaceParameter);
return returnValue.ToString();
}
}
#endregion Helper Classes
/// <summary>
/// A class to set WMI connection options.
/// </summary>
public class WmiBaseCmdlet : Cmdlet
{
#region Parameters
/// <summary>
/// Perform Async operation.
/// </summary>
[Parameter]
public SwitchParameter AsJob { get; set; } = false;
/// <summary>
/// The Impersonation level to use.
/// </summary>
[Parameter(ParameterSetName = "path")]
[Parameter(ParameterSetName = "class")]
[Parameter(ParameterSetName = "WQLQuery")]
[Parameter(ParameterSetName = "query")]
[Parameter(ParameterSetName = "list")]
public ImpersonationLevel Impersonation { get; set; } = ImpersonationLevel.Impersonate;
/// <summary>
/// The Authentication level to use.
/// </summary>
[Parameter(ParameterSetName = "path")]
[Parameter(ParameterSetName = "class")]
[Parameter(ParameterSetName = "WQLQuery")]
[Parameter(ParameterSetName = "query")]
[Parameter(ParameterSetName = "list")]
public AuthenticationLevel Authentication { get; set; } = AuthenticationLevel.PacketPrivacy;
/// <summary>
/// The Locale to use.
/// </summary>
[Parameter(ParameterSetName = "path")]
[Parameter(ParameterSetName = "class")]
[Parameter(ParameterSetName = "WQLQuery")]
[Parameter(ParameterSetName = "query")]
[Parameter(ParameterSetName = "list")]
public string Locale { get; set; } = null;
/// <summary>
/// If all Privileges are enabled.
/// </summary>
[Parameter(ParameterSetName = "path")]
[Parameter(ParameterSetName = "class")]
[Parameter(ParameterSetName = "WQLQuery")]
[Parameter(ParameterSetName = "query")]
[Parameter(ParameterSetName = "list")]
public SwitchParameter EnableAllPrivileges { get; set; }
/// <summary>
/// The Authority to use.
/// </summary>
[Parameter(ParameterSetName = "path")]
[Parameter(ParameterSetName = "class")]
[Parameter(ParameterSetName = "WQLQuery")]
[Parameter(ParameterSetName = "query")]
[Parameter(ParameterSetName = "list")]
public string Authority { get; set; } = null;
/// <summary>
/// The credential to use.
/// </summary>
[Parameter(ParameterSetName = "path")]
[Parameter(ParameterSetName = "class")]
[Parameter(ParameterSetName = "WQLQuery")]
[Parameter(ParameterSetName = "query")]
[Parameter(ParameterSetName = "list")]
[Credential]
public PSCredential Credential { get; set; }
/// <summary>
/// The credential to use.
/// </summary>
[Parameter]
public Int32 ThrottleLimit { get; set; } = s_DEFAULT_THROTTLE_LIMIT;
/// <summary>
/// The ComputerName in which to query.
/// </summary>
[Parameter(ParameterSetName = "path")]
[Parameter(ParameterSetName = "class")]
[Parameter(ParameterSetName = "WQLQuery")]
[Parameter(ParameterSetName = "query")]
[Parameter(ParameterSetName = "list")]
[ValidateNotNullOrEmpty]
[Alias("Cn")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] ComputerName
{
get { return _computerName; }
set { _computerName = value; serverNameSpecified = true; }
}
/// <summary>
/// The WMI namespace to use.
/// </summary>
[Parameter(ParameterSetName = "path")]
[Parameter(ParameterSetName = "class")]
[Parameter(ParameterSetName = "WQLQuery")]
[Parameter(ParameterSetName = "query")]
[Parameter(ParameterSetName = "list")]
[Alias("NS")]
public string Namespace
{
get { return _nameSpace; }
set { _nameSpace = value; namespaceSpecified = true; }
}
#endregion Parameters
#region parameter data
/// <summary>
/// The computer to query.
/// </summary>
private string[] _computerName = new string[] { "localhost" };
/// <summary>
/// WMI namespace.
/// </summary>
private string _nameSpace = "root\\cimv2";
/// <summary>
/// Specify if namespace was specified or not.
/// </summary>
internal bool namespaceSpecified = false;
/// <summary>
/// Specify if server name was specified or not.
/// </summary>
internal bool serverNameSpecified = false;
private static int s_DEFAULT_THROTTLE_LIMIT = 32; // maximum number of items to be processed at a time
#endregion parameter data
#region Command code
/// <summary>
/// Get connection options.
/// </summary>
internal ConnectionOptions GetConnectionOption()
{
ConnectionOptions options;
options = new ConnectionOptions();
options.Authentication = this.Authentication;
options.Locale = this.Locale;
options.Authority = this.Authority;
options.EnablePrivileges = this.EnableAllPrivileges;
options.Impersonation = this.Impersonation;
if (this.Credential != null)
{
if (!(this.Credential.UserName == null && this.Credential.Password == null)) // Empty credential, use implicit credential
{
options.Username = this.Credential.UserName;
options.SecurePassword = this.Credential.Password;
}
}
return options;
}
/// <summary>
/// Set wmi instance helper.
/// </summary>
internal ManagementObject SetWmiInstanceGetObject(ManagementPath mPath, string serverName)
{
ConnectionOptions options = GetConnectionOption();
ManagementObject mObject = null;
var setObject = this as SetWmiInstance;
if (setObject != null)
{
if (setObject.Path != null)
{
mPath.Server = serverName;
ManagementScope mScope = new ManagementScope(mPath, options);
if (mPath.IsClass)
{
ManagementClass mClass = new ManagementClass(mPath);
mClass.Scope = mScope;
mObject = mClass.CreateInstance();
}
else
{
// This can throw if path does not exist caller should catch it.
ManagementObject mInstance = new ManagementObject(mPath);
mInstance.Scope = mScope;
try
{
mInstance.Get();
}
catch (ManagementException e)
{
if (e.ErrorCode != ManagementStatus.NotFound)
{
throw;
}
int namespaceIndex = setObject.Path.IndexOf(':');
if (namespaceIndex == -1)
{
throw;
}
int classIndex = (setObject.Path.Substring(namespaceIndex)).IndexOf('.');
if (classIndex == -1)
{
throw;
}
// Get class object and create instance.
string newPath = setObject.Path.Substring(0, classIndex + namespaceIndex);
ManagementPath classPath = new ManagementPath(newPath);
ManagementClass mClass = new ManagementClass(classPath);
mClass.Scope = mScope;
mInstance = mClass.CreateInstance();
}
mObject = mInstance;
}
}
else
{
ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(serverName, setObject.Namespace), options);
ManagementClass mClass = new ManagementClass(setObject.Class);
mClass.Scope = scope;
mObject = mClass.CreateInstance();
}
if (setObject.Arguments != null)
{
IDictionaryEnumerator en = setObject.Arguments.GetEnumerator();
while (en.MoveNext())
{
mObject[en.Key as string] = en.Value;
}
}
}
return mObject;
}
/// <summary>
/// Set wmi instance helper for building management path.
/// </summary>
internal ManagementPath SetWmiInstanceBuildManagementPath()
{
ManagementPath mPath = null;
var wmiInstance = this as SetWmiInstance;
if (wmiInstance != null)
{
// If Class is specified only CreateOnly flag is supported
if (wmiInstance.Class != null)
{
if (wmiInstance.flagSpecified && wmiInstance.PutType != PutType.CreateOnly)
{
// Throw Terminating error
ThrowTerminatingError(new ErrorRecord(
new InvalidOperationException(),
"CreateOnlyFlagNotSpecifiedWithClassPath",
ErrorCategory.InvalidOperation,
wmiInstance.PutType));
}
wmiInstance.PutType = PutType.CreateOnly;
}
else
{
mPath = new ManagementPath(wmiInstance.Path);
if (string.IsNullOrEmpty(mPath.NamespacePath))
{
mPath.NamespacePath = wmiInstance.Namespace;
}
else if (wmiInstance.namespaceSpecified)
{
// ThrowTerminatingError
ThrowTerminatingError(new ErrorRecord(
new InvalidOperationException(),
"NamespaceSpecifiedWithPath",
ErrorCategory.InvalidOperation,
wmiInstance.Namespace));
}
if (mPath.Server != "." && wmiInstance.serverNameSpecified)
{
// ThrowTerminatingError
ThrowTerminatingError(new ErrorRecord(
new InvalidOperationException(),
"ComputerNameSpecifiedWithPath",
ErrorCategory.InvalidOperation,
wmiInstance.ComputerName));
}
if (mPath.IsClass)
{
if (wmiInstance.flagSpecified && wmiInstance.PutType != PutType.CreateOnly)
{
// Throw Terminating error
ThrowTerminatingError(new ErrorRecord(
new InvalidOperationException(),
"CreateOnlyFlagNotSpecifiedWithClassPath",
ErrorCategory.InvalidOperation,
wmiInstance.PutType));
}
wmiInstance.PutType = PutType.CreateOnly;
}
else
{
if (wmiInstance.flagSpecified)
{
if (!(wmiInstance.PutType == PutType.UpdateOnly || wmiInstance.PutType == PutType.UpdateOrCreate))
{
// Throw terminating error
ThrowTerminatingError(new ErrorRecord(
new InvalidOperationException(),
"NonUpdateFlagSpecifiedWithInstancePath",
ErrorCategory.InvalidOperation,
wmiInstance.PutType));
}
}
else
{
wmiInstance.PutType = PutType.UpdateOrCreate;
}
}
}
}
return mPath;
}
/// <summary>
/// Set wmi instance helper for pipeline input.
/// </summary>
internal ManagementObject SetWmiInstanceGetPipelineObject()
{
// Should only be called from Set-WMIInstance cmdlet
ManagementObject mObj = null;
var wmiInstance = this as SetWmiInstance;
if (wmiInstance != null)
{
// Extra check
if (wmiInstance.InputObject != null)
{
if (wmiInstance.InputObject.GetType() == typeof(ManagementClass))
{
// Check if Flag specified is CreateOnly or not
if (wmiInstance.flagSpecified && wmiInstance.PutType != PutType.CreateOnly)
{
// Throw terminating error
ThrowTerminatingError(new ErrorRecord(
new InvalidOperationException(),
"CreateOnlyFlagNotSpecifiedWithClassPath",
ErrorCategory.InvalidOperation,
wmiInstance.PutType));
}
mObj = ((ManagementClass)wmiInstance.InputObject).CreateInstance();
wmiInstance.PutType = PutType.CreateOnly;
}
else
{
// Check if Flag specified is Updateonly or UpdateOrCreateOnly or not
if (wmiInstance.flagSpecified)
{
if (!(wmiInstance.PutType == PutType.UpdateOnly || wmiInstance.PutType == PutType.UpdateOrCreate))
{
// Throw terminating error
ThrowTerminatingError(new ErrorRecord(
new InvalidOperationException(),
"NonUpdateFlagSpecifiedWithInstancePath",
ErrorCategory.InvalidOperation,
wmiInstance.PutType));
}
}
else
{
wmiInstance.PutType = PutType.UpdateOrCreate;
}
mObj = (ManagementObject)wmiInstance.InputObject.Clone();
}
if (wmiInstance.Arguments != null)
{
IDictionaryEnumerator en = wmiInstance.Arguments.GetEnumerator();
while (en.MoveNext())
{
mObj[en.Key as string] = en.Value;
}
}
}
}
return mObj;
}
/// <summary>
/// Start this cmdlet as a WMI job...
/// </summary>
internal void RunAsJob(string cmdletName)
{
PSWmiJob wmiJob = new PSWmiJob(this, ComputerName, this.ThrottleLimit, Job.GetCommandTextFromInvocationInfo(this.MyInvocation));
if (_context != null)
{
((System.Management.Automation.Runspaces.LocalRunspace)_context.CurrentRunspace).JobRepository.Add(wmiJob);
}
WriteObject(wmiJob);
}
// Get the PowerShell execution context if it's available at cmdlet creation time...
private System.Management.Automation.ExecutionContext _context = System.Management.Automation.Runspaces.LocalPipeline.GetExecutionContextFromTLS();
#endregion Command code
}
/// <summary>
/// A class to perform async operations for WMI cmdlets.
/// </summary>
internal class PSWmiJob : Job
{
#region internal constructor
/// <summary>
///Internal constructor for initializing WMI jobs.
/// </summary>
internal PSWmiJob(Cmdlet cmds, string[] computerName, int throttleLimt, string command)
: base(command, null)
{
PSJobTypeName = WMIJobType;
_throttleManager.ThrottleLimit = throttleLimt;
for (int i = 0; i < computerName.Length; i++)
{
PSWmiChildJob job = new PSWmiChildJob(cmds, computerName[i], _throttleManager);
job.StateChanged += new EventHandler<JobStateEventArgs>(HandleChildJobStateChanged);
job.JobUnblocked += new EventHandler(HandleJobUnblocked);
ChildJobs.Add(job);
}
CommonInit(throttleLimt);
}
/// <summary>
/// Internal constructor for initializing WMI jobs, where WMI command is executed a variable
/// number of times.
/// </summary>
internal PSWmiJob(Cmdlet cmds, string[] computerName, int throttleLimit, string command, int count)
: base(command, null)
{
PSJobTypeName = WMIJobType;
_throttleManager.ThrottleLimit = throttleLimit;
for (int i = 0; i < computerName.Length; ++i)
{
PSWmiChildJob childJob = new PSWmiChildJob(cmds, computerName[i], _throttleManager, count);
childJob.StateChanged += new EventHandler<JobStateEventArgs>(HandleChildJobStateChanged);
childJob.JobUnblocked += new EventHandler(HandleJobUnblocked);
ChildJobs.Add(childJob);
}
CommonInit(throttleLimit);
}
#endregion internal constructor
// Set to true when at least one chil job failed
private bool _atleastOneChildJobFailed = false;
// Count the number of childs which have finished
private int _finishedChildJobsCount = 0;
// Count of number of child jobs which are blocked
private int _blockedChildJobsCount = 0;
// WMI Job type name.
private const string WMIJobType = "WmiJob";
/// <summary>
/// Handles the StateChanged event from each of the child job objects.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void HandleChildJobStateChanged(object sender, JobStateEventArgs e)
{
if (e.JobStateInfo.State == JobState.Blocked)
{
// increment count of blocked child jobs
lock (_syncObject)
{
_blockedChildJobsCount++;
}
// if any of the child job is blocked, we set state to blocked
SetJobState(JobState.Blocked, null);
return;
}
// Ignore state changes which are not resulting in state change to finished.
if ((!IsFinishedState(e.JobStateInfo.State)) || (e.JobStateInfo.State == JobState.NotStarted))
{
return;
}
if (e.JobStateInfo.State == JobState.Failed)
{
// If any of the child job failed, we set status to failed
_atleastOneChildJobFailed = true;
}
bool allChildJobsFinished = false;
lock (_syncObject)
{
_finishedChildJobsCount++;
// We are done
if (_finishedChildJobsCount == ChildJobs.Count)
{
allChildJobsFinished = true;
}
}
if (allChildJobsFinished)
{
// if any child job failed, set status to failed
// If stop was called set, status to stopped
// else completed
if (_atleastOneChildJobFailed)
{
SetJobState(JobState.Failed);
}
else if (_stopIsCalled == true)
{
SetJobState(JobState.Stopped);
}
else
{
SetJobState(JobState.Completed);
}
}
}
private bool _stopIsCalled = false;
private string _statusMessage;
/// <summary>
/// Message indicating status of the job.
/// </summary>
public override string StatusMessage
{
get
{
return _statusMessage;
}
}
// ISSUE: Implement StatusMessage
/// <summary>
/// Checks the status of remote command execution.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
private void SetStatusMessage()
{
_statusMessage = "test";
}
private bool _moreData = false;
/// <summary>
/// Indicates if more data is available.
/// </summary>
/// <remarks>
/// This has more data if any of the child jobs have more data.
/// </remarks>
public override bool HasMoreData
{
get
{
// moreData is set to false and will be set to true
// if at least one child is has more data.
// if ( (!moreData))
// {
bool atleastOneChildHasMoreData = false;
for (int i = 0; i < ChildJobs.Count; i++)
{
if (ChildJobs[i].HasMoreData)
{
atleastOneChildHasMoreData = true;
break;
}
}
_moreData = atleastOneChildHasMoreData;
// }
return _moreData;
}
}
/// <summary>
/// Computers on which this job is running.
/// </summary>
public override string Location
{
get
{
return ConstructLocation();
}
}
private string ConstructLocation()
{
StringBuilder location = new StringBuilder();
foreach (PSWmiChildJob job in ChildJobs)
{
location.Append(job.Location);
location.Append(',');
}
location.Remove(location.Length - 1, 1);
return location.ToString();
}
/// <summary>
/// Stop Job.
/// </summary>
public override void StopJob()
{
// AssertNotDisposed();
if (!IsFinishedState(JobStateInfo.State))
{
_stopIsCalled = true;
_throttleManager.StopAllOperations();
Finished.WaitOne();
}
}
/// <summary>
/// Release all the resources.
/// </summary>
/// <param name="disposing">
/// if true, release all the managed objects.
/// </param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (!_isDisposed)
{
_isDisposed = true;
try
{
if (!IsFinishedState(JobStateInfo.State))
{
StopJob();
}
_throttleManager.Dispose();
foreach (Job job in ChildJobs)
{
job.Dispose();
}
}
finally
{
base.Dispose(disposing);
}
}
}
}
private bool _isDisposed = false;
/// <summary>
/// Initialization common to both constructors.
/// </summary>
private void CommonInit(int throttleLimit)
{
// Since no results are produced by any streams. We should
// close all the streams
base.CloseAllStreams();
// set status to "in progress"
SetJobState(JobState.Running);
// submit operations to the throttle manager
_throttleManager.EndSubmitOperations();
}
/// <summary>
/// Handles JobUnblocked event from a child job and decrements
/// count of blocked child jobs. When count reaches 0, sets the
/// state of the parent job to running.
/// </summary>
/// <param name="sender">Sender of this event, unused.</param>
/// <param name="eventArgs">event arguments, should be empty in this
/// case</param>
private void HandleJobUnblocked(object sender, EventArgs eventArgs)
{
bool unblockjob = false;
lock (_syncObject)
{
_blockedChildJobsCount--;
if (_blockedChildJobsCount == 0)
{
unblockjob = true;
}
}
if (unblockjob)
{
SetJobState(JobState.Running, null);
}
}
private ThrottleManager _throttleManager = new ThrottleManager();
private object _syncObject = new object(); // sync object
}
/// <summary>
/// Class for WmiChildJob object. This job object Execute wmi cmdlet.
/// </summary>
internal class PSWmiChildJob : Job
{
#region internal constructor
/// <summary>
/// Internal constructor for initializing WMI jobs.
/// </summary>
internal PSWmiChildJob(Cmdlet cmds, string computerName, ThrottleManager throttleManager)
: base(null, null)
{
UsesResultsCollection = true;
Location = computerName;
_throttleManager = throttleManager;
_wmiSinkArray = new ArrayList();
ManagementOperationObserver wmiSink = new ManagementOperationObserver();
_wmiSinkArray.Add(wmiSink);
_sinkCompleted++;
wmiSink.ObjectReady += new ObjectReadyEventHandler(this.NewObject);
wmiSink.Completed += new CompletedEventHandler(this.JobDone);
_helper = new WmiAsyncCmdletHelper(this, cmds, computerName, wmiSink);
_helper.WmiOperationState += new EventHandler<WmiJobStateEventArgs>(HandleWMIState);
_helper.ShutdownComplete += new EventHandler<EventArgs>(JobDoneForWin32Shutdown);
SetJobState(JobState.NotStarted);
IThrottleOperation operation = _helper;
operation.OperationComplete += new EventHandler<OperationStateEventArgs>(HandleOperationComplete);
throttleManager.ThrottleComplete += new EventHandler<EventArgs>(HandleThrottleComplete);
throttleManager.AddOperation(operation);
}
/// <summary>
/// Internal constructor for initializing WMI jobs, where WMI command is executed a variable
/// number of times.
/// </summary>
internal PSWmiChildJob(Cmdlet cmds, string computerName, ThrottleManager throttleManager, int count)
: base(null, null)
{
UsesResultsCollection = true;
Location = computerName;
_throttleManager = throttleManager;
_wmiSinkArray = new ArrayList();
ManagementOperationObserver wmiSink = new ManagementOperationObserver();
_wmiSinkArray.Add(wmiSink);
_sinkCompleted += count;
wmiSink.ObjectReady += new ObjectReadyEventHandler(this.NewObject);
wmiSink.Completed += new CompletedEventHandler(this.JobDone);
_helper = new WmiAsyncCmdletHelper(this, cmds, computerName, wmiSink, count);
_helper.WmiOperationState += new EventHandler<WmiJobStateEventArgs>(HandleWMIState);
_helper.ShutdownComplete += new EventHandler<EventArgs>(JobDoneForWin32Shutdown);
SetJobState(JobState.NotStarted);
IThrottleOperation operation = _helper;
operation.OperationComplete += new EventHandler<OperationStateEventArgs>(HandleOperationComplete);
throttleManager.ThrottleComplete += new EventHandler<EventArgs>(HandleThrottleComplete);
throttleManager.AddOperation(operation);
}
#endregion internal constructor
private WmiAsyncCmdletHelper _helper;
// bool _bFinished;
private ThrottleManager _throttleManager;
private object _syncObject = new object(); // sync object
private int _sinkCompleted;
private bool _bJobFailed;
private bool _bAtLeastOneObject;
private ArrayList _wmiSinkArray;
/// <summary>
/// Event raised by this job to indicate to its parent that
/// its now unblocked by the user.
/// </summary>
internal event EventHandler JobUnblocked;
/// <summary>
/// Set the state of the current job from blocked to
/// running and raise an event indicating to this
/// parent job that this job is unblocked.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal void UnblockJob()
{
SetJobState(JobState.Running, null);
JobUnblocked.SafeInvoke(this, EventArgs.Empty);
}
internal ManagementOperationObserver GetNewSink()
{
ManagementOperationObserver wmiSink = new ManagementOperationObserver();
_wmiSinkArray.Add(wmiSink);
lock (_syncObject)
{
_sinkCompleted++;
}
wmiSink.ObjectReady += new ObjectReadyEventHandler(this.NewObject);
wmiSink.Completed += new CompletedEventHandler(this.JobDone);
return wmiSink;
}
/// <summary>
/// It receives Management objects.
/// </summary>
private void NewObject(object sender, ObjectReadyEventArgs obj)
{
if (!_bAtLeastOneObject)
{
_bAtLeastOneObject = true;
}
this.WriteObject(obj.NewObject);
}
/// <summary>
/// It is called when WMI job is done.
/// </summary>
private void JobDone(object sender, CompletedEventArgs obj)
{
lock (_syncObject)
{
_sinkCompleted--;
}
if (obj.Status != ManagementStatus.NoError)
{
_bJobFailed = true;
}
if (_sinkCompleted == 0)
{
// Notify throttle manager and change the state to complete
// Two cases where _bFinished should be set to false.
// 1) Invalid class or some other condition so that after making a connection WMI is throwing an error
// 2) We could not get any instance for the class.
/*if(bAtLeastOneObject )
_bFinished = true;*/
_helper.RaiseOperationCompleteEvent(null, OperationState.StopComplete);
if (!_bJobFailed)
{
_helper.State = WmiState.Completed;
SetJobState(JobState.Completed);
}
else
{
_helper.State = WmiState.Failed;
SetJobState(JobState.Failed);
}
}
}
/// <summary>
/// It is called when the call to Win32shutdown is successfully completed.
/// </summary>
private void JobDoneForWin32Shutdown(object sender, EventArgs arg)
{
lock (_syncObject)
{
_sinkCompleted--;
}
if (_sinkCompleted == 0)
{
_helper.RaiseOperationCompleteEvent(null, OperationState.StopComplete);
_helper.State = WmiState.Completed;
SetJobState(JobState.Completed);
}
}
/// <summary>
/// Message indicating status of the job.
/// </summary>
public override string StatusMessage { get; } = "test";
/// <summary>
/// Indicates if there is more data available in
/// this Job.
/// </summary>
public override bool HasMoreData
{
get
{
return (Results.IsOpen || Results.Count > 0);
}
}
/// <summary>
/// Returns the computer on which this command is
/// running.
/// </summary>
public override string Location { get; }
/// <summary>
/// Stops the job.
/// </summary>
public override void StopJob()
{
AssertNotDisposed();
_throttleManager.StopOperation(_helper);
// if IgnoreStop is set, then StopOperation will
// return immediately, but StopJob should only
// return when job is complete. Waiting on the
// wait handle will ensure that its blocked
// until the job reaches a terminal state
Finished.WaitOne();
}
/// <summary>
/// Release all the resources.
/// </summary>
/// <param name="disposing">
/// if true, release all the managed objects.
/// </param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (!_isDisposed)
{
_isDisposed = true;
base.Dispose(disposing);
}
}
}
private bool _isDisposed;
/// <summary>
/// Handles operation complete event.
/// </summary>
private void HandleOperationComplete(object sender, OperationStateEventArgs stateEventArgs)
{
WmiAsyncCmdletHelper helper = (WmiAsyncCmdletHelper)sender;
if (helper.State == WmiState.NotStarted)
{
// This is a case WMI operation was not started.
SetJobState(JobState.Stopped, helper.InternalException);
}
else if (helper.State == WmiState.Running)
{
SetJobState(JobState.Running, helper.InternalException);
}
else if (helper.State == WmiState.Completed)
{
SetJobState(JobState.Completed, helper.InternalException);
}
else if (helper.State == WmiState.Failed)
{
SetJobState(JobState.Failed, helper.InternalException);
}
else
{
SetJobState(JobState.Stopped, helper.InternalException);
}
}
/// <summary>
/// Handles WMI state changed.
/// </summary>
private void HandleWMIState(object sender, WmiJobStateEventArgs stateEventArgs)
{
if (stateEventArgs.WmiState == WmiState.Running)
{
SetJobState(JobState.Running, _helper.InternalException);
}
else if (stateEventArgs.WmiState == WmiState.NotStarted)
{
SetJobState(JobState.NotStarted, _helper.InternalException);
}
else if (stateEventArgs.WmiState == WmiState.Completed)
{
SetJobState(JobState.Completed);
}
else if (stateEventArgs.WmiState == WmiState.Failed)
{
SetJobState(JobState.Failed, _helper.InternalException);
}
else
{
SetJobState(JobState.Stopped, _helper.InternalException);
}
}
/// <summary>
/// Handle a throttle complete event.
/// </summary>
/// <param name="sender">Sender of this event.</param>
/// <param name="eventArgs">Not used in this method.</param>
private void HandleThrottleComplete(object sender, EventArgs eventArgs)
{
if (_helper.State == WmiState.NotStarted)
{
// This is a case WMI operation was not started.
SetJobState(JobState.Stopped, _helper.InternalException);
}
else if (_helper.State == WmiState.Running)
{
SetJobState(JobState.Running, _helper.InternalException);
}
else if (_helper.State == WmiState.Completed)
{
SetJobState(JobState.Completed, _helper.InternalException);
}
else if (_helper.State == WmiState.Failed)
{
SetJobState(JobState.Failed, _helper.InternalException);
}
else
{
SetJobState(JobState.Stopped, _helper.InternalException);
}
// Do Nothing
}
}
}
|