File size: 70,475 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 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.Runtime.Serialization;
using System.Threading;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Runspaces
{
#region Exceptions
/// <summary>
/// Exception thrown when state of the runspace is different from
/// expected state of runspace.
/// </summary>
public class InvalidRunspaceStateException : SystemException
{
/// <summary>
/// Initializes a new instance of InvalidRunspaceStateException.
/// </summary>
public InvalidRunspaceStateException()
: base
(
StringUtil.Format(RunspaceStrings.InvalidRunspaceStateGeneral)
)
{
}
/// <summary>
/// Initializes a new instance of InvalidRunspaceStateException with a specified error message.
/// </summary>
/// <param name="message">
/// The message that describes the error.
/// </param>
public InvalidRunspaceStateException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the InvalidRunspaceStateException class
/// with a specified error message and a reference to the inner exception
/// that is the cause of this exception.
/// </summary>
/// <param name="message">
/// The message that describes the error.
/// </param>
/// <param name="innerException">
/// The exception that is the cause of the current exception.
/// </param>
public InvalidRunspaceStateException(string message, Exception innerException)
: base(message, innerException)
{
}
/// <summary>
/// Initializes a new instance of the InvalidRunspaceStateException
/// with a specified error message and current and expected state.
/// </summary>
/// <param name="message">The message that describes the error.</param>
/// <param name="currentState">Current state of runspace.</param>
/// <param name="expectedState">Expected states of runspace.</param>
internal InvalidRunspaceStateException
(
string message,
RunspaceState currentState,
RunspaceState expectedState
)
: base(message)
{
_expectedState = expectedState;
_currentState = currentState;
}
#region ISerializable Members
// 2005/04/20-JonN No need to implement GetObjectData
// if all fields are static or [NonSerialized]
/// <summary>
/// Initializes a new instance of the <see cref="InvalidRunspaceStateException"/>
/// class with serialized data.
/// </summary>
/// <param name="info">
/// The <see cref="SerializationInfo"/> that holds the serialized object
/// data about the exception being thrown.
/// </param>
/// <param name="context">
/// The <see cref="StreamingContext"/> that contains contextual information
/// about the source or destination.
/// </param>
[Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")]
protected InvalidRunspaceStateException(SerializationInfo info, StreamingContext context)
{
throw new NotSupportedException();
}
#endregion
/// <summary>
/// Access CurrentState of the runspace.
/// </summary>
/// <remarks>This is the state of the runspace when exception was thrown.
/// </remarks>
public RunspaceState CurrentState
{
get
{
return _currentState;
}
internal set
{
_currentState = value;
}
}
/// <summary>
/// Expected state of runspace by the operation which has thrown this exception.
/// </summary>
public RunspaceState ExpectedState
{
get
{
return _expectedState;
}
internal set
{
_expectedState = value;
}
}
/// <summary>
/// State of the runspace when exception was thrown.
/// </summary>
[NonSerialized]
private RunspaceState _currentState = 0;
/// <summary>
/// States of the runspace expected in method which throws this exception.
/// </summary>
[NonSerialized]
private RunspaceState _expectedState = 0;
}
#endregion Exceptions
#region Runspace state
/// <summary>
/// Defines various states of runspace.
/// </summary>
public enum RunspaceState
{
/// <summary>
/// Beginning state upon creation.
/// </summary>
BeforeOpen = 0,
/// <summary>
/// A runspace is being established.
/// </summary>
Opening = 1,
/// <summary>
/// The runspace is established and valid.
/// </summary>
Opened = 2,
/// <summary>
/// The runspace is closed or has not been established.
/// </summary>
Closed = 3,
/// <summary>
/// The runspace is being closed.
/// </summary>
Closing = 4,
/// <summary>
/// The runspace has been disconnected abnormally.
/// </summary>
Broken = 5,
/// <summary>
/// The runspace is being disconnected.
/// </summary>
Disconnecting = 6,
/// <summary>
/// The runspace is disconnected.
/// </summary>
Disconnected = 7,
/// <summary>
/// The runspace is Connecting.
/// </summary>
Connecting = 8
}
/// <summary>
/// These options control whether a new thread is created when a command is executed within a runspace.
/// </summary>
public enum PSThreadOptions
{
/// <summary>
/// Use the default options: UseNewThread for local Runspace, ReuseThread for local RunspacePool, server settings for remote Runspace and RunspacePool.
/// </summary>
Default = 0,
/// <summary>
/// Creates a new thread for each invocation.
/// </summary>
UseNewThread = 1,
/// <summary>
/// Creates a new thread for the first invocation and then re-uses
/// that thread in subsequent invocations.
/// </summary>
ReuseThread = 2,
/// <summary>
/// Doesn't create a new thread; the execution occurs on the thread
/// that calls Invoke. This option is not valid for asynchronous calls.
/// </summary>
UseCurrentThread = 3
}
/// <summary>
/// Defines type which has information about RunspaceState and
/// Exception associated with RunspaceState.
/// </summary>
public sealed class RunspaceStateInfo
{
#region constructors
/// <summary>
/// Constructor for state changes not resulting from an error.
/// </summary>
/// <param name="state">The state of the runspace.</param>
internal RunspaceStateInfo(RunspaceState state)
: this(state, null)
{
}
/// <summary>
/// Constructor for state changes with an optional error.
/// </summary>
/// <param name="state">The state of runspace.</param>
/// <param name="reason">A non-null exception if the state change was
/// caused by an error, otherwise; null.
/// </param>
internal RunspaceStateInfo(RunspaceState state, Exception reason)
: base()
{
State = state;
Reason = reason;
}
/// <summary>
/// Copy constructor to support cloning.
/// </summary>
/// <param name="runspaceStateInfo">The source
/// RunspaceStateInfo
/// </param>
internal RunspaceStateInfo(RunspaceStateInfo runspaceStateInfo)
{
State = runspaceStateInfo.State;
Reason = runspaceStateInfo.Reason;
}
#endregion constructors
#region public_properties
/// <summary>
/// The state of the runspace.
/// </summary>
public RunspaceState State { get; }
/// <summary>
/// The reason for the state change, if caused by an error.
/// </summary>
/// <remarks>
/// The value of this property is non-null if the state
/// changed due to an error. Otherwise, the value of this
/// property is null.
/// </remarks>
public Exception Reason { get; }
#endregion public_properties
/// <summary>
/// Override for ToString()
/// </summary>
/// <returns></returns>
public override string ToString()
{
return State.ToString();
}
/// <summary>
/// Clones current object.
/// </summary>
/// <returns>Cloned object.</returns>
internal RunspaceStateInfo Clone()
{
return new RunspaceStateInfo(this);
}
#region private_fields
#endregion private_fields
}
/// <summary>
/// Defines Event arguments passed to RunspaceStateEvent handler
/// <see cref="Runspace.StateChanged"/> event.
/// </summary>
public sealed class RunspaceStateEventArgs : EventArgs
{
#region constructors
/// <summary>
/// Constructs RunspaceStateEventArgs using RunspaceStateInfo.
/// </summary>
/// <param name="runspaceStateInfo">The information about
/// current state of the runspace.</param>
/// <exception cref="ArgumentNullException">RunspaceStateInfo is null
/// </exception>
internal RunspaceStateEventArgs(RunspaceStateInfo runspaceStateInfo)
{
if (runspaceStateInfo == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(runspaceStateInfo));
}
RunspaceStateInfo = runspaceStateInfo;
}
#endregion constructors
#region public_properties
/// <summary>
/// Information about state of the runspace.
/// </summary>
/// <remarks>
/// This value indicates the state of the runspace after the
/// change.
/// </remarks>
public RunspaceStateInfo RunspaceStateInfo { get; }
#endregion public_properties
}
/// <summary>
/// Enum to indicate whether a Runspace is busy or available.
/// </summary>
public enum RunspaceAvailability
{
/// <summary>
/// The Runspace is not been in the Opened state.
/// </summary>
None = 0,
/// <summary>
/// The Runspace is available to execute commands.
/// </summary>
Available,
/// <summary>
/// The Runspace is available to execute nested commands.
/// </summary>
AvailableForNestedCommand,
/// <summary>
/// The Runspace is busy executing a command.
/// </summary>
Busy,
/// <summary>
/// Applies only to remote runspace case. The remote runspace
/// is currently in a Debugger Stop mode and requires a debugger
/// SetDebuggerAction() call to continue.
/// </summary>
RemoteDebug
}
/// <summary>
/// Defines the event arguments passed to the AvailabilityChanged <see cref="Runspace.AvailabilityChanged"/> event.
/// </summary>
public sealed class RunspaceAvailabilityEventArgs : EventArgs
{
internal RunspaceAvailabilityEventArgs(RunspaceAvailability runspaceAvailability)
{
RunspaceAvailability = runspaceAvailability;
}
/// <summary>
/// Whether the Runspace is available to execute commands.
/// </summary>
public RunspaceAvailability RunspaceAvailability { get; }
}
#endregion Runspace state
#region Runspace capabilities
/// <summary>
/// Defines runspace capabilities.
/// </summary>
public enum RunspaceCapability
{
/// <summary>
/// Legacy capabilities for WinRM only, from Win7 timeframe.
/// </summary>
Default = 0x0,
/// <summary>
/// Runspace and remoting layer supports disconnect/connect feature.
/// </summary>
SupportsDisconnect = 0x1,
/// <summary>
/// Runspace is based on a named pipe transport.
/// </summary>
NamedPipeTransport = 0x2,
/// <summary>
/// Runspace is based on a VM socket transport.
/// </summary>
VMSocketTransport = 0x4,
/// <summary>
/// Runspace is based on SSH transport.
/// </summary>
SSHTransport = 0x8,
/// <summary>
/// Runspace is based on open custom connection/transport support.
/// </summary>
CustomTransport = 0x100
}
#endregion
/// <summary>
/// Public interface to PowerShell Runtime. Provides APIs for creating pipelines,
/// access session state etc.
/// </summary>
public abstract class Runspace : IDisposable
{
#region Private Data
private static int s_globalId;
private readonly Stack<PowerShell> _runningPowerShells;
private PowerShell _baseRunningPowerShell;
private readonly object _syncObject;
#endregion
#region constructor
/// <summary>
/// Explicit default constructor.
/// </summary>
internal Runspace()
{
// Create the default Runspace Id and friendly name.
Id = System.Threading.Interlocked.Increment(ref s_globalId);
Name = "Runspace" + Id.ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
_runningPowerShells = new Stack<PowerShell>();
_syncObject = new object();
// Keep track of this runspace until it is disposed.
lock (s_syncObject)
{
s_runspaceDictionary.Add(Id, new WeakReference<Runspace>(this));
}
}
/// <summary>
/// Static Constructor.
/// </summary>
static Runspace()
{
s_syncObject = new object();
s_runspaceDictionary = new SortedDictionary<int, WeakReference<Runspace>>();
s_globalId = 0;
}
#endregion constructor
#region properties
/// <summary>
/// Used to store Runspace reference on per thread basis. Used by
/// various PowerShell engine features to get access to TypeTable
/// etc.
/// </summary>
[ThreadStatic]
private static Runspace t_threadSpecificDefaultRunspace = null;
/// <summary>
/// Gets and sets the default Runspace used to evaluate scripts.
/// </summary>
/// <remarks>The Runspace used to set this property should not be shared between different threads.</remarks>
public static Runspace DefaultRunspace
{
get
{
return t_threadSpecificDefaultRunspace;
}
set
{
if (value == null || !value.RunspaceIsRemote)
{
t_threadSpecificDefaultRunspace = value;
}
else
{
throw new InvalidOperationException(RunspaceStrings.RunspaceNotLocal);
}
}
}
/// <summary>
/// A PrimaryRunspace is a runspace that persists for the entire lifetime of the PowerShell session. It is only
/// closed or disposed when the session is ending. So when the PrimaryRunspace is closing it will trigger on-exit
/// cleanup that includes closing any other local runspaces left open, and will allow the process to exit.
/// </summary>
internal static Runspace PrimaryRunspace
{
get
{
return s_primaryRunspace;
}
set
{
var result = Interlocked.CompareExchange<Runspace>(ref s_primaryRunspace, value, null);
if (result != null)
{
throw new PSInvalidOperationException(RunspaceStrings.PrimaryRunspaceAlreadySet);
}
}
}
private static Runspace s_primaryRunspace;
/// <summary>
/// Returns true if Runspace.DefaultRunspace can be used to
/// create an instance of the PowerShell class with
/// 'UseCurrentRunspace = true'.
/// </summary>
public static bool CanUseDefaultRunspace
{
// can use default runspace in a thread safe manner only if
// 1. we have a default runspace
// 2. we recognize the type of current runspace and current pipeline
// 3. the pipeline executes on the same thread as this method
// we don't return "true" for
// 1. we have a default runspace
// 2. no currently executing pipeline
// to avoid a race condition where a pipeline is started
// after this property getter did all the checks
get
{
RunspaceBase runspace = Runspace.DefaultRunspace as RunspaceBase;
if (runspace != null)
{
Pipeline currentPipeline = runspace.GetCurrentlyRunningPipeline();
LocalPipeline localPipeline = currentPipeline as LocalPipeline;
if ((localPipeline != null) && (localPipeline.NestedPipelineExecutionThread != null))
{
return
(localPipeline.NestedPipelineExecutionThread.ManagedThreadId
== Environment.CurrentManagedThreadId);
}
}
return false;
}
}
internal const ApartmentState DefaultApartmentState = ApartmentState.Unknown;
/// <summary>
/// ApartmentState of the thread used to execute commands within this Runspace.
/// </summary>
/// <remarks>
/// Any updates to the value of this property must be done before the Runspace is opened
/// </remarks>
/// <exception cref="InvalidRunspaceStateException">
/// An attempt to change this property was made after opening the Runspace
/// </exception>
public ApartmentState ApartmentState
{
get
{
return this.apartmentState;
}
set
{
if (this.RunspaceStateInfo.State != RunspaceState.BeforeOpen)
{
throw new InvalidRunspaceStateException(StringUtil.Format(RunspaceStrings.ChangePropertyAfterOpen));
}
this.apartmentState = value;
}
}
private ApartmentState apartmentState = Runspace.DefaultApartmentState;
/// <summary>
/// This property determines whether a new thread is create for each invocation.
/// </summary>
/// <remarks>
/// Any updates to the value of this property must be done before the Runspace is opened
/// </remarks>
/// <exception cref="InvalidRunspaceStateException">
/// An attempt to change this property was made after opening the Runspace
/// </exception>
/// <exception cref="InvalidOperationException">
/// The thread options cannot be changed to the requested value
/// </exception>
public abstract PSThreadOptions ThreadOptions
{
get;
set;
}
/// <summary>
/// Return version of this runspace.
/// </summary>
public abstract Version Version
{
get;
}
/// <summary>
/// Return whether the Runspace is Remote
/// We can determine this by whether the runspace is an implementation of LocalRunspace
/// or infer it from whether the ConnectionInfo property is null
/// If it happens to be an instance of a LocalRunspace, but has a non-null ConnectionInfo
/// we declare it to be remote.
/// </summary>
public bool RunspaceIsRemote
{
get
{
return this is not LocalRunspace && ConnectionInfo != null;
}
}
/// <summary>
/// Retrieve information about current state of the runspace.
/// </summary>
public abstract RunspaceStateInfo RunspaceStateInfo
{
get;
}
/// <summary>
/// Gets the current availability of the Runspace.
/// </summary>
public abstract RunspaceAvailability RunspaceAvailability
{
get;
protected set;
}
/// <summary>
/// InitialSessionState information for this runspace.
/// </summary>
public abstract InitialSessionState InitialSessionState
{
get;
}
/// <summary>
/// Get unique id for this instance of runspace. It is primarily used
/// for logging purposes.
/// </summary>
public Guid InstanceId
{
get;
// This id is also used to identify proxy and remote runspace objects.
// We need to set this when reconstructing a remote runspace to connect
// to an existing remote runspace.
internal set;
} = Guid.NewGuid();
/// <summary>
/// Gets execution context.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">Runspace is not opened.
/// </exception>
internal ExecutionContext ExecutionContext
{
get
{
return GetExecutionContext;
}
}
/// <summary>
/// Skip user profile on engine initialization.
/// </summary>
internal bool SkipUserProfile { get; set; } = false;
/// <summary>
/// Connection information for remote Runspaces, null for local Runspaces.
/// </summary>
public abstract RunspaceConnectionInfo ConnectionInfo { get; }
/// <summary>
/// ConnectionInfo originally supplied by the user.
/// </summary>
public abstract RunspaceConnectionInfo OriginalConnectionInfo { get; }
/// <summary>
/// Manager for JobSourceAdapters registered in this runspace.
/// </summary>
public abstract JobManager JobManager { get; }
/// <summary>
/// DisconnectedOn property applies to remote runspaces that have
/// been disconnected.
/// </summary>
public DateTime? DisconnectedOn
{
get;
internal set;
}
/// <summary>
/// ExpiresOn property applies to remote runspaces that have been
/// disconnected.
/// </summary>
public DateTime? ExpiresOn
{
get;
internal set;
}
/// <summary>
/// Gets and sets a friendly name for the Runspace.
/// </summary>
public string Name
{
get;
set;
}
/// <summary>
/// Gets the Runspace Id.
/// </summary>
public int Id { get; }
/// <summary>
/// Gets and sets a boolean indicating whether the runspace has a
/// debugger attached with <c>Debug-Runspace</c>.
/// </summary>
public bool IsRemoteDebuggerAttached { get; internal set; }
/// <summary>
/// Returns protocol version that the remote server uses for PS remoting.
/// </summary>
internal Version GetRemoteProtocolVersion()
{
Version remoteProtocolVersionDeclaredByServer;
bool isServerDeclarationValid = PSPrimitiveDictionary.TryPathGet(
this.GetApplicationPrivateData(),
out remoteProtocolVersionDeclaredByServer,
PSVersionInfo.PSVersionTableName,
PSVersionInfo.PSRemotingProtocolVersionName);
if (isServerDeclarationValid)
{
return remoteProtocolVersionDeclaredByServer;
}
else
{
return RemotingConstants.ProtocolVersion;
}
}
/// <summary>
/// Engine activity id (for ETW tracing)
/// </summary>
internal Guid EngineActivityId { get; set; } = Guid.Empty;
/// <summary>
/// Returns a read only runspace dictionary.
/// </summary>
internal static ReadOnlyDictionary<int, WeakReference<Runspace>> RunspaceDictionary
{
get
{
lock (s_syncObject)
{
return new ReadOnlyDictionary<int, WeakReference<Runspace>>(new Dictionary<int, WeakReference<Runspace>>(s_runspaceDictionary));
}
}
}
private static readonly SortedDictionary<int, WeakReference<Runspace>> s_runspaceDictionary;
private static readonly object s_syncObject;
/// <summary>
/// Returns a read only list of runspaces.
/// </summary>
internal static IReadOnlyList<Runspace> RunspaceList
{
get
{
List<Runspace> runspaceList = new List<Runspace>();
lock (s_syncObject)
{
foreach (var item in s_runspaceDictionary.Values)
{
Runspace runspace;
if (item.TryGetTarget(out runspace))
{
runspaceList.Add(runspace);
}
}
}
return new ReadOnlyCollection<Runspace>(runspaceList);
}
}
#endregion properties
#region events
/// <summary>
/// Event raised when RunspaceState changes.
/// </summary>
public abstract event EventHandler<RunspaceStateEventArgs> StateChanged;
/// <summary>
/// Event raised when the availability of the Runspace changes.
/// </summary>
public abstract event EventHandler<RunspaceAvailabilityEventArgs> AvailabilityChanged;
/// <summary>
/// Returns true if there are any subscribers to the AvailabilityChanged event.
/// </summary>
internal abstract bool HasAvailabilityChangedSubscribers
{
get;
}
/// <summary>
/// Raises the AvailabilityChanged event.
/// </summary>
protected abstract void OnAvailabilityChanged(RunspaceAvailabilityEventArgs e);
/// <summary>
/// Used to raise the AvailabilityChanged event when the state of the currently executing pipeline changes.
/// </summary>
/// <remarks>
/// The possible pipeline states are
/// NotStarted
/// Running
/// Disconnected
/// Stopping
/// Stopped
/// Completed
/// Failed
/// </remarks>
internal void UpdateRunspaceAvailability(PipelineState pipelineState, bool raiseEvent, Guid? cmdInstanceId = null)
{
RunspaceAvailability oldAvailability = this.RunspaceAvailability;
switch (oldAvailability)
{
// Because of disconnect/connect support runspace availability can now transition
// in and out of "None" state.
case RunspaceAvailability.None:
switch (pipelineState)
{
case PipelineState.Running:
this.RunspaceAvailability = RunspaceAvailability.Busy;
break;
// Otherwise no change.
}
break;
case RunspaceAvailability.Available:
switch (pipelineState)
{
case PipelineState.Running:
this.RunspaceAvailability = RunspaceAvailability.Busy;
break;
case PipelineState.Disconnected:
this.RunspaceAvailability = Runspaces.RunspaceAvailability.None;
break;
}
break;
case RunspaceAvailability.AvailableForNestedCommand:
switch (pipelineState)
{
case PipelineState.Running:
this.RunspaceAvailability = RunspaceAvailability.Busy;
break;
case PipelineState.Completed: // a nested pipeline caused the host to exit nested prompt
this.RunspaceAvailability = (this.InNestedPrompt || (_runningPowerShells.Count > 1)) ?
RunspaceAvailability.AvailableForNestedCommand : RunspaceAvailability.Available;
break;
default:
break; // no change in the availability
}
break;
case RunspaceAvailability.Busy:
case RunspaceAvailability.RemoteDebug:
switch (pipelineState)
{
case PipelineState.Disconnected:
if (oldAvailability == Runspaces.RunspaceAvailability.RemoteDebug)
{
this.RunspaceAvailability = RunspaceAvailability.RemoteDebug;
}
else
{
this.RunspaceAvailability = RunspaceAvailability.None;
}
break;
case PipelineState.Stopping:
break; // no change in the availability
case PipelineState.Completed:
case PipelineState.Stopped:
case PipelineState.Failed:
if (this.InNestedPrompt
|| (this is not RemoteRunspace && this.Debugger.InBreakpoint))
{
this.RunspaceAvailability = RunspaceAvailability.AvailableForNestedCommand;
}
else
{
RemoteRunspace remoteRunspace = this as RemoteRunspace;
RemoteDebugger remoteDebugger = (remoteRunspace != null) ? remoteRunspace.Debugger as RemoteDebugger : null;
Internal.ConnectCommandInfo remoteCommand = remoteRunspace?.RemoteCommand;
if (((pipelineState == PipelineState.Completed) || (pipelineState == PipelineState.Failed) ||
((pipelineState == PipelineState.Stopped) && (this.RunspaceStateInfo.State == RunspaceState.Opened)))
&& (remoteCommand != null) && (cmdInstanceId != null) && (remoteCommand.CommandId == cmdInstanceId))
{
// Completed, Failed, and Stopped with Runspace.Opened states are command finish states and we know
// that the command is finished on the server.
// Setting ConnectCommands to null indicates that the runspace is free to run other
// commands.
remoteRunspace.RunspacePool.RemoteRunspacePoolInternal.ConnectCommands = null;
remoteCommand = null;
if ((remoteDebugger != null) && (pipelineState == PipelineState.Stopped))
{
// Notify remote debugger of a stop in case the stop occurred while command was in debug stop.
remoteDebugger.OnCommandStopped();
}
}
Pipeline currentPipeline = this.GetCurrentlyRunningPipeline();
RemotePipeline remotePipeline = currentPipeline as RemotePipeline;
Guid? pipeLineCmdInstance = (remotePipeline != null && remotePipeline.PowerShell != null) ? remotePipeline.PowerShell.InstanceId : (Guid?)null;
if (currentPipeline == null)
{
// A runspace is available:
// - if there is no currently running pipeline
// and for remote runspaces:
// - if there is no remote command associated with it.
// - if the remote runspace pool is marked as available for connection.
if (remoteCommand == null)
{
if (remoteRunspace != null)
{
if ((remoteDebugger != null) && (pipelineState == PipelineState.Stopped))
{
// Notify remote debugger of a stop in case the stop occurred while command was in debug stop.
remoteDebugger.OnCommandStopped();
}
this.RunspaceAvailability =
remoteRunspace.RunspacePool.RemoteRunspacePoolInternal.AvailableForConnection ?
RunspaceAvailability.Available : Runspaces.RunspaceAvailability.Busy;
}
else
{
this.RunspaceAvailability = RunspaceAvailability.Available;
}
}
}
else if ((cmdInstanceId != null) && (pipeLineCmdInstance != null) && (cmdInstanceId == pipeLineCmdInstance))
{
if ((remoteDebugger != null) && (pipelineState == PipelineState.Stopped))
{
// Notify remote debugger of a stop in case the stop occurred while command was in debug stop.
remoteDebugger.OnCommandStopped();
}
this.RunspaceAvailability = RunspaceAvailability.Available;
}
else // a nested pipeline completed, but the parent pipeline is still running
{
if (oldAvailability == Runspaces.RunspaceAvailability.RemoteDebug)
{
this.RunspaceAvailability = Runspaces.RunspaceAvailability.RemoteDebug;
}
else if ((currentPipeline.PipelineStateInfo.State == PipelineState.Running) || (_runningPowerShells.Count > 1))
{
// Either the current pipeline is running or there are other nested commands to run in the Runspace.
this.RunspaceAvailability = RunspaceAvailability.Busy;
}
else
{
this.RunspaceAvailability = RunspaceAvailability.Available;
}
}
}
break;
case PipelineState.Running: // this can happen if a nested pipeline is created without entering a nested prompt
break; // no change in the availability
default:
break; // no change in the availability
}
break;
default:
Diagnostics.Assert(false, "Invalid RunspaceAvailability");
break;
}
if (raiseEvent && this.RunspaceAvailability != oldAvailability)
{
OnAvailabilityChanged(new RunspaceAvailabilityEventArgs(this.RunspaceAvailability));
}
}
/// <summary>
/// Used to update the runspace availability when the state of the currently executing PowerShell instance changes.
/// </summary>
/// <remarks>
/// The possible invocation states are
/// NotStarted
/// Running
/// Stopping
/// Stopped
/// Completed
/// Failed
/// </remarks>
internal void UpdateRunspaceAvailability(PSInvocationState invocationState, bool raiseEvent, Guid cmdInstanceId)
{
switch (invocationState)
{
case PSInvocationState.NotStarted:
UpdateRunspaceAvailability(PipelineState.NotStarted, raiseEvent, cmdInstanceId);
break;
case PSInvocationState.Running:
UpdateRunspaceAvailability(PipelineState.Running, raiseEvent, cmdInstanceId);
break;
case PSInvocationState.Completed:
UpdateRunspaceAvailability(PipelineState.Completed, raiseEvent, cmdInstanceId);
break;
case PSInvocationState.Failed:
UpdateRunspaceAvailability(PipelineState.Failed, raiseEvent, cmdInstanceId);
break;
case PSInvocationState.Stopping:
UpdateRunspaceAvailability(PipelineState.Stopping, raiseEvent, cmdInstanceId);
break;
case PSInvocationState.Stopped:
UpdateRunspaceAvailability(PipelineState.Stopped, raiseEvent, cmdInstanceId);
break;
case PSInvocationState.Disconnected:
UpdateRunspaceAvailability(PipelineState.Disconnected, raiseEvent, cmdInstanceId);
break;
default:
Diagnostics.Assert(false, "Invalid PSInvocationState");
break;
}
}
/// <summary>
/// Used to update the runspace availability event when the state of the runspace changes.
/// </summary>
/// <remarks>
/// The possible runspace states are:
/// BeforeOpen
/// Opening
/// Opened
/// Closed
/// Closing
/// Broken
/// </remarks>
protected void UpdateRunspaceAvailability(RunspaceState runspaceState, bool raiseEvent)
{
RunspaceAvailability oldAvailability = this.RunspaceAvailability;
RemoteRunspace remoteRunspace = this as RemoteRunspace;
Internal.ConnectCommandInfo remoteCommand = null;
bool remoteDebug = false;
if (remoteRunspace != null)
{
remoteCommand = remoteRunspace.RemoteCommand;
RemoteDebugger remoteDebugger = remoteRunspace.Debugger as RemoteDebugger;
remoteDebug = (remoteDebugger != null) && remoteDebugger.IsRemoteDebug;
}
switch (oldAvailability)
{
case RunspaceAvailability.None:
switch (runspaceState)
{
case RunspaceState.Opened:
if (remoteDebug)
{
this.RunspaceAvailability = Runspaces.RunspaceAvailability.RemoteDebug;
}
else
{
this.RunspaceAvailability = (remoteCommand == null && GetCurrentlyRunningPipeline() == null) ?
RunspaceAvailability.Available : RunspaceAvailability.Busy;
}
break;
default:
break; // no change in the availability
}
break;
case RunspaceAvailability.Available:
case RunspaceAvailability.AvailableForNestedCommand:
case RunspaceAvailability.RemoteDebug:
case RunspaceAvailability.Busy:
switch (runspaceState)
{
case RunspaceState.Closing:
case RunspaceState.Closed:
case RunspaceState.Broken:
case RunspaceState.Disconnected:
this.RunspaceAvailability = RunspaceAvailability.None;
break;
default:
break; // no change in the availability
}
break;
default:
Diagnostics.Assert(false, "Invalid RunspaceAvailability");
break;
}
if (raiseEvent && this.RunspaceAvailability != oldAvailability)
{
OnAvailabilityChanged(new RunspaceAvailabilityEventArgs(this.RunspaceAvailability));
}
}
/// <summary>
/// Used to update the runspace availability from Enter/ExitNestedPrompt and the debugger.
/// </summary>
internal void UpdateRunspaceAvailability(RunspaceAvailability availability, bool raiseEvent)
{
RunspaceAvailability oldAvailability = this.RunspaceAvailability;
this.RunspaceAvailability = availability;
if (raiseEvent && this.RunspaceAvailability != oldAvailability)
{
OnAvailabilityChanged(new RunspaceAvailabilityEventArgs(this.RunspaceAvailability));
}
}
/// <summary>
/// Raises the AvailabilityChanged event.
/// </summary>
internal void RaiseAvailabilityChangedEvent(RunspaceAvailability availability)
{
OnAvailabilityChanged(new RunspaceAvailabilityEventArgs(availability));
}
#endregion events
#region Public static methods
/// <summary>
/// Queries the server for disconnected runspaces and creates an array of runspace
/// objects associated with each disconnected runspace on the server. Each
/// runspace object in the returned array is in the Disconnected state and can be
/// connected to the server by calling the Connect() method on the runspace.
/// </summary>
/// <param name="connectionInfo">Connection object for the target server.</param>
/// <returns>Array of Runspace objects each in the Disconnected state.</returns>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspaces")]
public static Runspace[] GetRunspaces(RunspaceConnectionInfo connectionInfo)
{
return GetRunspaces(connectionInfo, null, null);
}
/// <summary>
/// Queries the server for disconnected runspaces and creates an array of runspace
/// objects associated with each disconnected runspace on the server. Each
/// runspace object in the returned array is in the Disconnected state and can be
/// connected to the server by calling the Connect() method on the runspace.
/// </summary>
/// <param name="connectionInfo">Connection object for the target server.</param>
/// <param name="host">Client host object.</param>
/// <returns>Array of Runspace objects each in the Disconnected state.</returns>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspaces")]
public static Runspace[] GetRunspaces(RunspaceConnectionInfo connectionInfo, PSHost host)
{
return GetRunspaces(connectionInfo, host, null);
}
/// <summary>
/// Queries the server for disconnected runspaces and creates an array of runspace
/// objects associated with each disconnected runspace on the server. Each
/// runspace object in the returned array is in the Disconnected state and can be
/// connected to the server by calling the Connect() method on the runspace.
/// </summary>
/// <param name="connectionInfo">Connection object for the target server.</param>
/// <param name="host">Client host object.</param>
/// <param name="typeTable">TypeTable object.</param>
/// <returns>Array of Runspace objects each in the Disconnected state.</returns>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspaces")]
public static Runspace[] GetRunspaces(RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable)
{
return RemoteRunspace.GetRemoteRunspaces(connectionInfo, host, typeTable);
}
/// <summary>
/// Returns a single disconnected Runspace object targeted to the remote computer and remote
/// session as specified by the connection, session Id, and command Id parameters.
/// </summary>
/// <param name="connectionInfo">Connection object for the target server.</param>
/// <param name="sessionId">Id of a disconnected remote session on the target server.</param>
/// <param name="commandId">Optional Id of a disconnected command running in the disconnected remote session on the target server.</param>
/// <param name="host">Optional client host object.</param>
/// <param name="typeTable">Optional TypeTable object.</param>
/// <returns>Disconnected runspace corresponding to the provided session Id.</returns>
public static Runspace GetRunspace(RunspaceConnectionInfo connectionInfo, Guid sessionId, Guid? commandId, PSHost host, TypeTable typeTable)
{
return RemoteRunspace.GetRemoteRunspace(connectionInfo, sessionId, commandId, host, typeTable);
}
#endregion
#region public Disconnect-Connect methods
/// <summary>
/// Disconnects the runspace synchronously.
/// </summary>
/// <remarks>
/// Disconnects the remote runspace and any running command from the server
/// machine. Any data generated by the running command on the server is
/// cached on the server machine. This runspace object goes to the disconnected
/// state. This object can be reconnected to the server by calling the
/// Connect() method.
/// If the remote runspace on the server remains disconnected for the IdleTimeout
/// value (as defined in the WSManConnectionInfo object) then it is closed and
/// torn down on the server.
/// </remarks>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is not Opened.
/// </exception>
public abstract void Disconnect();
/// <summary>
/// Disconnects the runspace asynchronously.
/// </summary>
/// <remarks>
/// Disconnects the remote runspace and any running command from the server
/// machine. Any data generated by the running command on the server is
/// cached on the server machine. This runspace object goes to the disconnected
/// state. This object can be reconnected to the server by calling the
/// Connect() method.
/// If the remote runspace on the server remains disconnected for the IdleTimeout
/// value (as defined in the WSManConnectionInfo object) then it is closed and
/// torn down on the server.
/// </remarks>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is not Opened.
/// </exception>
public abstract void DisconnectAsync();
/// <summary>
/// Connects the runspace to its remote counterpart synchronously.
/// </summary>
/// <remarks>
/// Connects the runspace object to its corresponding runspace on the target
/// server machine. The target server machine is identified by the connection
/// object passed in during construction. The remote runspace is identified
/// by the internal runspace Guid value.
/// </remarks>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is not Disconnected.
/// </exception>
public abstract void Connect();
/// <summary>
/// Connects a runspace to its remote counterpart asynchronously.
/// </summary>
/// <remarks>
/// Connects the runspace object to its corresponding runspace on the target
/// server machine. The target server machine is identified by the connection
/// object passed in during construction. The remote runspace is identified
/// by the internal runspace Guid value.
/// </remarks>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is not Disconnected.
/// </exception>
public abstract void ConnectAsync();
/// <summary>
/// Creates a PipeLine object in the disconnected state for the currently disconnected
/// remote running command associated with this runspace.
/// </summary>
/// <returns>Pipeline object in disconnected state.</returns>
public abstract Pipeline CreateDisconnectedPipeline();
/// <summary>
/// Creates a PowerShell object in the disconnected state for the currently disconnected
/// remote running command associated with this runspace.
/// </summary>
/// <returns>PowerShell object in disconnected state.</returns>
public abstract PowerShell CreateDisconnectedPowerShell();
/// <summary>
/// Returns Runspace capabilities.
/// </summary>
/// <returns>RunspaceCapability.</returns>
public abstract RunspaceCapability GetCapabilities();
#endregion
#region methods
/// <summary>
/// Opens the runspace synchronously. Runspace must be opened before it can be used.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is not BeforeOpen
/// </exception>
public abstract void Open();
/// <summary>
/// Open the runspace Asynchronously.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is not BeforeOpen
/// </exception>
public abstract void OpenAsync();
/// <summary>
/// Close the runspace synchronously.
/// </summary>
/// <remarks>
/// Attempts to execute pipelines after a call to close will fail.
/// </remarks>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is BeforeOpen or Opening
/// </exception>
public abstract void Close();
/// <summary>
/// Close the runspace Asynchronously.
/// </summary>
/// <remarks>
/// Attempts to execute pipelines after a call to
/// close will fail.
/// </remarks>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is BeforeOpen or Opening
/// </exception>
public abstract void CloseAsync();
/// <summary>
/// Create an empty pipeline.
/// </summary>
/// <returns>An empty pipeline.</returns>
public abstract Pipeline CreatePipeline();
/// <summary>
/// Creates a pipeline for specified command string.
/// </summary>
/// <param name="command">A valid command string.</param>
/// <returns>
/// A pipeline pre-filled with a <see cref="Command"/> object for specified command parameter.
/// </returns>
/// <exception cref="ArgumentNullException">
/// command is null
/// </exception>
public abstract Pipeline CreatePipeline(string command);
/// <summary>
/// Create a pipeline from a command string.
/// </summary>
/// <param name="command">A valid command string.</param>
/// <param name="addToHistory">If true command is added to history.</param>
/// <returns>
/// A pipeline pre-filled with a <see cref="Command"/> object for specified command parameter.
/// </returns>
/// <exception cref="ArgumentNullException">
/// command is null
/// </exception>
public abstract Pipeline CreatePipeline(string command, bool addToHistory);
/// <summary>
/// Creates a nested pipeline.
/// </summary>
/// <remarks>
/// Nested pipelines are needed for nested prompt scenario. Nested
/// prompt requires that we execute new pipelines( child pipelines)
/// while current pipeline (lets call it parent pipeline) is blocked.
/// </remarks>
public abstract Pipeline CreateNestedPipeline();
/// <summary>
/// Creates a nested pipeline.
/// </summary>
/// <param name="command">A valid command string.</param>
/// <param name="addToHistory">If true command is added to history.</param>
/// <returns>
/// A pipeline pre-filled with Command specified in commandString.
/// </returns>
/// <exception cref="ArgumentNullException">
/// command is null
/// </exception>
public abstract Pipeline CreateNestedPipeline(string command, bool addToHistory);
/// <summary>
/// Returns the currently executing pipeline, or null if no pipeline is executing.
/// </summary>
internal abstract Pipeline GetCurrentlyRunningPipeline();
/// <summary>
/// Private data to be used by applications built on top of PowerShell.
///
/// Local runspace is created with application private data set to an empty <see cref="PSPrimitiveDictionary"/>.
///
/// Remote runspace gets its application private data from the server (set when creating a remote runspace pool)
/// Calling this method on a remote runspace will block until the data is received from the server.
/// The server will send application private data before reaching <see cref="RunspacePoolState.Opened"/> state.
///
/// Runspaces that are part of a <see cref="RunspacePool"/> inherit application private data from the pool.
/// </summary>
public abstract PSPrimitiveDictionary GetApplicationPrivateData();
/// <summary>
/// A method that runspace pools can use to propagate application private data into runspaces.
/// </summary>
/// <param name="applicationPrivateData"></param>
internal abstract void SetApplicationPrivateData(PSPrimitiveDictionary applicationPrivateData);
/// <summary>
/// Push a running PowerShell onto the stack.
/// </summary>
/// <param name="ps">PowerShell.</param>
internal void PushRunningPowerShell(PowerShell ps)
{
Dbg.Assert(ps != null, "Caller should not pass in null reference.");
lock (_syncObject)
{
_runningPowerShells.Push(ps);
if (_runningPowerShells.Count == 1)
{
_baseRunningPowerShell = ps;
}
}
}
/// <summary>
/// Pop the currently running PowerShell from stack.
/// </summary>
/// <returns>PowerShell.</returns>
internal PowerShell PopRunningPowerShell()
{
lock (_syncObject)
{
int count = _runningPowerShells.Count;
if (count > 0)
{
if (count == 1)
{
_baseRunningPowerShell = null;
}
return _runningPowerShells.Pop();
}
}
return null;
}
internal PowerShell GetCurrentBasePowerShell()
{
return _baseRunningPowerShell;
}
#endregion methods
#region SessionStateProxy
/// <summary>
/// Gets session state proxy.
/// </summary>
public SessionStateProxy SessionStateProxy
{
get
{
return GetSessionStateProxy();
}
}
internal abstract SessionStateProxy GetSessionStateProxy();
#endregion SessionStateProxy
#region IDisposable Members
/// <summary>
/// Disposes this runspace instance. Dispose will close the runspace if not closed already.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Protected dispose which can be overridden by derived classes.
/// </summary>
/// <param name="disposing"></param>
protected virtual void Dispose(bool disposing)
{
lock (s_syncObject)
{
s_runspaceDictionary.Remove(Id);
}
}
#endregion IDisposable Members
/// <summary>
/// Gets the execution context.
/// </summary>
internal abstract ExecutionContext GetExecutionContext
{
get;
}
/// <summary>
/// Returns true if the internal host is in a nested prompt.
/// </summary>
internal abstract bool InNestedPrompt
{
get;
}
/// <summary>
/// Gets the debugger.
/// </summary>
public virtual Debugger Debugger
{
get
{
var context = GetExecutionContext;
return context?.Debugger;
}
}
/// <summary>
/// InternalDebugger.
/// </summary>
internal Debugger InternalDebugger
{
get;
set;
}
/// <summary>
/// Gets the event manager.
/// </summary>
public abstract PSEventManager Events
{
get;
}
#if !CORECLR // Transaction Not Supported On CSS
/// <summary>
/// Sets the base transaction for the runspace; any transactions created on this runspace will be nested to this instance.
/// </summary>
/// <param name="transaction">The base transaction</param>
/// <remarks>This overload uses RollbackSeverity.Error; i.e. the transaction will be rolled back automatically on a non-terminating error or worse</remarks>
public void SetBaseTransaction(System.Transactions.CommittableTransaction transaction)
{
this.ExecutionContext.TransactionManager.SetBaseTransaction(transaction, RollbackSeverity.Error);
}
/// <summary>
/// Sets the base transaction for the runspace; any transactions created on this runspace will be nested to this instance.
/// </summary>
/// <param name="transaction">The base transaction</param>
/// <param name="severity">The severity of error that causes PowerShell to automatically rollback the transaction</param>
public void SetBaseTransaction(System.Transactions.CommittableTransaction transaction, RollbackSeverity severity)
{
this.ExecutionContext.TransactionManager.SetBaseTransaction(transaction, severity);
}
/// <summary>
/// Clears the transaction set by SetBaseTransaction()
/// </summary>
public void ClearBaseTransaction()
{
this.ExecutionContext.TransactionManager.ClearBaseTransaction();
}
#endif
/// <summary>
/// Resets the variable table for the runspace to the default state.
/// </summary>
public virtual void ResetRunspaceState()
{
throw new NotImplementedException("ResetRunspaceState");
}
// Used for pipeline id generation.
private long _pipelineIdSeed;
// Generate pipeline id unique to this runspace
internal long GeneratePipelineId()
{
return System.Threading.Interlocked.Increment(ref _pipelineIdSeed);
}
}
/// <summary>
/// This class provides subset of functionality provided by
/// session state.
/// </summary>
public class SessionStateProxy
{
internal SessionStateProxy()
{
}
private readonly RunspaceBase _runspace;
internal SessionStateProxy(RunspaceBase runspace)
{
Dbg.Assert(runspace != null, "Caller should validate the parameter");
_runspace = runspace;
}
/// <summary>
/// Set a variable in session state.
/// </summary>
/// <param name="name">
/// The name of the item to set.
/// </param>
/// <param name="value">
/// The new value of the item being set.
/// </param>
/// <exception cref="ArgumentNullException">
/// name is null
/// </exception>
/// <exception cref="InvalidRunspaceStateException">
/// Runspace is not open.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Another SessionStateProxy call or another pipeline is in progress.
/// </exception>
public virtual void SetVariable(string name, object value)
{
if (name == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(name));
}
_runspace.SetVariable(name, value);
}
/// <summary>
/// Get a variable out of session state.
/// </summary>
/// <param name="name">
/// name of variable to look up
/// </param>
/// <returns>
/// The value of the specified variable.
/// </returns>
/// <exception cref="ArgumentNullException">
/// name is null
/// </exception>
/// <exception cref="InvalidRunspaceStateException">
/// Runspace is not open.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Another SessionStateProxy call or another pipeline is in progress.
/// </exception>
public virtual object GetVariable(string name)
{
if (name == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(name));
}
if (name.Equals(string.Empty))
{
return null;
}
return _runspace.GetVariable(name);
}
/// <summary>
/// Get the list of applications out of session state.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// Runspace is not open.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Another SessionStateProxy call or another pipeline is in progress.
/// </exception>
public virtual List<string> Applications
{
get
{
return _runspace.Applications;
}
}
/// <summary>
/// Get the list of scripts out of session state.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// Runspace is not open.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Another SessionStateProxy call or another pipeline is in progress.
/// </exception>
public virtual List<string> Scripts
{
get
{
return _runspace.Scripts;
}
}
/// <summary>
/// Get the APIs to access drives out of session state.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// Runspace is not open.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Another SessionStateProxy call or another pipeline is in progress.
/// </exception>
public virtual DriveManagementIntrinsics Drive
{
get { return _runspace.Drive; }
}
/// <summary>
/// Get/Set the language mode out of session state.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// Runspace is not open.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Another SessionStateProxy call or another pipeline is in progress.
/// </exception>
public virtual PSLanguageMode LanguageMode
{
get { return _runspace.LanguageMode; }
set { _runspace.LanguageMode = value; }
}
/// <summary>
/// Get the module info out of session state.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// Runspace is not open.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Another SessionStateProxy call or another pipeline is in progress.
/// </exception>
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Shipped this way in V2 before becoming virtual.")]
public virtual PSModuleInfo Module
{
get { return _runspace.Module; }
}
/// <summary>
/// Get the APIs to access paths and locations out of session state.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// Runspace is not open.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Another SessionStateProxy call or another pipeline is in progress.
/// </exception>
public virtual PathIntrinsics Path
{
get { return _runspace.PathIntrinsics; }
}
/// <summary>
/// Get the APIs to access a provider out of session state.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// Runspace is not open.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Another SessionStateProxy call or another pipeline is in progress.
/// </exception>
public virtual CmdletProviderManagementIntrinsics Provider
{
get { return _runspace.Provider; }
}
/// <summary>
/// Get the APIs to access variables out of session state.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// Runspace is not open.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Another SessionStateProxy call or another pipeline is in progress.
/// </exception>
public virtual PSVariableIntrinsics PSVariable
{
get { return _runspace.PSVariable; }
}
/// <summary>
/// Get the APIs to build script blocks and execute script out of session state.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// Runspace is not open.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Another SessionStateProxy call or another pipeline is in progress.
/// </exception>
public virtual CommandInvocationIntrinsics InvokeCommand
{
get { return _runspace.InvokeCommand; }
}
/// <summary>
/// Gets the instance of the provider interface APIs out of session state.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// Runspace is not open.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Another SessionStateProxy call or another pipeline is in progress.
/// </exception>
public virtual ProviderIntrinsics InvokeProvider
{
get { return _runspace.InvokeProvider; }
}
}
}
|