File size: 65,711 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 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#nullable enable
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Management.Automation.Internal;
using System.Management.Automation.Security;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation
{
/// <summary>
/// Used to enumerate the commands on the system that match the specified
/// command name.
/// </summary>
internal class CommandSearcher : IEnumerable<CommandInfo>, IEnumerator<CommandInfo>
{
/// <summary>
/// Constructs a command searching enumerator that resolves the location
/// to a command using a standard algorithm.
/// </summary>
/// <param name="commandName">The name of the command to look for.</param>
/// <param name="options">Determines which types of commands glob resolution of the name will take place on.</param>
/// <param name="commandTypes">The types of commands to look for.</param>
/// <param name="context">The execution context for this engine instance.</param>
/// <param name="fuzzyMatcher">The fuzzy matcher to use for fuzzy searching.</param>
///
/// <exception cref="ArgumentNullException">If <paramref name="context"/> is null.</exception>
/// <exception cref="PSArgumentException">If <paramref name="commandName"/> is null or empty.</exception>
internal CommandSearcher(
string commandName,
SearchResolutionOptions options,
CommandTypes commandTypes,
ExecutionContext context,
FuzzyMatcher? fuzzyMatcher = null)
{
Diagnostics.Assert(context != null, "caller to verify context is not null");
Diagnostics.Assert(!string.IsNullOrEmpty(commandName), "caller to verify commandName is valid");
_commandName = commandName;
_context = context;
_commandResolutionOptions = options;
_commandTypes = commandTypes;
_fuzzyMatcher = fuzzyMatcher;
// Initialize the enumerators
this.Reset();
}
/// <summary>
/// Gets an instance of a command enumerator.
/// </summary>
/// <returns>
/// An instance of this class as IEnumerator.
/// </returns>
IEnumerator<CommandInfo> IEnumerable<CommandInfo>.GetEnumerator()
{
return this;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this;
}
/// <summary>
/// Moves the enumerator to the next command match. Public for IEnumerable.
/// </summary>
/// <returns>
/// true if there was another command that matches, false otherwise.
/// </returns>
public bool MoveNext()
{
_currentMatch = null;
if (_currentState == SearchState.SearchingAliases)
{
_currentMatch = SearchForAliases();
// Why don't we check IsVisible on other scoped items?
if (_currentMatch != null && SessionState.IsVisible(_commandOrigin, _currentMatch))
{
return true;
}
// Make sure Current doesn't return an alias that isn't visible
_currentMatch = null;
// Advance the state
_currentState = SearchState.SearchingFunctions;
}
if (_currentState == SearchState.SearchingFunctions)
{
_currentMatch = SearchForFunctions();
// Return the alias info only if it is visible. If not, then skip to the next
// stage of command resolution...
if (_currentMatch != null)
{
return true;
}
// Advance the state
_currentState = SearchState.SearchingCmdlets;
}
if (_currentState == SearchState.SearchingCmdlets)
{
_currentMatch = SearchForCmdlets();
if (_currentMatch != null)
{
return true;
}
// Advance the state
_currentState = SearchState.StartSearchingForExternalCommands;
}
if (_currentState == SearchState.StartSearchingForExternalCommands)
{
if ((_commandTypes & (CommandTypes.Application | CommandTypes.ExternalScript)) == 0)
{
// Since we are not requiring any path lookup in this search, just return false now
// because all the remaining searches do path lookup.
return false;
}
// For security reasons, if the command is coming from outside the runspace and it looks like a path,
// we want to pre-check that path before doing any probing of the network or drives
if (_commandOrigin == CommandOrigin.Runspace && _commandName.IndexOfAny(Utils.Separators.DirectoryOrDrive) >= 0)
{
bool allowed = false;
// Ok - it looks like it might be a path, so we're going to check to see if the command is prefixed
// by any of the allowed paths. If so, then we allow the search to proceed...
// If either the Applications or Script lists contain just '*' the command is allowed
// at this point.
if ((_context.EngineSessionState.Applications.Count == 1 &&
_context.EngineSessionState.Applications[0].Equals("*", StringComparison.OrdinalIgnoreCase)) ||
(_context.EngineSessionState.Scripts.Count == 1 &&
_context.EngineSessionState.Scripts[0].Equals("*", StringComparison.OrdinalIgnoreCase)))
{
allowed = true;
}
else
{
// Ok, see if it's in the applications list
foreach (string path in _context.EngineSessionState.Applications)
{
if (checkPath(path, _commandName))
{
allowed = true;
break;
}
}
// If it wasn't in the applications list, see it's in the script list
if (!allowed)
{
foreach (string path in _context.EngineSessionState.Scripts)
{
if (checkPath(path, _commandName))
{
allowed = true;
break;
}
}
}
}
if (!allowed)
{
return false;
}
}
// Advance the state
_currentState = SearchState.PowerShellPathResolution;
_currentMatch = ProcessBuiltinScriptState();
if (_currentMatch != null)
{
// Set the current state to QualifiedFileSystemPath since
// we want to skip the qualified file system path search
// in the case where we found a PowerShell qualified path.
_currentState = SearchState.QualifiedFileSystemPath;
return true;
}
}
if (_currentState == SearchState.PowerShellPathResolution)
{
_currentState = SearchState.QualifiedFileSystemPath;
_currentMatch = ProcessPathResolutionState();
if (_currentMatch != null)
{
return true;
}
}
// Search using CommandPathSearch
if (_currentState == SearchState.QualifiedFileSystemPath ||
_currentState == SearchState.PathSearch)
{
_currentMatch = ProcessQualifiedFileSystemState();
if (_currentMatch != null)
{
return true;
}
}
if (_currentState == SearchState.PathSearch)
{
_currentState = SearchState.PowerShellRelativePath;
_currentMatch = ProcessPathSearchState();
if (_currentMatch != null)
{
return true;
}
}
return false;
}
private CommandInfo? SearchForAliases()
{
CommandInfo? currentMatch = null;
if (_context.EngineSessionState != null &&
(_commandTypes & CommandTypes.Alias) != 0)
{
currentMatch = GetNextAlias();
}
return currentMatch;
}
private CommandInfo? SearchForFunctions()
{
CommandInfo? currentMatch = null;
if (_context.EngineSessionState != null &&
(_commandTypes & (CommandTypes.Function | CommandTypes.Filter | CommandTypes.Configuration)) != 0)
{
currentMatch = GetNextFunction();
}
return currentMatch;
}
private CommandInfo? SearchForCmdlets()
{
CommandInfo? currentMatch = null;
if ((_commandTypes & CommandTypes.Cmdlet) != 0)
{
currentMatch = GetNextCmdlet();
}
return currentMatch;
}
private CommandInfo? ProcessBuiltinScriptState()
{
CommandInfo? currentMatch = null;
// Check to see if the path is qualified
if (_context.EngineSessionState != null &&
_context.EngineSessionState.ProviderCount > 0 &&
IsQualifiedPSPath(_commandName))
{
currentMatch = GetNextFromPath();
}
return currentMatch;
}
private CommandInfo? ProcessPathResolutionState()
{
CommandInfo? currentMatch = null;
try
{
// Check to see if the path is a file system path that
// is rooted. If so that is the next match
if (Path.IsPathRooted(_commandName) &&
File.Exists(_commandName))
{
try
{
currentMatch = GetInfoFromPath(_commandName);
}
catch (FileLoadException)
{
}
catch (FormatException)
{
}
catch (MetadataException)
{
}
}
}
catch (ArgumentException)
{
// If the path contains illegal characters that
// weren't caught by the other APIs, IsPathRooted
// will throw an exception.
// For example, looking for a command called
// `abcdef
// The `a will be translated into the beep control character
// which is not a legal file system character, though
// Path.InvalidPathChars does not contain it as an invalid
// character.
}
return currentMatch;
}
private CommandInfo? ProcessQualifiedFileSystemState()
{
try
{
setupPathSearcher();
}
catch (ArgumentException)
{
_currentState = SearchState.NoMoreMatches;
throw;
}
catch (PathTooLongException)
{
_currentState = SearchState.NoMoreMatches;
throw;
}
CommandInfo? currentMatch = null;
_currentState = SearchState.PathSearch;
if (_canDoPathLookup)
{
try
{
// the previous call to setupPathSearcher ensures _pathSearcher != null
while (currentMatch == null && _pathSearcher!.MoveNext())
{
currentMatch = GetInfoFromPath(((IEnumerator<string>)_pathSearcher).Current);
}
}
catch (InvalidOperationException)
{
// The enumerator may throw if there are no more matches
}
}
return currentMatch;
}
private CommandInfo? ProcessPathSearchState()
{
CommandInfo? currentMatch = null;
string? path = DoPowerShellRelativePathLookup();
if (!string.IsNullOrEmpty(path))
{
currentMatch = GetInfoFromPath(path);
}
return currentMatch;
}
/// <summary>
/// Gets the CommandInfo representing the current command match.
/// </summary>
/// <value></value>
/// <exception cref="InvalidOperationException">
/// The enumerator is positioned before the first element of
/// the collection or after the last element.
/// </exception>
CommandInfo IEnumerator<CommandInfo>.Current
{
get
{
if ((_currentState == SearchState.SearchingAliases && _currentMatch == null) ||
_currentState == SearchState.NoMoreMatches ||
_currentMatch == null)
{
throw PSTraceSource.NewInvalidOperationException();
}
return _currentMatch;
}
}
object IEnumerator.Current
{
get
{
return ((IEnumerator<CommandInfo>)this).Current;
}
}
/// <summary>
/// Required by the IEnumerator generic interface.
/// Resets the searcher.
/// </summary>
public void Dispose()
{
if (_pathSearcher != null)
{
_pathSearcher.Dispose();
_pathSearcher = null;
}
Reset();
GC.SuppressFinalize(this);
}
#region private members
/// <summary>
/// Gets the next command info using the command name as a path.
/// </summary>
/// <returns>
/// A CommandInfo for the next command if it exists as a path, or null otherwise.
/// </returns>
private CommandInfo? GetNextFromPath()
{
CommandInfo? result = null;
do // false loop
{
CommandDiscovery.discoveryTracer.WriteLine(
"The name appears to be a qualified path: {0}",
_commandName);
CommandDiscovery.discoveryTracer.WriteLine(
"Trying to resolve the path as an PSPath");
// Find the match if it is.
// Try literal path resolution if it is set to run first
if (_commandResolutionOptions.HasFlag(SearchResolutionOptions.ResolveLiteralThenPathPatterns))
{
var path = GetNextLiteralPathThatExistsAndHandleExceptions(_commandName, out _);
if (path != null)
{
return GetInfoFromPath(path);
}
}
Collection<string> resolvedPaths = new Collection<string>();
if (WildcardPattern.ContainsWildcardCharacters(_commandName))
{
resolvedPaths = GetNextFromPathUsingWildcards(_commandName, out _);
}
// Try literal path resolution if wildcards are enable first and wildcard search failed
if (!_commandResolutionOptions.HasFlag(SearchResolutionOptions.ResolveLiteralThenPathPatterns) &&
resolvedPaths.Count == 0)
{
string? path = GetNextLiteralPathThatExistsAndHandleExceptions(_commandName, out _);
if (path != null)
{
return GetInfoFromPath(path);
}
}
if (resolvedPaths.Count > 1)
{
CommandDiscovery.discoveryTracer.TraceError(
"The path resolved to more than one result so this path cannot be used.");
break;
}
// If the path was resolved, and it exists
if (resolvedPaths.Count == 1 &&
File.Exists(resolvedPaths[0]))
{
string path = resolvedPaths[0];
CommandDiscovery.discoveryTracer.WriteLine(
"Path resolved to: {0}",
path);
result = GetInfoFromPath(path);
}
} while (false);
return result;
}
/// <summary>
/// Gets the next path using WildCards.
/// </summary>
/// <param name="command">
/// The command to search for.
/// </param>
/// <param name="provider">The provider that the command was found in.</param>
/// <returns>
/// A collection of full paths to the commands which were found.
/// </returns>
private Collection<string> GetNextFromPathUsingWildcards(string? command, out ProviderInfo? provider)
{
try
{
return _context.LocationGlobber.GetGlobbedProviderPathsFromMonadPath(path: command, allowNonexistingPaths: false, provider: out provider, providerInstance: out _);
}
catch (ItemNotFoundException)
{
CommandDiscovery.discoveryTracer.TraceError(
"The path could not be found: {0}",
command);
}
catch (DriveNotFoundException)
{
CommandDiscovery.discoveryTracer.TraceError(
"A drive could not be found for the path: {0}",
command);
}
catch (ProviderNotFoundException)
{
CommandDiscovery.discoveryTracer.TraceError(
"A provider could not be found for the path: {0}",
command);
}
catch (InvalidOperationException)
{
CommandDiscovery.discoveryTracer.TraceError(
"The path specified a home directory, but the provider home directory was not set. {0}",
command);
}
catch (ProviderInvocationException providerException)
{
CommandDiscovery.discoveryTracer.TraceError(
"The provider associated with the path '{0}' encountered an error: {1}",
command,
providerException.Message);
}
catch (PSNotSupportedException)
{
CommandDiscovery.discoveryTracer.TraceError(
"The provider associated with the path '{0}' does not implement ContainerCmdletProvider",
command);
}
provider = null;
return new Collection<string>();
}
private static bool checkPath(string path, string commandName)
{
return path.StartsWith(commandName, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Gets the appropriate CommandInfo instance given the specified path.
/// </summary>
/// <param name="path">
/// The path to create the CommandInfo for.
/// </param>
/// <returns>
/// An instance of the appropriate CommandInfo derivative given the specified path.
/// </returns>
/// <exception cref="FileLoadException">
/// The <paramref name="path"/> refers to a cmdlet, or cmdletprovider
/// and it could not be loaded as an XML document.
/// </exception>
/// <exception cref="FormatException">
/// The <paramref name="path"/> refers to a cmdlet, or cmdletprovider
/// that does not adhere to the appropriate file format for its extension.
/// </exception>
/// <exception cref="MetadataException">
/// If <paramref name="path"/> refers to a cmdlet file that
/// contains invalid metadata.
/// </exception>
private CommandInfo? GetInfoFromPath(string path)
{
CommandInfo? result = null;
do // false loop
{
if (!File.Exists(path))
{
CommandDiscovery.discoveryTracer.TraceError("The path does not exist: {0}", path);
break;
}
// Now create the appropriate CommandInfo using the extension
string? extension = null;
try
{
extension = Path.GetExtension(path);
}
catch (ArgumentException)
{
// If the path contains illegal characters that
// weren't caught by the other APIs, GetExtension
// will throw an exception.
// For example, looking for a command called
// `abcdef
// The `a will be translated into the beep control character
// which is not a legal file system character.
}
if (extension == null)
{
result = null;
break;
}
if (string.Equals(extension, StringLiterals.PowerShellScriptFileExtension, StringComparison.OrdinalIgnoreCase))
{
if ((_commandTypes & CommandTypes.ExternalScript) != 0)
{
string scriptName = Path.GetFileName(path);
CommandDiscovery.discoveryTracer.WriteLine(
"Command Found: path ({0}) is a script with name: {1}",
path,
scriptName);
// The path is to a PowerShell script
result = new ExternalScriptInfo(scriptName, path, _context);
break;
}
break;
}
if ((_commandTypes & CommandTypes.Application) != 0)
{
// Anything else is treated like an application
string appName = Path.GetFileName(path);
CommandDiscovery.discoveryTracer.WriteLine(
"Command Found: path ({0}) is an application with name: {1}",
path,
appName);
result = new ApplicationInfo(appName, path, _context);
break;
}
} while (false);
// Verify that this script is not untrusted, if we aren't constrained.
if (ShouldSkipCommandResolutionForConstrainedLanguage(result, _context))
{
result = null;
}
return result;
}
/// <summary>
/// Gets the next matching alias.
/// </summary>
/// <returns>
/// A CommandInfo representing the next matching alias if found, otherwise null.
/// </returns>
private CommandInfo? GetNextAlias()
{
CommandInfo? result = null;
if ((_commandResolutionOptions & SearchResolutionOptions.ResolveAliasPatterns) != 0)
{
if (_matchingAlias == null)
{
// Generate the enumerator of matching alias names
Collection<AliasInfo> matchingAliases = new Collection<AliasInfo>();
WildcardPattern aliasMatcher =
WildcardPattern.Get(
_commandName,
WildcardOptions.IgnoreCase);
foreach (KeyValuePair<string, AliasInfo> aliasEntry in _context.EngineSessionState.GetAliasTable())
{
if (aliasMatcher.IsMatch(aliasEntry.Key) ||
(_fuzzyMatcher is not null && _fuzzyMatcher.IsFuzzyMatch(aliasEntry.Key, _commandName)))
{
matchingAliases.Add(aliasEntry.Value);
}
}
// Process alias from modules
AliasInfo? c = GetAliasFromModules(_commandName);
if (c != null)
{
matchingAliases.Add(c);
}
_matchingAlias = matchingAliases.GetEnumerator();
}
if (!_matchingAlias.MoveNext())
{
// Advance the state
_currentState = SearchState.SearchingFunctions;
_matchingAlias = null;
}
else
{
result = _matchingAlias.Current;
}
}
else
{
// Advance the state
_currentState = SearchState.SearchingFunctions;
result = _context.EngineSessionState.GetAlias(_commandName) ?? GetAliasFromModules(_commandName);
}
// Verify that this alias was not created by an untrusted constrained language,
// if we aren't constrained.
if (ShouldSkipCommandResolutionForConstrainedLanguage(result, _context))
{
result = null;
}
if (result != null)
{
CommandDiscovery.discoveryTracer.WriteLine(
"Alias found: {0} {1}",
result.Name,
result.Definition);
}
return result;
}
/// <summary>
/// Gets the next matching function.
/// </summary>
/// <returns>
/// A CommandInfo representing the next matching function if found, otherwise null.
/// </returns>
private CommandInfo? GetNextFunction()
{
CommandInfo? result = null;
if (_commandResolutionOptions.HasFlag(SearchResolutionOptions.ResolveFunctionPatterns))
{
if (_matchingFunctionEnumerator == null)
{
Collection<CommandInfo?> matchingFunction = new Collection<CommandInfo?>();
// Generate the enumerator of matching function names
WildcardPattern functionMatcher =
WildcardPattern.Get(
_commandName,
WildcardOptions.IgnoreCase);
foreach ((string functionName, FunctionInfo functionInfo) in _context.EngineSessionState.GetFunctionTable())
{
if (functionMatcher.IsMatch(functionName) ||
(_fuzzyMatcher is not null && _fuzzyMatcher.IsFuzzyMatch(functionName, _commandName)))
{
matchingFunction.Add(functionInfo);
}
else if (_commandResolutionOptions.HasFlag(SearchResolutionOptions.UseAbbreviationExpansion))
{
if (_commandName.Equals(ModuleUtils.AbbreviateName(functionName), StringComparison.OrdinalIgnoreCase))
{
matchingFunction.Add(functionInfo);
}
}
}
// Process functions from modules
CommandInfo? cmdInfo = GetFunctionFromModules(_commandName);
if (cmdInfo != null)
{
matchingFunction.Add(cmdInfo);
}
_matchingFunctionEnumerator = matchingFunction.GetEnumerator();
}
if (!_matchingFunctionEnumerator.MoveNext())
{
// Advance the state
_currentState = SearchState.SearchingCmdlets;
_matchingFunctionEnumerator = null;
}
else
{
result = _matchingFunctionEnumerator.Current;
}
}
else
{
// Advance the state
_currentState = SearchState.SearchingCmdlets;
result = GetFunction(_commandName);
}
// Verify that this function was not created by an untrusted constrained language,
// if we aren't constrained.
if (ShouldSkipCommandResolutionForConstrainedLanguage(result, _context))
{
result = null;
}
return result;
}
// Don't return commands to the user if that might result in:
// - Trusted commands calling untrusted functions that the user has overridden
// - Debug prompts calling internal functions that are likely to have code injection
private static bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInfo? result, ExecutionContext executionContext)
{
if (result == null)
{
return false;
}
// Don't return untrusted commands to trusted functions.
if (result.DefiningLanguageMode == PSLanguageMode.ConstrainedLanguage && executionContext.LanguageMode == PSLanguageMode.FullLanguage)
{
if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit)
{
return true;
}
// This audit log message is to inform the user that an expected command will not be available because it is not trusted
// when the machine is in policy enforcement mode.
SystemPolicy.LogWDACAuditMessage(
context: executionContext,
title: CommandBaseStrings.SearcherWDACLogTitle,
message: StringUtil.Format(CommandBaseStrings.SearcherWDACLogMessage, result.Name, result.ModuleName ?? string.Empty),
fqid: "CommandSearchFailureForUntrustedCommand");
}
// Don't allow invocation of trusted functions from debug breakpoints.
// They were probably defined within a trusted script, and could be
// susceptible to injection attacks. However, we do allow execution
// of functions defined in the global scope (i.e.: "more",) as those
// are intended to be exposed explicitly to users.
if ((result is FunctionInfo) &&
(executionContext.LanguageMode == PSLanguageMode.ConstrainedLanguage) &&
(result.DefiningLanguageMode == PSLanguageMode.FullLanguage) &&
(executionContext.Debugger != null) &&
(executionContext.Debugger.InBreakpoint) &&
(!(executionContext.TopLevelSessionState.GetFunctionTableAtScope("GLOBAL").ContainsKey(result.Name))))
{
return true;
}
return false;
}
private AliasInfo? GetAliasFromModules(string command)
{
AliasInfo? result = null;
if (command.IndexOf('\\') > 0)
{
// See if it's a module qualified alias...
PSSnapinQualifiedName? qualifiedName = PSSnapinQualifiedName.GetInstance(command);
if (qualifiedName != null && !string.IsNullOrEmpty(qualifiedName.PSSnapInName))
{
PSModuleInfo? module = GetImportedModuleByName(qualifiedName.PSSnapInName);
module?.ExportedAliases.TryGetValue(qualifiedName.ShortName, out result);
}
}
return result;
}
private CommandInfo? GetFunctionFromModules(string command)
{
FunctionInfo? result = null;
if (command.IndexOf('\\') > 0)
{
// See if it's a module qualified function call...
PSSnapinQualifiedName? qualifiedName = PSSnapinQualifiedName.GetInstance(command);
if (qualifiedName != null && !string.IsNullOrEmpty(qualifiedName.PSSnapInName))
{
PSModuleInfo? module = GetImportedModuleByName(qualifiedName.PSSnapInName);
module?.ExportedFunctions.TryGetValue(qualifiedName.ShortName, out result);
}
}
return result;
}
private PSModuleInfo? GetImportedModuleByName(string moduleName)
{
PSModuleInfo? module = null;
List<PSModuleInfo> modules = _context.Modules.GetModules(new string[] { moduleName }, false);
if (modules != null && modules.Count > 0)
{
foreach (PSModuleInfo m in modules)
{
if (_context.previousModuleImported.ContainsKey(m.Name) && ((string?)_context.previousModuleImported[m.Name] == m.Path))
{
module = m;
break;
}
}
module ??= modules[0];
}
return module;
}
/// <summary>
/// Gets the FunctionInfo or FilterInfo for the specified function name.
/// </summary>
/// <param name="function">
/// The name of the function/filter to retrieve.
/// </param>
/// <returns>
/// A FunctionInfo if the function name exists and is a function, a FilterInfo if
/// the filter name exists and is a filter, or null otherwise.
/// </returns>
private CommandInfo? GetFunction(string function)
{
CommandInfo? result = _context.EngineSessionState.GetFunction(function);
if (result != null)
{
var formatString = result switch
{
FilterInfo => "Filter found: {0}",
ConfigurationInfo => "Configuration found: {0}",
_ => "Function found: {0}",
};
CommandDiscovery.discoveryTracer.WriteLine(formatString, function);
}
else
{
result = GetFunctionFromModules(function);
}
return result;
}
/// <summary>
/// Gets the next cmdlet from the collection of matching cmdlets.
/// If the collection doesn't exist yet it is created and the
/// enumerator is moved to the first item in the collection.
/// </summary>
/// <returns>
/// A CmdletInfo for the next matching Cmdlet or null if there are
/// no more matches.
/// </returns>
private CmdletInfo? GetNextCmdlet()
{
CmdletInfo? result = null;
bool useAbbreviationExpansion = _commandResolutionOptions.HasFlag(SearchResolutionOptions.UseAbbreviationExpansion);
if (_matchingCmdlet == null)
{
if (_commandResolutionOptions.HasFlag(SearchResolutionOptions.CommandNameIsPattern) || useAbbreviationExpansion)
{
Collection<CmdletInfo> matchingCmdletInfo = new Collection<CmdletInfo>();
PSSnapinQualifiedName? PSSnapinQualifiedCommandName =
PSSnapinQualifiedName.GetInstance(_commandName);
if (!useAbbreviationExpansion && PSSnapinQualifiedCommandName == null)
{
return null;
}
string? moduleName = PSSnapinQualifiedCommandName?.PSSnapInName;
var cmdletShortName = PSSnapinQualifiedCommandName?.ShortName;
WildcardPattern? cmdletMatcher = cmdletShortName != null
? WildcardPattern.Get(cmdletShortName, WildcardOptions.IgnoreCase)
: null;
SessionStateInternal ss = _context.EngineSessionState;
foreach (List<CmdletInfo> cmdletList in ss.GetCmdletTable().Values)
{
foreach (CmdletInfo cmdlet in cmdletList)
{
if ((cmdletMatcher is not null && cmdletMatcher.IsMatch(cmdlet.Name)) ||
(_fuzzyMatcher is not null && _fuzzyMatcher.IsFuzzyMatch(cmdlet.Name, _commandName)))
{
if (string.IsNullOrEmpty(moduleName) || moduleName.Equals(cmdlet.ModuleName, StringComparison.OrdinalIgnoreCase))
{
// If PSSnapin is specified, make sure they match
matchingCmdletInfo.Add(cmdlet);
}
}
else if (useAbbreviationExpansion)
{
if (_commandName.Equals(ModuleUtils.AbbreviateName(cmdlet.Name), StringComparison.OrdinalIgnoreCase))
{
matchingCmdletInfo.Add(cmdlet);
}
}
}
}
_matchingCmdlet = matchingCmdletInfo.GetEnumerator();
}
else
{
_matchingCmdlet = _context.CommandDiscovery.GetCmdletInfo(_commandName,
_commandResolutionOptions.HasFlag(SearchResolutionOptions.SearchAllScopes));
}
}
if (!_matchingCmdlet.MoveNext())
{
// Advance the state
_currentState = SearchState.StartSearchingForExternalCommands;
_matchingCmdlet = null;
}
else
{
result = _matchingCmdlet.Current;
}
return traceResult(result);
}
private IEnumerator<CmdletInfo>? _matchingCmdlet;
[return: NotNullIfNotNull("result")]
private static CmdletInfo? traceResult(CmdletInfo? result)
{
if (result != null)
{
CommandDiscovery.discoveryTracer.WriteLine(
"Cmdlet found: {0} {1}",
result.Name,
result.ImplementingType);
}
return result;
}
private string? DoPowerShellRelativePathLookup()
{
string? result = null;
if (_context.EngineSessionState != null &&
_context.EngineSessionState.ProviderCount > 0 && _commandName.Length != 0)
{
// NTRAID#Windows OS Bugs-1009294-2004/02/04-JeffJon
// This is really slow. Maybe since we are only allowing FS paths right
// now we should use the file system APIs to verify the existence of the file.
// Since the path to the command was not found using the PATH variable,
// maybe it is relative to the current location. Try resolving the
// path.
// Relative Path: ".\command.exe"
// Home Path: "~\command.exe"
// Drive Relative Path: "\Users\User\AppData\Local\Temp\command.exe"
char firstChar = _commandName[0];
if (firstChar == '.' || firstChar == '~' || firstChar == '\\')
{
using (CommandDiscovery.discoveryTracer.TraceScope(
"{0} appears to be a relative path. Trying to resolve relative path",
_commandName))
{
result = ResolvePSPath(_commandName);
}
}
}
return result;
}
/// <summary>
/// Resolves the given path as an PSPath and ensures that it was resolved
/// by the FileSystemProvider.
/// </summary>
/// <param name="path">
/// The path to resolve.
/// </param>
/// <returns>
/// The path that was resolved. Null if the path couldn't be resolved or was
/// not resolved by the FileSystemProvider.
/// </returns>
private string? ResolvePSPath(string? path)
{
string? result = null;
try
{
ProviderInfo? provider = null;
string? resolvedPath = null;
// Try literal path resolution if it is set to run first
if (_commandResolutionOptions.HasFlag(SearchResolutionOptions.ResolveLiteralThenPathPatterns))
{
// Cannot return early as this code path only expects
// The file system provider and the final check for that
// must verify this before we return.
resolvedPath = GetNextLiteralPathThatExists(path, out provider);
}
if (WildcardPattern.ContainsWildcardCharacters(path) &&
((resolvedPath == null) || (provider == null)))
{
// Let PowerShell resolve relative path with wildcards.
Collection<string> resolvedPaths = GetNextFromPathUsingWildcards(path, out provider);
if (resolvedPaths.Count == 0)
{
resolvedPath = null;
CommandDiscovery.discoveryTracer.TraceError(
"The relative path with wildcard did not resolve to valid path. {0}",
path);
}
else if (resolvedPaths.Count > 1)
{
resolvedPath = null;
CommandDiscovery.discoveryTracer.TraceError(
"The relative path with wildcard resolved to multiple paths. {0}",
path);
}
else
{
resolvedPath = resolvedPaths[0];
}
}
// Try literal path resolution if wildcards are enabled first and wildcard search failed
if (!_commandResolutionOptions.HasFlag(SearchResolutionOptions.ResolveLiteralThenPathPatterns) &&
((resolvedPath == null) || (provider == null)))
{
resolvedPath = GetNextLiteralPathThatExists(path, out provider);
}
// Verify the path was resolved to a file system path
if (provider != null && provider.NameEquals(_context.ProviderNames.FileSystem))
{
result = resolvedPath;
CommandDiscovery.discoveryTracer.WriteLine(
"The relative path was resolved to: {0}",
result);
}
else
{
// The path was not to the file system
CommandDiscovery.discoveryTracer.TraceError(
"The relative path was not a file system path. {0}",
path);
}
}
catch (InvalidOperationException)
{
CommandDiscovery.discoveryTracer.TraceError(
"The home path was not specified for the provider. {0}",
path);
}
catch (ProviderInvocationException providerInvocationException)
{
CommandDiscovery.discoveryTracer.TraceError(
"While resolving the path, \"{0}\", an error was encountered by the provider: {1}",
path,
providerInvocationException.Message);
}
catch (ItemNotFoundException)
{
CommandDiscovery.discoveryTracer.TraceError(
"The path does not exist: {0}",
path);
}
catch (DriveNotFoundException driveNotFound)
{
CommandDiscovery.discoveryTracer.TraceError(
"The drive does not exist: {0}",
driveNotFound.ItemName);
}
return result;
}
/// <summary>
/// Gets the next literal path.
/// Filtering to ones that exist for the filesystem.
/// Handles Exceptions
/// </summary>
/// <param name="command">
/// The command to search for.
/// </param>
/// <param name="provider">The provider that the command was found in.</param>
/// <returns>
/// Full path to the command.
/// </returns>
private string? GetNextLiteralPathThatExistsAndHandleExceptions(string command, out ProviderInfo? provider)
{
try
{
return GetNextLiteralPathThatExists(command, out provider);
}
catch (ItemNotFoundException)
{
CommandDiscovery.discoveryTracer.TraceError(
"The path could not be found: {0}",
_commandName);
}
catch (DriveNotFoundException)
{
// This can be because we think a scope or a url is a drive
// and need to continue searching.
// Although, scope does not work through get-command
CommandDiscovery.discoveryTracer.TraceError(
"A drive could not be found for the path: {0}",
_commandName);
}
catch (ProviderNotFoundException)
{
CommandDiscovery.discoveryTracer.TraceError(
"A provider could not be found for the path: {0}",
_commandName);
}
catch (InvalidOperationException)
{
CommandDiscovery.discoveryTracer.TraceError(
"The path specified a home directory, but the provider home directory was not set. {0}",
_commandName);
}
catch (ProviderInvocationException providerException)
{
CommandDiscovery.discoveryTracer.TraceError(
"The provider associated with the path '{0}' encountered an error: {1}",
_commandName,
providerException.Message);
}
catch (PSNotSupportedException)
{
CommandDiscovery.discoveryTracer.TraceError(
"The provider associated with the path '{0}' does not implement ContainerCmdletProvider",
_commandName);
}
provider = null;
return null;
}
/// <summary>
/// Gets the next literal path.
/// Filtering to ones that exist for the filesystem.
/// </summary>
/// <param name="command">
/// The command to search for.
/// </param>
/// <param name="provider">The provider that the command was found in.</param>
/// <returns>
/// Full path to the command.
/// </returns>
private string? GetNextLiteralPathThatExists(string? command, out ProviderInfo? provider)
{
string resolvedPath = _context.LocationGlobber.GetProviderPath(command, out provider);
if (provider.NameEquals(_context.ProviderNames.FileSystem)
&& !File.Exists(resolvedPath)
&& !Directory.Exists(resolvedPath))
{
provider = null;
return null;
}
return resolvedPath;
}
/// <summary>
/// Creates a collection of patterns used to find the command.
/// </summary>
/// <param name="name">
/// The name of the command to search for.
/// </param>
/// <param name="commandDiscovery">Get names for command discovery.</param>
/// <returns>
/// A collection of the patterns used to find the command.
/// The patterns are as follows:
/// 1. [commandName].cmdlet
/// 2. [commandName].ps1
/// 3..x
/// foreach (extension in PATHEXT)
/// [commandName].[extension]
/// x+1. [commandName]
/// </returns>
/// <exception cref="ArgumentException">
/// If <paramref name="name"/> contains one or more of the
/// invalid characters defined in InvalidPathChars.
/// </exception>
internal LookupPathCollection ConstructSearchPatternsFromName(string name, bool commandDiscovery = false)
{
var result = new LookupPathCollection();
// First check to see if the commandName has an extension, if so
// look for that first
bool commandNameAddedFirst = Path.HasExtension(name);
if (commandNameAddedFirst)
{
result.Add(name);
}
// Add the extensions for script, module and data files in that order...
if (_commandTypes.HasFlag(CommandTypes.ExternalScript))
{
result.Add(name + StringLiterals.PowerShellScriptFileExtension);
if (!commandDiscovery)
{
// psd1 and psm1 are not executable, so don't add them
result.Add(name + StringLiterals.PowerShellModuleFileExtension);
result.Add(name + StringLiterals.PowerShellDataFileExtension);
}
}
#if !UNIX
if (_commandTypes.HasFlag(CommandTypes.Application))
{
// Now add each extension from the PATHEXT environment variable
foreach (string extension in CommandDiscovery.PathExtensions)
{
result.Add(name + extension);
}
}
#endif
// Now add the commandName by itself if it wasn't added as the first pattern
if (!commandNameAddedFirst)
{
result.Add(name);
}
return result;
}
/// <summary>
/// Determines if the given command name is a qualified PowerShell path.
/// </summary>
/// <param name="commandName">
/// The name of the command.
/// </param>
/// <returns>
/// True if the command name is either a provider-qualified or PowerShell drive-qualified
/// path. False otherwise.
/// </returns>
private static bool IsQualifiedPSPath(string commandName)
{
Dbg.Assert(
!string.IsNullOrEmpty(commandName),
"The caller should have verified the commandName");
bool result =
LocationGlobber.IsAbsolutePath(commandName) ||
LocationGlobber.IsProviderQualifiedPath(commandName) ||
LocationGlobber.IsHomePath(commandName) ||
LocationGlobber.IsProviderDirectPath(commandName);
return result;
}
private enum CanDoPathLookupResult
{
Yes,
PathIsRooted,
WildcardCharacters,
DirectorySeparator,
IllegalCharacters
}
/// <summary>
/// Determines if the command name has any path special
/// characters which would require resolution. If so,
/// path lookup will not succeed.
/// </summary>
/// <param name="possiblePath">
/// The command name (or possible path) to look for the special characters.
/// </param>
/// <returns>
/// True if the command name does not contain any special
/// characters. False otherwise.
/// </returns>
private static CanDoPathLookupResult CanDoPathLookup(string possiblePath)
{
CanDoPathLookupResult result = CanDoPathLookupResult.Yes;
do // false loop
{
// If the command name contains any wildcard characters
// we can't do the path lookup
if (WildcardPattern.ContainsWildcardCharacters(possiblePath))
{
result = CanDoPathLookupResult.WildcardCharacters;
break;
}
try
{
if (Path.IsPathRooted(possiblePath))
{
result = CanDoPathLookupResult.PathIsRooted;
break;
}
}
catch (ArgumentException)
{
result = CanDoPathLookupResult.IllegalCharacters;
break;
}
// If the command contains any path separators, we can't
// do the path lookup
if (possiblePath.AsSpan().IndexOfAny('\\', '/') != -1)
{
result = CanDoPathLookupResult.DirectorySeparator;
break;
}
// If the command contains any invalid path characters, we can't
// do the path lookup
if (PathUtils.ContainsInvalidPathChars(possiblePath))
{
result = CanDoPathLookupResult.IllegalCharacters;
break;
}
} while (false);
return result;
}
/// <summary>
/// The command name to search for.
/// </summary>
private string _commandName;
/// <summary>
/// Determines which command types will be globbed.
/// </summary>
private readonly SearchResolutionOptions _commandResolutionOptions;
/// <summary>
/// Determines which types of commands to look for.
/// </summary>
private CommandTypes _commandTypes = CommandTypes.All;
/// <summary>
/// The enumerator that uses the Path to
/// search for commands.
/// </summary>
private CommandPathSearch? _pathSearcher;
/// <summary>
/// The execution context instance for the current engine...
/// </summary>
private readonly ExecutionContext _context;
/// <summary>
/// The fuzzy matcher to use for fuzzy searching.
/// </summary>
private readonly FuzzyMatcher? _fuzzyMatcher;
/// <summary>
/// A routine to initialize the path searcher...
/// </summary>
/// <exception cref="ArgumentException">
/// If the commandName used to construct this object
/// contains one or more of the invalid characters defined
/// in InvalidPathChars.
/// </exception>
private void setupPathSearcher()
{
// If it's already set up, just return...
if (_pathSearcher != null)
{
return;
}
// We are never going to look for non-executable commands in CommandSearcher.
// Even though file types like .DOC, .LOG,.TXT, etc. can be opened / invoked, users think of these as files, not applications.
// So I don't think we should show applications with the additional extensions at all.
// Applications should only include files whose extensions are in the PATHEXT list and these would only be returned with the All parameter.
if ((_commandResolutionOptions & SearchResolutionOptions.CommandNameIsPattern) != 0)
{
_canDoPathLookup = true;
_canDoPathLookupResult = CanDoPathLookupResult.Yes;
_pathSearcher =
new CommandPathSearch(
_commandName,
_context.CommandDiscovery.GetLookupDirectoryPaths(),
_context,
acceptableCommandNames: null,
_fuzzyMatcher);
}
else
{
_canDoPathLookupResult = CanDoPathLookup(_commandName);
if (_canDoPathLookupResult == CanDoPathLookupResult.Yes)
{
_canDoPathLookup = true;
_commandName = _commandName.TrimEnd(Utils.Separators.PathSearchTrimEnd);
_pathSearcher =
new CommandPathSearch(
_commandName,
_context.CommandDiscovery.GetLookupDirectoryPaths(),
_context,
ConstructSearchPatternsFromName(_commandName, commandDiscovery: true),
fuzzyMatcher: null);
}
else if (_canDoPathLookupResult == CanDoPathLookupResult.PathIsRooted)
{
_canDoPathLookup = true;
string? directory = Path.GetDirectoryName(_commandName);
var directoryCollection = new LookupPathCollection { directory };
CommandDiscovery.discoveryTracer.WriteLine(
"The path is rooted, so only doing the lookup in the specified directory: {0}",
directory);
string fileName = Path.GetFileName(_commandName);
if (!string.IsNullOrEmpty(fileName))
{
fileName = fileName.TrimEnd(Utils.Separators.PathSearchTrimEnd);
_pathSearcher =
new CommandPathSearch(
fileName,
directoryCollection,
_context,
ConstructSearchPatternsFromName(fileName, commandDiscovery: true),
fuzzyMatcher: null);
}
else
{
_canDoPathLookup = false;
}
}
else if (_canDoPathLookupResult == CanDoPathLookupResult.DirectorySeparator)
{
_canDoPathLookup = true;
// We must try to resolve the path as an PSPath or else we can't do
// path lookup for relative paths.
string? directory = Path.GetDirectoryName(_commandName);
directory = ResolvePSPath(directory);
CommandDiscovery.discoveryTracer.WriteLine(
"The path is relative, so only doing the lookup in the specified directory: {0}",
directory);
if (directory == null)
{
_canDoPathLookup = false;
}
else
{
var directoryCollection = new LookupPathCollection { directory };
string fileName = Path.GetFileName(_commandName);
if (!string.IsNullOrEmpty(fileName))
{
fileName = fileName.TrimEnd(Utils.Separators.PathSearchTrimEnd);
_pathSearcher =
new CommandPathSearch(
fileName,
directoryCollection,
_context,
ConstructSearchPatternsFromName(fileName, commandDiscovery: true),
fuzzyMatcher: null);
}
else
{
_canDoPathLookup = false;
}
}
}
}
}
/// <summary>
/// Resets the enumerator to before the first command match, public for IEnumerable.
/// </summary>
public void Reset()
{
// If this is a command coming from outside the runspace and there are no
// permitted scripts or applications,
// remove them from the set of things to search for...
if (_commandOrigin == CommandOrigin.Runspace)
{
if (_context.EngineSessionState.Applications.Count == 0)
_commandTypes &= ~CommandTypes.Application;
if (_context.EngineSessionState.Scripts.Count == 0)
_commandTypes &= ~CommandTypes.ExternalScript;
}
_pathSearcher?.Reset();
_currentMatch = null;
_currentState = SearchState.SearchingAliases;
_matchingAlias = null;
_matchingCmdlet = null;
}
internal CommandOrigin CommandOrigin
{
get { return _commandOrigin; }
set { _commandOrigin = value; }
}
private CommandOrigin _commandOrigin = CommandOrigin.Internal;
/// <summary>
/// An enumerator of the matching aliases.
/// </summary>
private IEnumerator<AliasInfo>? _matchingAlias;
/// <summary>
/// An enumerator of the matching functions.
/// </summary>
private IEnumerator<CommandInfo?>? _matchingFunctionEnumerator;
/// <summary>
/// The CommandInfo that references the command that matches the pattern.
/// </summary>
private CommandInfo? _currentMatch;
private bool _canDoPathLookup;
private CanDoPathLookupResult _canDoPathLookupResult = CanDoPathLookupResult.Yes;
/// <summary>
/// The current state of the enumerator.
/// </summary>
private SearchState _currentState = SearchState.SearchingAliases;
private enum SearchState
{
// the searcher has been reset or has not been advanced since being created.
SearchingAliases,
// the searcher has finished alias resolution and is now searching for functions.
SearchingFunctions,
// the searcher has finished function resolution and is now searching for cmdlets
SearchingCmdlets,
// the search has finished builtin script resolution and is now searching for external commands
StartSearchingForExternalCommands,
// the searcher has moved to
PowerShellPathResolution,
// the searcher has moved to a qualified file system path
QualifiedFileSystemPath,
// the searcher has moved to using a CommandPathSearch object
// for resolution
PathSearch,
// the searcher has moved to using a CommandPathSearch object
// with get prepended to the command name for resolution
GetPathSearch,
// the searcher has moved to resolving the command as a
// relative PowerShell path
PowerShellRelativePath,
// No more matches can be found
NoMoreMatches,
}
#endregion private members
}
/// <summary>
/// Determines which types of commands should be globbed using the specified
/// pattern. Any flag that is not specified will only match if exact.
/// </summary>
[Flags]
internal enum SearchResolutionOptions
{
None = 0x0,
ResolveAliasPatterns = 0x01,
ResolveFunctionPatterns = 0x02,
CommandNameIsPattern = 0x04,
SearchAllScopes = 0x08,
/// <summary>
/// Enable searching for cmdlets/functions by abbreviation expansion.
/// </summary>
UseAbbreviationExpansion = 0x10,
/// <summary>
/// Enable resolving wildcard in paths.
/// </summary>
ResolveLiteralThenPathPatterns = 0x20
}
}
|