File size: 69,192 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 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.Management.Automation.Runspaces;
using Dbg = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Contains information about a single history entry.
/// </summary>
public class HistoryInfo
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="pipelineId">Id of pipeline in which command associated
/// with this history entry is executed</param>
/// <param name="cmdline">Command string.</param>
/// <param name="status">Status of pipeline execution.</param>
/// <param name="startTime">StartTime of execution.</param>
/// <param name="endTime">EndTime of execution.</param>
internal HistoryInfo(long pipelineId, string cmdline, PipelineState status, DateTime startTime, DateTime endTime)
{
Dbg.Assert(cmdline != null, "caller should validate the parameter");
_pipelineId = pipelineId;
CommandLine = cmdline;
ExecutionStatus = status;
StartExecutionTime = startTime;
EndExecutionTime = endTime;
Cleared = false;
}
/// <summary>
/// Copy constructor to support cloning.
/// </summary>
/// <param name="history"></param>
private HistoryInfo(HistoryInfo history)
{
Id = history.Id;
_pipelineId = history._pipelineId;
CommandLine = history.CommandLine;
ExecutionStatus = history.ExecutionStatus;
StartExecutionTime = history.StartExecutionTime;
EndExecutionTime = history.EndExecutionTime;
Cleared = history.Cleared;
}
/// <summary>
/// Id of this history entry.
/// </summary>
/// <value></value>
public long Id { get; private set; }
/// <summary>
/// CommandLine string.
/// </summary>
/// <value></value>
public string CommandLine { get; private set; }
/// <summary>
/// Execution status of associated pipeline.
/// </summary>
/// <value></value>
public PipelineState ExecutionStatus { get; private set; }
/// <summary>
/// Start time of execution of associated pipeline.
/// </summary>
/// <value></value>
public DateTime StartExecutionTime { get; }
/// <summary>
/// End time of execution of associated pipeline.
/// </summary>
/// <value></value>
public DateTime EndExecutionTime { get; private set; }
/// <summary>
/// The time it took to execute the associeated pipeline.
/// </summary>
public TimeSpan Duration => EndExecutionTime - StartExecutionTime;
/// <summary>
/// Override for ToString() method.
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (string.IsNullOrEmpty(CommandLine))
{
return base.ToString();
}
else
{
return CommandLine;
}
}
/// <summary>
/// Cleared status of an entry.
/// </summary>
internal bool Cleared { get; set; } = false;
/// <summary>
/// Sets Id.
/// </summary>
/// <param name="id"></param>
internal void SetId(long id) => Id = id;
/// <summary>
/// Set status.
/// </summary>
/// <param name="status"></param>
internal void SetStatus(PipelineState status) => ExecutionStatus = status;
/// <summary>
/// Set endtime.
/// </summary>
/// <param name="endTime"></param>
internal void SetEndTime(DateTime endTime) => EndExecutionTime = endTime;
/// <summary>
/// Sets command.
/// </summary>
/// <param name="command"></param>
internal void SetCommand(string command) => CommandLine = command;
/// <summary>
/// Id of the pipeline corresponding to this history entry.
/// </summary>
private readonly long _pipelineId;
/// <summary>
/// Returns a clone of this object.
/// </summary>
/// <returns></returns>
public HistoryInfo Clone()
{
return new HistoryInfo(this);
}
}
/// <summary>
/// This class implements history and provides APIs for adding and fetching
/// entries from history.
/// </summary>
internal class History
{
/// <summary>
/// Default history size.
/// </summary>
internal const int DefaultHistorySize = 4096;
#region constructors
/// <summary>
/// Constructs history store.
/// </summary>
internal History(ExecutionContext context)
{
// Create history size variable. Add ValidateRangeAttribute to
// validate the range.
Collection<Attribute> attrs = new Collection<Attribute>();
attrs.Add(new ValidateRangeAttribute(1, (int)Int16.MaxValue));
PSVariable historySizeVar = new PSVariable(SpecialVariables.HistorySize, DefaultHistorySize, ScopedItemOptions.None, attrs);
historySizeVar.Description = SessionStateStrings.MaxHistoryCountDescription;
context.EngineSessionState.SetVariable(historySizeVar, false, CommandOrigin.Internal);
_capacity = DefaultHistorySize;
_buffer = new HistoryInfo[_capacity];
}
#endregion constructors
#region internal
/// <summary>
/// Create a new history entry.
/// </summary>
/// <param name="pipelineId"></param>
/// <param name="cmdline"></param>
/// <param name="status"></param>
/// <param name="startTime"></param>
/// <param name="endTime"></param>
/// <param name="skipIfLocked">If true, the entry will not be added when the history is locked.</param>
/// <returns>Id for the new created entry. Use this id to fetch the
/// entry. Returns -1 if the entry is not added.</returns>
/// <remarks>This function is thread safe</remarks>
internal long AddEntry(long pipelineId, string cmdline, PipelineState status, DateTime startTime, DateTime endTime, bool skipIfLocked)
{
if (!System.Threading.Monitor.TryEnter(_syncRoot, skipIfLocked ? 0 : System.Threading.Timeout.Infinite))
{
return -1;
}
try
{
ReallocateBufferIfNeeded();
HistoryInfo entry = new HistoryInfo(pipelineId, cmdline, status, startTime, endTime);
return Add(entry);
}
finally
{
System.Threading.Monitor.Exit(_syncRoot);
}
}
/// <summary>
/// Update the history entry corresponding to id.
/// </summary>
/// <param name="id">Id of history entry to be updated.</param>
/// <param name="status">Status to be updated.</param>
/// <param name="endTime">EndTime to be updated.</param>
/// <param name="skipIfLocked">If true, the entry will not be added when the history is locked.</param>
/// <returns></returns>
internal void UpdateEntry(long id, PipelineState status, DateTime endTime, bool skipIfLocked)
{
if (!System.Threading.Monitor.TryEnter(_syncRoot, skipIfLocked ? 0 : System.Threading.Timeout.Infinite))
{
return;
}
try
{
HistoryInfo entry = CoreGetEntry(id);
if (entry != null)
{
entry.SetStatus(status);
entry.SetEndTime(endTime);
}
}
finally
{
System.Threading.Monitor.Exit(_syncRoot);
}
}
/// <summary>
/// Gets entry from buffer for given id. This id should be the
/// id returned by Add method.
/// </summary>
/// <param name="id">Id of the entry to be fetched.</param>
/// <returns>Entry corresponding to id if it is present else null
/// </returns>
internal HistoryInfo GetEntry(long id)
{
lock (_syncRoot)
{
ReallocateBufferIfNeeded();
HistoryInfo entry = CoreGetEntry(id);
if (entry != null)
if (!entry.Cleared)
return entry.Clone();
return null;
}
}
/// <summary>
/// Get count HistoryEntries.
/// </summary>
/// <param name="id"></param>
/// <param name="count"></param>
/// <param name="newest"></param>
/// <returns>History entries.</returns>
internal HistoryInfo[] GetEntries(long id, long count, SwitchParameter newest)
{
ReallocateBufferIfNeeded();
if (count < -1)
{
throw PSTraceSource.NewArgumentOutOfRangeException(nameof(count), count);
}
if (newest.ToString() == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(newest));
}
if (count == -1 || count > _countEntriesAdded || count > _countEntriesInBuffer)
count = _countEntriesInBuffer;
if (count == 0 || _countEntriesInBuffer == 0)
{
return Array.Empty<HistoryInfo>();
}
lock (_syncRoot)
{
// Using list instead of an array to store the entries.With array we are getting null values
// when the historybuffer size is changed
List<HistoryInfo> entriesList = new List<HistoryInfo>();
if (id > 0)
{
long firstId, baseId;
baseId = id;
// get id,count,newest values
if (!newest.IsPresent)
{
// get older entries
// Calculate the first id (i.e lowest id to fetch)
firstId = baseId - count + 1;
// If first id is less than the lowest id in history store,
// assign lowest id as first ID
if (firstId < 1)
{
firstId = 1;
}
for (long i = baseId; i >= firstId; --i)
{
if (firstId <= 1) break;
// if entry is null , continue the loop with the next entry
if (_buffer[GetIndexFromId(i)] == null) continue;
if (_buffer[GetIndexFromId(i)].Cleared)
{
// we have to clear count entries before an id, so if an entry is null,decrement
// first id as long as its is greater than the lowest entry in the buffer.
firstId--;
continue;
}
}
for (long i = firstId; i <= baseId; ++i)
{
// if an entry is null after being cleared by clear-history cmdlet,
// continue with the next entry
if (_buffer[GetIndexFromId(i)] == null || _buffer[GetIndexFromId(i)].Cleared)
continue;
entriesList.Add(_buffer[GetIndexFromId(i)].Clone());
}
}
else
{ // get latest entries
// first id becomes the id +count no of entries from the end of the buffer
firstId = baseId + count - 1;
// if first id is more than the no of entries in the buffer, first id will be the last entry in the buffer
if (firstId >= _countEntriesAdded)
{
firstId = _countEntriesAdded;
}
for (long i = baseId; i <= firstId; i++)
{
if (firstId >= _countEntriesAdded) break;
// if entry is null , continue the loop with the next entry
if (_buffer[GetIndexFromId(i)] == null) continue;
if (_buffer[GetIndexFromId(i)].Cleared)
{
// we have to clear count entries before an id, so if an entry is null,increment first id
firstId++;
continue;
}
}
for (long i = firstId; i >= baseId; --i)
{
// if an entry is null after being cleared by clear-history cmdlet,
// continue with the next entry
if (_buffer[GetIndexFromId(i)] == null || _buffer[GetIndexFromId(i)].Cleared)
continue;
entriesList.Add(_buffer[GetIndexFromId(i)].Clone());
}
}
}
else
{
// get entries for count,newest
long index, SmallestID = 0;
// if we change the defaulthistory size and when no of entries exceed the size, then
// we need to get the smallest entry in the buffer when we want to clear the oldest entry
// eg if size is 5 and then the entries can be 7,6,1,2,3
if (_capacity != DefaultHistorySize)
SmallestID = SmallestIDinBuffer();
if (!newest.IsPresent)
{
// get oldest count entries
index = 1;
if (_capacity != DefaultHistorySize)
{
if (_countEntriesAdded > _capacity)
index = SmallestID;
}
for (long i = count - 1; i >= 0;)
{
if (index > _countEntriesAdded) break;
if ((index <= 0 || GetIndexFromId(index) >= _buffer.Length) ||
(_buffer[GetIndexFromId(index)].Cleared))
{
index++; continue;
}
else
{
entriesList.Add(_buffer[GetIndexFromId(index)].Clone());
i--; index++;
}
}
}
else
{
index = _countEntriesAdded; //SmallestIDinBuffer
for (long i = count - 1; i >= 0;)
{
// if an entry is cleared continue to the next entry
if (_capacity != DefaultHistorySize)
{
if (_countEntriesAdded > _capacity)
{
if (index < SmallestID)
break;
}
}
if (index < 1) break;
if ((index <= 0 || GetIndexFromId(index) >= _buffer.Length) ||
(_buffer[GetIndexFromId(index)].Cleared))
{ index--; continue; }
else
{
// clone the entry from the history buffer
entriesList.Add(_buffer[GetIndexFromId(index)].Clone());
i--; index--;
}
}
}
}
HistoryInfo[] entries = new HistoryInfo[entriesList.Count];
entriesList.CopyTo(entries);
return entries;
}
}
/// <summary>
/// Get History Entries based on the WildCard Pattern value.
/// If passed 0, returns all the values, else return on the basis of count.
/// </summary>
/// <param name="wildcardpattern"></param>
/// <param name="count"></param>
/// <param name="newest"></param>
/// <returns></returns>
internal HistoryInfo[] GetEntries(WildcardPattern wildcardpattern, long count, SwitchParameter newest)
{
lock (_syncRoot)
{
if (count < -1)
{
throw PSTraceSource.NewArgumentOutOfRangeException(nameof(count), count);
}
if (newest.ToString() == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(newest));
}
if (count > _countEntriesAdded || count == -1)
{
count = _countEntriesInBuffer;
}
List<HistoryInfo> cmdlist = new List<HistoryInfo>();
long SmallestID = 1;
// if buffersize is changes,Get the smallest entry that's not cleared in the buffer
if (_capacity != DefaultHistorySize)
SmallestID = SmallestIDinBuffer();
if (count != 0)
{
if (!newest.IsPresent)
{
long id = 1;
if (_capacity != DefaultHistorySize)
{
if (_countEntriesAdded > _capacity)
id = SmallestID;
}
for (long i = 0; i <= count - 1;)
{
if (id > _countEntriesAdded) break;
if (!_buffer[GetIndexFromId(id)].Cleared && wildcardpattern.IsMatch(_buffer[GetIndexFromId(id)].CommandLine.Trim()))
{
cmdlist.Add(_buffer[GetIndexFromId(id)].Clone()); i++;
}
id++;
}
}
else
{
long id = _countEntriesAdded;
for (long i = 0; i <= count - 1;)
{
// if buffersize is changed,we have to loop from max entry to min entry that's not cleared
if (_capacity != DefaultHistorySize)
{
if (_countEntriesAdded > _capacity)
{
if (id < SmallestID)
break;
}
}
if (id < 1) break;
if (!_buffer[GetIndexFromId(id)].Cleared && wildcardpattern.IsMatch(_buffer[GetIndexFromId(id)].CommandLine.Trim()))
{
cmdlist.Add(_buffer[GetIndexFromId(id)].Clone()); i++;
}
id--;
}
}
}
else
{
for (long i = 1; i <= _countEntriesAdded; i++)
{
if (!_buffer[GetIndexFromId(i)].Cleared && wildcardpattern.IsMatch(_buffer[GetIndexFromId(i)].CommandLine.Trim()))
{
cmdlist.Add(_buffer[GetIndexFromId(i)].Clone());
}
}
}
HistoryInfo[] entries = new HistoryInfo[cmdlist.Count];
cmdlist.CopyTo(entries);
return entries;
}
}
/// <summary>
/// Clears the history entry from buffer for a given id.
/// </summary>
/// <param name="id">Id of the entry to be Cleared.</param>
/// <returns>Nothing.</returns>
internal void ClearEntry(long id)
{
lock (_syncRoot)
{
if (id < 0)
{
throw PSTraceSource.NewArgumentOutOfRangeException(nameof(id), id);
}
// no entries are present to clear
if (_countEntriesInBuffer == 0)
return;
// throw an exception if id is out of range
if (id > _countEntriesAdded)
{
return;
}
HistoryInfo entry = CoreGetEntry(id);
if (entry != null)
{
entry.Cleared = true;
_countEntriesInBuffer--;
}
return;
}
}
/// <summary>
/// gets the total number of entries added
/// </summary>
/// <returns>count of total entries added.</returns>
internal int Buffercapacity()
{
return _capacity;
}
#endregion internal
#region private
/// <summary>
/// Adds an entry to the buffer. If buffer is full, overwrites
/// oldest entry in the buffer.
/// </summary>
/// <param name="entry"></param>
/// <returns>Returns id for the entry. This id should be used to fetch
/// the entry from the buffer.</returns>
/// <remarks>Id starts from 1 and is incremented by 1 for each new entry</remarks>
private long Add(HistoryInfo entry)
{
if (entry == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(entry));
}
_buffer[GetIndexForNewEntry()] = entry;
// Increment count of entries added so far
_countEntriesAdded++;
// Id of an entry in history is same as its number in history store.
entry.SetId(_countEntriesAdded);
// Increment count of entries in buffer by 1
IncrementCountOfEntriesInBuffer();
return _countEntriesAdded;
}
/// <summary>
/// Gets entry from buffer for given id. This id should be the
/// id returned by Add method.
/// </summary>
/// <param name="id">Id of the entry to be fetched.</param>
/// <returns>Entry corresponding to id if it is present else null
/// </returns>
private HistoryInfo CoreGetEntry(long id)
{
if (id <= 0)
{
throw PSTraceSource.NewArgumentOutOfRangeException(nameof(id), id);
}
if (_countEntriesInBuffer == 0)
return null;
if (id > _countEntriesAdded)
{
return null;
}
// if (_buffer[GetIndexFromId(id)].Cleared == false )
return _buffer[GetIndexFromId(id)];
// else
// return null;
}
/// <summary>
/// Gets the smallest id in the buffer.
/// </summary>
/// <returns></returns>
private long SmallestIDinBuffer()
{
long minID = 0;
if (_buffer == null)
return minID;
for (int i = 0; i < _buffer.Length; i++)
{
// assign the first entry in the buffer as min.
if (_buffer[i] != null && !_buffer[i].Cleared)
{
minID = _buffer[i].Id;
break;
}
}
// check for the minimum id that is not cleared
for (int i = 0; i < _buffer.Length; i++)
{
if (_buffer[i] != null && !_buffer[i].Cleared)
if (minID > _buffer[i].Id)
minID = _buffer[i].Id;
}
return minID;
}
/// <summary>
/// Reallocates the buffer if history size changed.
/// </summary>
private void ReallocateBufferIfNeeded()
{
// Get current value of histoysize variable
int historySize = GetHistorySize();
if (historySize == _capacity)
return;
HistoryInfo[] tempBuffer = new HistoryInfo[historySize];
// Calculate number of entries to copy in new buffer.
int numberOfEntries = _countEntriesInBuffer;
// when buffer size is changed,we have to consider the totalnumber of entries added
if (numberOfEntries < _countEntriesAdded)
numberOfEntries = (int)_countEntriesAdded;
if (_countEntriesInBuffer > historySize)
numberOfEntries = historySize;
for (int i = numberOfEntries; i > 0; --i)
{
long nextId = _countEntriesAdded - i + 1;
tempBuffer[GetIndexFromId(nextId, historySize)] = _buffer[GetIndexFromId(nextId)];
}
_countEntriesInBuffer = numberOfEntries;
_capacity = historySize;
_buffer = tempBuffer;
}
/// <summary>
/// Get the index for new entry.
/// </summary>
/// <returns>Index for new entry.</returns>
private int GetIndexForNewEntry()
{
return (int)(_countEntriesAdded % _capacity);
}
/// <summary>
/// Gets index in buffer for an entry with given Id.
/// </summary>
/// <returns></returns>
private int GetIndexFromId(long id)
{
return (int)((id - 1) % _capacity);
}
/// <summary>
/// Gets index in buffer for an entry with given Id using passed in
/// capacity.
/// </summary>
/// <param name="id"></param>
/// <param name="capacity"></param>
/// <returns></returns>
private static int GetIndexFromId(long id, int capacity)
{
return (int)((id - 1) % capacity);
}
/// <summary>
/// Increment number of entries in buffer by 1.
/// </summary>
private void IncrementCountOfEntriesInBuffer()
{
if (_countEntriesInBuffer < _capacity)
_countEntriesInBuffer++;
}
/// <summary>
/// Get the current history size.
/// </summary>
/// <returns></returns>
private static int GetHistorySize()
{
int historySize = 0;
var executionContext = LocalPipeline.GetExecutionContextFromTLS();
object obj = executionContext?.GetVariableValue(SpecialVariables.HistorySizeVarPath);
if (obj != null)
{
try
{
historySize = (int)LanguagePrimitives.ConvertTo(obj, typeof(int), System.Globalization.CultureInfo.InvariantCulture);
}
catch (InvalidCastException)
{ }
}
if (historySize <= 0)
{
historySize = DefaultHistorySize;
}
return historySize;
}
/// <summary>
/// Buffer.
/// </summary>
private HistoryInfo[] _buffer;
/// <summary>
/// Capacity of circular buffer.
/// </summary>
private int _capacity;
/// <summary>
/// Number of entries in buffer currently.
/// </summary>
private int _countEntriesInBuffer;
/// <summary>
/// Total number of entries added till now including those which have
/// been overwritten after buffer got full. This is also number of
/// last entry added.
/// </summary>
private long _countEntriesAdded;
/// <summary>
/// Private object for synchronization.
/// </summary>
private readonly object _syncRoot = new object();
#endregion private
/// <summary>
/// Return the ID of the next history item to be added.
/// </summary>
internal long GetNextHistoryId()
{
return _countEntriesAdded + 1;
}
#region invoke_loop_detection
/// <summary>
/// This is a set of HistoryInfo ids which are currently being executed in the
/// pipelines of the Runspace that is holding this 'History' instance.
/// </summary>
private readonly HashSet<long> _invokeHistoryIds = new HashSet<long>();
internal bool PresentInInvokeHistoryEntrySet(HistoryInfo entry)
{
return _invokeHistoryIds.Contains(entry.Id);
}
internal void AddToInvokeHistoryEntrySet(HistoryInfo entry)
{
_invokeHistoryIds.Add(entry.Id);
}
internal void RemoveFromInvokeHistoryEntrySet(HistoryInfo entry)
{
_invokeHistoryIds.Remove(entry.Id);
}
#endregion invoke_loop_detection
}
/// <summary>
/// This class Implements the get-history command.
/// </summary>
[Cmdlet(VerbsCommon.Get, "History", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096788")]
[OutputType(typeof(HistoryInfo))]
public class GetHistoryCommand : PSCmdlet
{
/// <summary>
/// Ids of entries to display.
/// </summary>
private long[] _id;
/// <summary>
/// Ids of entries to display.
/// </summary>
/// <value></value>
[Parameter(Position = 0, ValueFromPipeline = true)]
[ValidateRange((long)1, long.MaxValue)]
public long[] Id
{
get
{
return _id;
}
set
{
_id = value;
}
}
/// <summary>
/// Is Count parameter specified.
/// </summary>
private bool _countParameterSpecified;
/// <summary>
/// Count of entries to display. By default, count is the length of the history buffer.
/// So "Get-History" returns all history entries.
/// </summary>
private int _count;
/// <summary>
/// No of History Entries (starting from last) that are to be displayed.
/// </summary>
[Parameter(Position = 1)]
[ValidateRange(0, (int)Int16.MaxValue)]
public int Count
{
get
{
return _count;
}
set
{
_countParameterSpecified = true;
_count = value;
}
}
/// <summary>
/// Implements the Processing() method for show/History command.
/// </summary>
protected override void ProcessRecord()
{
History history = ((LocalRunspace)Context.CurrentRunspace).History;
if (_id != null)
{
if (!_countParameterSpecified)
{
// If Id parameter is specified and count is not specified,
// get history
foreach (long id in _id)
{
Dbg.Assert(id > 0, "ValidateRangeAttribute should not allow this");
HistoryInfo entry = history.GetEntry(id);
if (entry != null && entry.Id == id)
{
WriteObject(entry);
}
else
{
Exception ex =
new ArgumentException
(
StringUtil.Format(HistoryStrings.NoHistoryForId, id)
);
WriteError
(
new ErrorRecord
(
ex,
"GetHistoryNoHistoryForId",
ErrorCategory.ObjectNotFound,
id
)
);
}
}
}
else if (_id.Length > 1)
{
Exception ex =
new ArgumentException
(
StringUtil.Format(HistoryStrings.NoCountWithMultipleIds)
);
ThrowTerminatingError
(
new ErrorRecord
(
ex,
"GetHistoryNoCountWithMultipleIds",
ErrorCategory.InvalidArgument,
_count
)
);
}
else
{
long id = _id[0];
Dbg.Assert(id > 0, "ValidateRangeAttribute should not allow this");
WriteObject(history.GetEntries(id, _count, false), true);
}
}
else
{
// The default value for _count is the size of the history buffer.
if (!_countParameterSpecified)
{
_count = history.Buffercapacity();
}
HistoryInfo[] entries = history.GetEntries(0, _count, true);
for (long i = entries.Length - 1; i >= 0; i--)
WriteObject(entries[i]);
}
}
}
/// <summary>
/// This class implements the Invoke-History command.
/// </summary>
[Cmdlet(VerbsLifecycle.Invoke, "History", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096586")]
public class InvokeHistoryCommand : PSCmdlet
{
#region Parameters
/// <summary>
/// Invoke cmd can execute only one history entry. If multiple
/// ids are provided, we throw error.
/// </summary>
private bool _multipleIdProvided;
private string _id;
/// <summary>
/// Accepts a string value indicating a previously executed command to
/// re-execute.
/// If string can be parsed to long,
/// it will be used as HistoryId
/// else
/// as a string value indicating a previously executed command to
/// re-execute. This string is the first n characters of the command
/// that is to be re-executed.
/// </summary>
[Parameter(Position = 0, ValueFromPipelineByPropertyName = true)]
public string Id
{
get
{
return _id;
}
set
{
if (_id != null)
{
// Id has been set already.
_multipleIdProvided = true;
}
_id = value;
}
}
#endregion
/// <summary>
/// Implements the BeginProcessing() method for eval/History command.
/// </summary>
protected override void EndProcessing()
{
// Invoke-history can execute only one command. If multiple
// ids were provided, throw exception
if (_multipleIdProvided)
{
ThrowTerminatingError(
new ErrorRecord(
new ArgumentException(HistoryStrings.InvokeHistoryMultipleCommandsError),
"InvokeHistoryMultipleCommandsError",
ErrorCategory.InvalidArgument,
targetObject: null));
}
var ctxRunspace = (LocalRunspace)Context.CurrentRunspace;
History history = ctxRunspace.History;
Dbg.Assert(history != null, "History should be non null");
// Get the history entry to invoke
HistoryInfo entry = GetHistoryEntryToInvoke(history);
string commandToInvoke = entry.CommandLine;
if (!ShouldProcess(commandToInvoke))
{
return;
}
// Check if there is a loop in invoke-history
if (history.PresentInInvokeHistoryEntrySet(entry))
{
ThrowTerminatingError(
new ErrorRecord(
new InvalidOperationException(HistoryStrings.InvokeHistoryLoopDetected),
"InvokeHistoryLoopDetected",
ErrorCategory.InvalidOperation,
targetObject: null));
}
else
{
history.AddToInvokeHistoryEntrySet(entry);
}
// Replace Invoke-History with string which is getting invoked
ReplaceHistoryString(entry, ctxRunspace);
try
{
// Echo command
Host.UI.WriteLine(commandToInvoke);
}
catch (HostException)
{
// when the host is not interactive, HostException is thrown
// do nothing
}
// Items invoked as History should act as though they were submitted by the user - so should still come from
// the runspace itself. For this reason, it is insufficient to just use the InvokeScript method on the Cmdlet class.
using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace))
{
ps.AddScript(commandToInvoke);
EventHandler<DataAddedEventArgs> debugAdded = (object sender, DataAddedEventArgs e) => { DebugRecord record = (DebugRecord)((PSDataCollection<DebugRecord>)sender)[e.Index]; WriteDebug(record.Message); };
EventHandler<DataAddedEventArgs> errorAdded = (object sender, DataAddedEventArgs e) => { ErrorRecord record = (ErrorRecord)((PSDataCollection<ErrorRecord>)sender)[e.Index]; WriteError(record); };
EventHandler<DataAddedEventArgs> informationAdded = (object sender, DataAddedEventArgs e) => { InformationRecord record = (InformationRecord)((PSDataCollection<InformationRecord>)sender)[e.Index]; WriteInformation(record); };
EventHandler<DataAddedEventArgs> progressAdded = (object sender, DataAddedEventArgs e) => { ProgressRecord record = (ProgressRecord)((PSDataCollection<ProgressRecord>)sender)[e.Index]; WriteProgress(record); };
EventHandler<DataAddedEventArgs> verboseAdded = (object sender, DataAddedEventArgs e) => { VerboseRecord record = (VerboseRecord)((PSDataCollection<VerboseRecord>)sender)[e.Index]; WriteVerbose(record.Message); };
EventHandler<DataAddedEventArgs> warningAdded = (object sender, DataAddedEventArgs e) => { WarningRecord record = (WarningRecord)((PSDataCollection<WarningRecord>)sender)[e.Index]; WriteWarning(record.Message); };
ps.Streams.Debug.DataAdded += debugAdded;
ps.Streams.Error.DataAdded += errorAdded;
ps.Streams.Information.DataAdded += informationAdded;
ps.Streams.Progress.DataAdded += progressAdded;
ps.Streams.Verbose.DataAdded += verboseAdded;
ps.Streams.Warning.DataAdded += warningAdded;
LocalRunspace localRunspace = ps.Runspace as LocalRunspace;
try
{
// Indicate to the system that we are in nested prompt mode, since we are emulating running the command at the prompt.
// This ensures that the command being run as nested runs in the correct language mode, because CreatePipelineProcessor()
// always forces CommandOrigin to Internal for nested running commands, and Command.CreateCommandProcessor() forces Internal
// commands to always run in FullLanguage mode unless in a nested prompt.
if (localRunspace != null)
{
localRunspace.InInternalNestedPrompt = ps.IsNested;
}
Collection<PSObject> results = ps.Invoke();
if (results.Count > 0)
{
WriteObject(results, true);
}
}
finally
{
history.RemoveFromInvokeHistoryEntrySet(entry);
if (localRunspace != null)
{
localRunspace.InInternalNestedPrompt = false;
}
ps.Streams.Debug.DataAdded -= debugAdded;
ps.Streams.Error.DataAdded -= errorAdded;
ps.Streams.Information.DataAdded -= informationAdded;
ps.Streams.Progress.DataAdded -= progressAdded;
ps.Streams.Verbose.DataAdded -= verboseAdded;
ps.Streams.Warning.DataAdded -= warningAdded;
}
}
}
/// <summary>
/// Helper function which gets history entry to invoke.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Justification = "It's ok to use ID in the ArgumentException")]
private HistoryInfo GetHistoryEntryToInvoke(History history)
{
HistoryInfo entry = null;
// User didn't specify any input parameter. Invoke the last
// entry
if (_id == null)
{
HistoryInfo[] entries = history.GetEntries(0, 1, true);
if (entries.Length == 1)
{
entry = entries[0];
}
else
{
Exception ex =
new InvalidOperationException
(
StringUtil.Format(HistoryStrings.NoLastHistoryEntryFound)
);
ThrowTerminatingError
(
new ErrorRecord
(
ex,
"InvokeHistoryNoLastHistoryEntryFound",
ErrorCategory.InvalidOperation,
null
)
);
}
}
else
{
// Parse input
PopulateIdAndCommandLine();
// User specified a commandline. Get list of all history entries
// and find latest match
if (_commandLine != null)
{
HistoryInfo[] entries = history.GetEntries(0, -1, false);
// and search backwards through the entries
for (int i = entries.Length - 1; i >= 0; i--)
{
if (entries[i].CommandLine.StartsWith(_commandLine, StringComparison.Ordinal))
{
entry = entries[i];
break;
}
}
if (entry == null)
{
Exception ex =
new ArgumentException
(
StringUtil.Format(HistoryStrings.NoHistoryForCommandline, _commandLine)
);
ThrowTerminatingError
(
new ErrorRecord
(
ex,
"InvokeHistoryNoHistoryForCommandline",
ErrorCategory.ObjectNotFound,
_commandLine
)
);
}
}
else
{
if (_historyId <= 0)
{
Exception ex =
new ArgumentOutOfRangeException
(
"Id",
StringUtil.Format(HistoryStrings.InvalidIdGetHistory, _historyId)
);
ThrowTerminatingError
(
new ErrorRecord
(
ex,
"InvokeHistoryInvalidIdGetHistory",
ErrorCategory.InvalidArgument,
_historyId
)
);
}
else
{
// Retrieve the command at the index we've specified
entry = history.GetEntry(_historyId);
if (entry == null || entry.Id != _historyId)
{
Exception ex =
new ArgumentException
(
StringUtil.Format(HistoryStrings.NoHistoryForId, _historyId)
);
ThrowTerminatingError
(
new ErrorRecord
(
ex,
"InvokeHistoryNoHistoryForId",
ErrorCategory.ObjectNotFound,
_historyId
)
);
}
}
}
}
return entry;
}
/// <summary>
/// Id of history entry to execute.
/// </summary>
private long _historyId = -1;
/// <summary>
/// Commandline to execute.
/// </summary>
private string _commandLine;
/// <summary>
/// Parse Id parameter to populate _historyId and _commandLine.
/// </summary>
private void PopulateIdAndCommandLine()
{
if (_id == null)
return;
try
{
_historyId = (long)LanguagePrimitives.ConvertTo(_id, typeof(long), System.Globalization.CultureInfo.InvariantCulture);
}
catch (PSInvalidCastException)
{
_commandLine = _id;
return;
}
}
/// <summary>
/// Invoke-history is replaced in history by the command it executed.
/// This replacement happens only if Invoke-History is single element
/// in the pipeline. If there are more than one element in pipeline
/// (ex A | Invoke-History 2 | B) then we cannot do this replacement.
/// </summary>
private static void ReplaceHistoryString(HistoryInfo entry, LocalRunspace localRunspace)
{
var pipeline = (LocalPipeline)localRunspace.GetCurrentlyRunningPipeline();
if (pipeline.AddToHistory)
{
pipeline.HistoryString = entry.CommandLine;
}
}
}
/// <summary>
/// This class Implements the add-history command.
/// </summary>
[Cmdlet(VerbsCommon.Add, "History", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096479")]
[OutputType(typeof(HistoryInfo))]
public class AddHistoryCommand : PSCmdlet
{
#region parameters
/// <summary>
/// This parameter specifies the current pipeline object.
/// </summary>
[Parameter(Position = 0, ValueFromPipeline = true)]
public PSObject[] InputObject { get; set; }
private bool _passthru;
/// <summary>
/// A Boolean that indicates whether history objects should be
/// passed to the next element in the pipeline.
/// </summary>
[Parameter]
public SwitchParameter Passthru
{
get { return _passthru; }
set { _passthru = value; }
}
#endregion parameters
/// <summary>
/// Override for BeginProcessing.
/// </summary>
protected
override
void BeginProcessing()
{
// Get currently running pipeline and add history entry for
// this pipeline.
// Note:Generally History entry for current pipeline is added
// on completion of pipeline (See LocalPipeline implementation).
// However Add-history adds additional entries in to history and
// additional entries must be added after history for current pipeline.
// This is done by adding the history entry for current pipeline below.
LocalPipeline lpl = (LocalPipeline)((RunspaceBase)Context.CurrentRunspace).GetCurrentlyRunningPipeline();
lpl.AddHistoryEntryFromAddHistoryCmdlet();
}
/// <summary>
/// Override for ProcessRecord.
/// </summary>
protected
override
void ProcessRecord()
{
History history = ((LocalRunspace)Context.CurrentRunspace).History;
Dbg.Assert(history != null, "History should be non null");
if (InputObject != null)
{
foreach (PSObject input in InputObject)
{
// Wrap the inputobject in PSObject and convert it to
// HistoryInfo object.
HistoryInfo infoToAdd = GetHistoryInfoObject(input);
if (infoToAdd != null)
{
long id = history.AddEntry
(
0,
infoToAdd.CommandLine,
infoToAdd.ExecutionStatus,
infoToAdd.StartExecutionTime,
infoToAdd.EndExecutionTime,
false
);
if (Passthru)
{
HistoryInfo infoAdded = history.GetEntry(id);
WriteObject(infoAdded);
}
}
}
}
}
/// <summary>
/// Convert mshObject that has the properties of an HistoryInfo
/// object in to HistoryInfo object.
/// </summary>
/// <param name="mshObject">
/// mshObject to be converted to HistoryInfo.
/// </param>
/// <returns>
/// HistoryInfo object if conversion is successful else null.
/// </returns>
#pragma warning disable 0162
private
HistoryInfo
GetHistoryInfoObject(PSObject mshObject)
{
do
{
if (mshObject == null)
{
break;
}
// Read CommandLine property
if (GetPropertyValue(mshObject, "CommandLine") is not string commandLine)
{
break;
}
// Read ExecutionStatus property
object pipelineState = GetPropertyValue(mshObject, "ExecutionStatus");
if (pipelineState == null || !LanguagePrimitives.TryConvertTo<PipelineState>(pipelineState, out PipelineState executionStatus))
{
break;
}
// Read StartExecutionTime property
object temp = GetPropertyValue(mshObject, "StartExecutionTime");
if (temp == null || !LanguagePrimitives.TryConvertTo<DateTime>(temp, CultureInfo.CurrentCulture, out DateTime startExecutionTime))
{
break;
}
// Read EndExecutionTime property
temp = GetPropertyValue(mshObject, "EndExecutionTime");
if (temp == null || !LanguagePrimitives.TryConvertTo<DateTime>(temp, CultureInfo.CurrentCulture, out DateTime endExecutionTime))
{
break;
}
return new HistoryInfo(
pipelineId: 0,
commandLine,
executionStatus,
startExecutionTime,
endExecutionTime
);
} while (false);
// If we are here, an error has occurred.
Exception ex =
new InvalidDataException
(
StringUtil.Format(HistoryStrings.AddHistoryInvalidInput)
);
WriteError
(
new ErrorRecord
(
ex,
"AddHistoryInvalidInput",
ErrorCategory.InvalidData,
mshObject
)
);
return null;
}
#pragma warning restore 0162
private static
object
GetPropertyValue(PSObject mshObject, string propertyName)
{
PSMemberInfo propertyInfo = mshObject.Properties[propertyName];
if (propertyInfo == null)
return null;
return propertyInfo.Value;
}
}
/// <summary>
/// This Class implements the Clear History cmdlet
/// </summary>
[Cmdlet(VerbsCommon.Clear, "History", SupportsShouldProcess = true, DefaultParameterSetName = "IDParameter", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096691")]
public class ClearHistoryCommand : PSCmdlet
{
#region Command Line Parameters
/// <summary>
/// Specifies the ID of a command in the session history.Clear history clears the entries
/// wit the specified ID(s)
/// </summary>
[Parameter(ParameterSetName = "IDParameter", Position = 0,
HelpMessage = "Specifies the ID of a command in the session history.Clear history clears only the specified command")]
[ValidateRange((int)1, int.MaxValue)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public int[] Id
{
get
{
return _id;
}
set
{
_id = value;
}
}
/// <summary>
/// Id of a history entry.
/// </summary>
private int[] _id;
/// <summary>
/// Command line name of an entry in the session history.
/// </summary>
[Parameter(ParameterSetName = "CommandLineParameter", HelpMessage = "Specifies the name of a command in the session history")]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] CommandLine
{
get
{
return _commandline;
}
set
{
_commandline = value;
}
}
/// <summary>
/// Commandline parameter.
/// </summary>
private string[] _commandline = null;
/// <summary>
/// Clears the specified number of history entries
/// </summary>
[Parameter(Mandatory = false, Position = 1, HelpMessage = "Clears the specified number of history entries")]
[ValidateRange((int)1, int.MaxValue)]
public int Count
{
get
{
return _count;
}
set
{
_countParameterSpecified = true;
_count = value;
}
}
/// <summary>
/// Count of the history entries.
/// </summary>
private int _count = 32;
/// <summary>
/// A boolean variable to indicate if the count parameter specified.
/// </summary>
private bool _countParameterSpecified = false;
/// <summary>
/// Specifies whether new entries to be cleared or the default old ones.
/// </summary>
[Parameter(Mandatory = false, HelpMessage = "Specifies whether new entries to be cleared or the default old ones.")]
public SwitchParameter Newest
{
get
{
return _newest;
}
set
{
_newest = value;
}
}
/// <summary>
/// Switch parameter on the history entries.
/// </summary>
private SwitchParameter _newest;
#endregion Command Line Parameters
/// <summary>
/// Overriding Begin Processing.
/// </summary>
protected override void BeginProcessing()
{
_history = ((LocalRunspace)Context.CurrentRunspace).History;
}
/// <summary>
/// Overriding Process Record.
/// </summary>
protected override void ProcessRecord()
{
// case statement to identify the parameter set
switch (ParameterSetName)
{
case "IDParameter":
ClearHistoryByID();
break;
case "CommandLineParameter":
ClearHistoryByCmdLine();
break;
default:
ThrowTerminatingError(
new ErrorRecord(
new ArgumentException("Invalid ParameterSet Name"),
"Unable to access the session history", ErrorCategory.InvalidOperation, null));
return;
}
}
#region Private
/// <summary>
/// Clears the session history based on the id parameter
/// takes no parameters
/// </summary>
/// <returns>Nothing.</returns>
private void ClearHistoryByID()
{
if (_countParameterSpecified && Count < 0)
{
Exception ex =
new ArgumentException
(
StringUtil.Format("HistoryStrings", "InvalidCountValue")
);
ThrowTerminatingError
(
new ErrorRecord
(
ex,
"ClearHistoryInvalidCountValue",
ErrorCategory.InvalidArgument,
_count
)
);
}
// if id parameter is not present
if (_id != null)
{
// if count parameter is not present
if (!_countParameterSpecified)
{
// clearing the entry for each id in the id[] parameter.
foreach (long id in _id)
{
Dbg.Assert(id > 0, "ValidateRangeAttribute should not allow this");
HistoryInfo entry = _history.GetEntry(id);
if (entry != null && entry.Id == id)
{
_history.ClearEntry(entry.Id);
}
else
{// throw an exception if an entry for an id is not found
Exception ex =
new ArgumentException
(
StringUtil.Format(HistoryStrings.NoHistoryForId, id)
);
WriteError
(
new ErrorRecord
(
ex,
"GetHistoryNoHistoryForId",
ErrorCategory.ObjectNotFound,
id
)
);
}
}
}
else if (_id.Length > 1)
{// throwing an exception for invalid parameter combinations
Exception ex =
new ArgumentException
(
StringUtil.Format(HistoryStrings.NoCountWithMultipleIds)
);
ThrowTerminatingError
(
new ErrorRecord
(
ex,
"GetHistoryNoCountWithMultipleIds",
ErrorCategory.InvalidArgument,
_count
)
);
}
else
{// if id,count and newest parameters are present
// throw an exception for invalid count values
long id = _id[0];
Dbg.Assert(id > 0, "ValidateRangeAttribute should not allow this");
ClearHistoryEntries(id, _count, null, _newest);
}
}
else
{
// confirmation message if all the clearhistory cmdlet is used without any parameters
if (!_countParameterSpecified)
{
string message = StringUtil.Format(HistoryStrings.ClearHistoryWarning, "Warning"); // "The command would clear all the entry(s) from the session history,Are you sure you want to continue ?";
if (!ShouldProcess(message))
{
return;
}
ClearHistoryEntries(0, -1, null, _newest);
}
else
{
ClearHistoryEntries(0, _count, null, _newest);
}
}
}
/// <summary>
/// Clears the session history based on the Commandline parameter
/// takes no parameters
/// </summary>
/// <returns>Nothing.</returns>
private void ClearHistoryByCmdLine()
{
// throw an exception for invalid count values
if (_countParameterSpecified && Count < 0)
{
Exception ex =
new ArgumentException
(
StringUtil.Format(HistoryStrings.InvalidCountValue)
);
ThrowTerminatingError
(
new ErrorRecord
(
ex,
"ClearHistoryInvalidCountValue",
ErrorCategory.InvalidArgument,
_count
)
);
}
// if command line is not present
if (_commandline != null)
{
// if count parameter is not present
if (!_countParameterSpecified)
{
foreach (string cmd in _commandline)
{
ClearHistoryEntries(0, 1, cmd, _newest);
}
}
else if (_commandline.Length > 1)
{// throwing exceptions for invalid parameter combinations
Exception ex =
new ArgumentException
(
StringUtil.Format(HistoryStrings.NoCountWithMultipleCmdLine)
);
ThrowTerminatingError
(
new ErrorRecord
(
ex,
"NoCountWithMultipleCmdLine ",
ErrorCategory.InvalidArgument,
_commandline
)
);
}
else
{ // if commandline,count and newest parameters are present.
ClearHistoryEntries(0, _count, _commandline[0], _newest);
}
}
}
/// <summary>
/// Clears the session history based on the input parameter
/// </summary>
/// <returns>Nothing.</returns>
/// <param name="id">Id of the entry to be cleared.</param>
/// <param name="count">Count of entries to be cleared.</param>
/// <param name="cmdline">Cmdline string to be cleared.</param>
/// <param name="newest">Order of the entries.</param>
private void ClearHistoryEntries(long id, int count, string cmdline, SwitchParameter newest)
{
// if cmdline is null,use default parameter set notion.
if (cmdline == null)
{
// if id is present,clears count entries from id
if (id > 0)
{
HistoryInfo entry = _history.GetEntry(id);
if (entry == null || entry.Id != id)
{
Exception ex =
new ArgumentException
(
StringUtil.Format(HistoryStrings.NoHistoryForId, id)
);
WriteError
(
new ErrorRecord
(
ex,
"GetHistoryNoHistoryForId",
ErrorCategory.ObjectNotFound,
id
)
);
}
_entries = _history.GetEntries(id, count, newest);
}
else
{// if only count is present
_entries = _history.GetEntries(0, count, newest);
}
}
else
{
// creates a wild card pattern
WildcardPattern wildcardpattern = WildcardPattern.Get(cmdline, WildcardOptions.IgnoreCase);
// count set to zero if not specified.
if (!_countParameterSpecified && WildcardPattern.ContainsWildcardCharacters(cmdline))
{
count = 0;
}
// Return the matching history entries for the command line parameter
// if newest id false...gets the oldest entry
_entries = _history.GetEntries(wildcardpattern, count, newest);
}
// Clear the History value.
foreach (HistoryInfo entry in _entries)
{
if (entry != null && !entry.Cleared)
_history.ClearEntry(entry.Id);
}
return;
}
/// <summary>
/// History obj.
/// </summary>
private History _history;
/// <summary>
/// Array of historyinfo objects.
/// </summary>
private HistoryInfo[] _entries;
#endregion Private
}
}
|