Ejemplo n.º 1
0
 internal CommandSearcher(string commandName, SearchResolutionOptions options, CommandTypes commandTypes, ExecutionContext context)
 {
     this.commandName = commandName;
     this._context    = context;
     this.commandResolutionOptions = options;
     this.commandTypes             = commandTypes;
     this.Reset();
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Searches for PowerShell commands, optionally using wildcard patterns.
        /// </summary>
        /// <param name="name">The name of the command to use.</param>
        /// <param name="commandTypes">Type of commands to support.</param>
        /// <param name="nameIsPattern">If true treat the name as a pattern to search for.</param>
        /// <returns>Collection of command names...</returns>
        public IEnumerable <CommandInfo> GetCommands(string name, CommandTypes commandTypes, bool nameIsPattern)
        {
            if (name == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(name));
            }

            SearchResolutionOptions options = nameIsPattern ?
                                              (SearchResolutionOptions.CommandNameIsPattern | SearchResolutionOptions.ResolveFunctionPatterns | SearchResolutionOptions.ResolveAliasPatterns)
                : SearchResolutionOptions.None;

            return(GetCommands(name, commandTypes, options));
        }
Ejemplo n.º 3
0
 internal CommandSearcher(
     string commandName,
     SearchResolutionOptions options,
     CommandTypes commandTypes,
     ExecutionContext context)
 {
     if (context == null)
     {
         throw CommandSearcher.tracer.NewArgumentNullException(nameof(context));
     }
     this.commandName = !string.IsNullOrEmpty(commandName) ? commandName : throw CommandSearcher.tracer.NewArgumentException(nameof(commandName));
     this._context    = context;
     this.commandResolutionOptions = options;
     this.commandTypes             = commandTypes;
     this.Reset();
 }
Ejemplo n.º 4
0
        internal IEnumerable <CommandInfo> GetCommands(string name, CommandTypes commandTypes, SearchResolutionOptions options, CommandOrigin?commandOrigin = null)
        {
            CommandSearcher searcher = new CommandSearcher(
                name,
                options,
                commandTypes,
                _context);

            if (commandOrigin != null)
            {
                searcher.CommandOrigin = commandOrigin.Value;
            }

            while (true)
            {
                try
                {
                    if (!searcher.MoveNext())
                    {
                        break;
                    }
                }
                catch (ArgumentException)
                {
                    continue;
                }
                catch (PathTooLongException)
                {
                    continue;
                }
                catch (FileLoadException)
                {
                    continue;
                }
                catch (MetadataException)
                {
                    continue;
                }
                catch (FormatException)
                {
                    continue;
                }

                CommandInfo commandInfo = ((IEnumerator)searcher).Current as CommandInfo;
                if (commandInfo != null)
                {
                    yield return(commandInfo);
                }
            }
        }
Ejemplo n.º 5
0
 private static CommandInfo TryNormalSearch(string commandName, ExecutionContext context, CommandOrigin commandOrigin, SearchResolutionOptions searchResolutionOptions, CommandTypes commandTypes, ref Exception lastError)
 {
     CommandInfo current = null;
     CommandSearcher searcher = new CommandSearcher(commandName, searchResolutionOptions, commandTypes, context) {
         CommandOrigin = commandOrigin
     };
     try
     {
         if (!searcher.MoveNext())
         {
             if (!commandName.Contains("-") && !commandName.Contains(@"\"))
             {
                 discoveryTracer.WriteLine("The command [{0}] was not found, trying again with get- prepended", new object[] { commandName });
                 commandName = "get" + '-' + commandName;
                 try
                 {
                     current = LookupCommandInfo(commandName, commandTypes, searchResolutionOptions, commandOrigin, context);
                 }
                 catch (CommandNotFoundException)
                 {
                 }
             }
             return current;
         }
         current = searcher.Current;
     }
     catch (ArgumentException exception)
     {
         lastError = exception;
     }
     catch (PathTooLongException exception2)
     {
         lastError = exception2;
     }
     catch (FileLoadException exception3)
     {
         lastError = exception3;
     }
     catch (FormatException exception4)
     {
         lastError = exception4;
     }
     catch (MetadataException exception5)
     {
         lastError = exception5;
     }
     return current;
 }
Ejemplo n.º 6
0
 private static CommandInfo TryModuleAutoDiscovery(string commandName, ExecutionContext context, string originalCommandName, CommandOrigin commandOrigin, SearchResolutionOptions searchResolutionOptions, CommandTypes commandTypes, ref Exception lastError)
 {
     CommandInfo info = null;
     try
     {
         CmdletInfo cmdlet = context.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Get-Module");
         if ((commandOrigin == CommandOrigin.Internal) || ((cmdlet != null) && (cmdlet.Visibility == SessionStateEntryVisibility.Public)))
         {
             cmdlet = context.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Import-Module");
             if ((commandOrigin == CommandOrigin.Internal) || ((cmdlet != null) && (cmdlet.Visibility == SessionStateEntryVisibility.Public)))
             {
                 discoveryTracer.WriteLine("Executing non module-qualified search: {0}", new object[] { commandName });
                 context.CommandDiscovery.RegisterLookupCommandInfoAction("ActiveModuleSearch", commandName);
                 foreach (string str in ModuleUtils.GetDefaultAvailableModuleFiles(true, true, context))
                 {
                     string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(str);
                     Dictionary<string, List<CommandTypes>> dictionary = AnalysisCache.GetExportedCommands(str, false, context);
                     if (dictionary != null)
                     {
                         if (dictionary.ContainsKey(commandName))
                         {
                             CommandInfo commandInfo = new CmdletInfo("Import-Module", typeof(ImportModuleCommand), null, null, context) {
                                 Visibility = cmdlet.Visibility
                             };
                             Command command = new Command(commandInfo);
                             discoveryTracer.WriteLine("Found in module: {0}", new object[] { str });
                             PowerShell shell = PowerShell.Create(RunspaceMode.CurrentRunspace).AddCommand(command).AddParameter("Name", str).AddParameter("Scope", "GLOBAL").AddParameter("PassThru").AddParameter("ErrorAction", ActionPreference.Ignore).AddParameter("WarningAction", ActionPreference.Ignore).AddParameter("Verbose", false).AddParameter("Debug", false);
                             Collection<PSModuleInfo> collection = null;
                             try
                             {
                                 collection = shell.Invoke<PSModuleInfo>();
                             }
                             catch (Exception exception)
                             {
                                 discoveryTracer.WriteLine("Encountered error importing module: {0}", new object[] { exception.Message });
                                 lastError = exception;
                                 CommandProcessorBase.CheckForSevereException(exception);
                             }
                             if ((collection == null) || (collection.Count == 0))
                             {
                                 string resourceStr = StringUtil.Format(DiscoveryExceptions.CouldNotAutoImportMatchingModule, commandName, fileNameWithoutExtension);
                                 CommandNotFoundException exception2 = new CommandNotFoundException(originalCommandName, lastError, "CouldNotAutoloadMatchingModule", resourceStr, new object[0]);
                                 throw exception2;
                             }
                             info = LookupCommandInfo(commandName, commandTypes, searchResolutionOptions, commandOrigin, context);
                         }
                         if (info != null)
                         {
                             return info;
                         }
                     }
                 }
             }
             return info;
         }
         return info;
     }
     catch (CommandNotFoundException)
     {
         throw;
     }
     catch (Exception exception3)
     {
         CommandProcessorBase.CheckForSevereException(exception3);
     }
     finally
     {
         context.CommandDiscovery.UnregisterLookupCommandInfoAction("ActiveModuleSearch", commandName);
     }
     return info;
 }
Ejemplo n.º 7
0
        internal static CommandInfo LookupCommandInfo(string commandName, CommandTypes commandTypes, SearchResolutionOptions searchResolutionOptions, CommandOrigin commandOrigin, ExecutionContext context)
        {
            if (string.IsNullOrEmpty(commandName))
            {
                return null;
            }
            CommandInfo result = null;
            string command = commandName;
            Exception lastError = null;
            CommandLookupEventArgs e = null;
            EventHandler<CommandLookupEventArgs> preCommandLookupAction = context.EngineIntrinsics.InvokeCommand.PreCommandLookupAction;
            if (preCommandLookupAction != null)
            {
                discoveryTracer.WriteLine("Executing PreCommandLookupAction: {0}", new object[] { commandName });
                try
                {
                    context.CommandDiscovery.RegisterLookupCommandInfoAction("ActivePreLookup", command);
                    e = new CommandLookupEventArgs(command, commandOrigin, context);
                    preCommandLookupAction(command, e);
                    discoveryTracer.WriteLine("PreCommandLookupAction returned: {0}", new object[] { e.Command });
                }
                catch (Exception exception2)
                {
                    CommandProcessorBase.CheckForSevereException(exception2);
                }
                finally
                {
                    context.CommandDiscovery.UnregisterLookupCommandInfoAction("ActivePreLookup", commandName);
                }
            }
            if ((e == null) || !e.StopSearch)
            {
                discoveryTracer.WriteLine("Looking up command: {0}", new object[] { commandName });
                result = TryNormalSearch(commandName, context, commandOrigin, searchResolutionOptions, commandTypes, ref lastError);
                if (result == null)
                {
                    PSModuleAutoLoadingPreference preference = GetCommandDiscoveryPreference(context, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference");
                    if (preference != PSModuleAutoLoadingPreference.None)
                    {
                        result = TryModuleAutoLoading(commandName, context, command, commandOrigin, result, ref lastError);
                    }
                    if (result == null)
                    {
                        if (preference == PSModuleAutoLoadingPreference.All)
                        {
                            result = TryModuleAutoDiscovery(commandName, context, command, commandOrigin, searchResolutionOptions, commandTypes, ref lastError);
                        }
                        if (result == null)
                        {
                            result = InvokeCommandNotFoundHandler(commandName, context, command, commandOrigin, result);
                        }
                    }
                }
            }
            else if (e.Command != null)
            {
                result = e.Command;
            }
            if (result != null)
            {
                EventHandler<CommandLookupEventArgs> postCommandLookupAction = context.EngineIntrinsics.InvokeCommand.PostCommandLookupAction;
                if (postCommandLookupAction != null)
                {
                    discoveryTracer.WriteLine("Executing PostCommandLookupAction: {0}", new object[] { command });
                    try
                    {
                        context.CommandDiscovery.RegisterLookupCommandInfoAction("ActivePostCommand", command);
                        e = new CommandLookupEventArgs(command, commandOrigin, context) {
                            Command = result
                        };
                        postCommandLookupAction(command, e);
                        if (e != null)
                        {
                            result = e.Command;
                            discoveryTracer.WriteLine("PreCommandLookupAction returned: {0}", new object[] { e.Command });
                        }
                    }
                    catch (Exception exception3)
                    {
                        CommandProcessorBase.CheckForSevereException(exception3);
                    }
                    finally
                    {
                        context.CommandDiscovery.UnregisterLookupCommandInfoAction("ActivePostCommand", command);
                    }
                }
            }
            if (result == null)
            {
                discoveryTracer.TraceError("'{0}' is not recognized as a cmdlet, function, operable program or script file.", new object[] { commandName });
                CommandNotFoundException exception4 = new CommandNotFoundException(command, lastError, "CommandNotFoundException", DiscoveryExceptions.CommandNotFoundException, new object[0]);

				throw exception4;
            }
            return result;
        }
Ejemplo n.º 8
0
        internal IEnumerable<CommandInfo> GetCommands(string name, CommandTypes commandTypes, SearchResolutionOptions options, CommandOrigin? commandOrigin = null)
        {
            CommandSearcher searcher = new CommandSearcher(
                name,
                options,
                commandTypes,
                _context);

            if (commandOrigin != null)
            {
                searcher.CommandOrigin = commandOrigin.Value;
            }

            do
            {
                try
                {
                    if (!searcher.MoveNext())
                    {
                        break;
                    }
                }
                catch (ArgumentException)
                {
                    continue;
                }
                catch (PathTooLongException)
                {
                    continue;
                }
                catch (FileLoadException)
                {
                    continue;
                }
                catch (MetadataException)
                {
                    continue;
                }
                catch (FormatException)
                {
                    continue;
                }

                CommandInfo commandInfo = ((IEnumerator)searcher).Current as CommandInfo;
                if (commandInfo != null)
                {
                    yield return commandInfo;
                }
            } while (true);
        }
Ejemplo n.º 9
0
        private void AccumulateMatchingCommands(IEnumerable <string> commandNames)
        {
            SearchResolutionOptions none = SearchResolutionOptions.None;

            if (this.All != false)
            {
                none = SearchResolutionOptions.SearchAllScopes;
            }
            if ((this.CommandType & CommandTypes.Alias) != 0)
            {
                none |= SearchResolutionOptions.ResolveAliasPatterns;
            }
            if ((this.CommandType & (CommandTypes.Workflow | CommandTypes.Filter | CommandTypes.Function)) != 0)
            {
                none |= SearchResolutionOptions.ResolveFunctionPatterns;
            }
            foreach (string str in commandNames)
            {
                try
                {
                    string str2    = null;
                    string pattern = str;
                    bool   flag    = false;
                    if ((str.IndexOf('\\') > 0) && (str.Split(new char[] { '\\' }).Length == 2))
                    {
                        string[] strArray = str.Split(new char[] { '\\' }, 2);
                        str2    = strArray[0];
                        pattern = strArray[1];
                        flag    = true;
                    }
                    if ((this.Module.Length == 1) && !WildcardPattern.ContainsWildcardCharacters(this.Module[0]))
                    {
                        str2 = this.Module[0];
                    }
                    bool isPattern = WildcardPattern.ContainsWildcardCharacters(pattern);
                    if (isPattern)
                    {
                        none |= SearchResolutionOptions.CommandNameIsPattern;
                    }
                    int  currentCount = 0;
                    bool flag3        = this.FindCommandForName(none, str, isPattern, true, ref currentCount);
                    if (!flag3 || isPattern)
                    {
                        if (!isPattern || !string.IsNullOrEmpty(str2))
                        {
                            string commandName = str;
                            if (!flag && !string.IsNullOrEmpty(str2))
                            {
                                commandName = str2 + @"\" + str;
                            }
                            try
                            {
                                CommandDiscovery.LookupCommandInfo(commandName, base.MyInvocation.CommandOrigin, base.Context);
                            }
                            catch (CommandNotFoundException)
                            {
                            }
                            flag3 = this.FindCommandForName(none, str, isPattern, false, ref currentCount);
                        }
                        else if ((this.ListImported == false) && ((this.TotalCount < 0) || (currentCount < this.TotalCount)))
                        {
                            foreach (CommandInfo info in ModuleUtils.GetMatchingCommands(pattern, base.Context, base.MyInvocation.CommandOrigin, true))
                            {
                                CommandInfo current = info;
                                if ((this.IsCommandMatch(ref current) && !this.IsCommandInResult(current)) && this.IsParameterMatch(current))
                                {
                                    this.accumulatedResults.Add(current);
                                    currentCount++;
                                    if ((this.TotalCount >= 0) && (currentCount >= this.TotalCount))
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    if (!flag3 && !isPattern)
                    {
                        CommandNotFoundException replaceParentContainsErrorRecordException = new CommandNotFoundException(str, null, "CommandNotFoundException", DiscoveryExceptions.CommandNotFoundException, new object[0]);
                        base.WriteError(new ErrorRecord(replaceParentContainsErrorRecordException.ErrorRecord, replaceParentContainsErrorRecordException));
                    }
                }
                catch (CommandNotFoundException exception2)
                {
                    base.WriteError(new ErrorRecord(exception2.ErrorRecord, exception2));
                }
            }
        }
Ejemplo n.º 10
0
        private bool FindCommandForName(SearchResolutionOptions options, string commandName, bool isPattern, bool emitErrors, ref int currentCount)
        {
            CommandSearcher searcher = new CommandSearcher(commandName, options, this.CommandType, base.Context);
            bool            flag     = false;

Label_0016:
            try
            {
                if (!searcher.MoveNext())
                {
                    goto Label_016F;
                }
            }
            catch (ArgumentException exception)
            {
                if (emitErrors)
                {
                    base.WriteError(new ErrorRecord(exception, "GetCommandInvalidArgument", ErrorCategory.SyntaxError, null));
                }
                goto Label_0016;
            }
            catch (PathTooLongException exception2)
            {
                if (emitErrors)
                {
                    base.WriteError(new ErrorRecord(exception2, "GetCommandInvalidArgument", ErrorCategory.SyntaxError, null));
                }
                goto Label_0016;
            }
            catch (FileLoadException exception3)
            {
                if (emitErrors)
                {
                    base.WriteError(new ErrorRecord(exception3, "GetCommandFileLoadError", ErrorCategory.ReadError, null));
                }
                goto Label_0016;
            }
            catch (MetadataException exception4)
            {
                if (emitErrors)
                {
                    base.WriteError(new ErrorRecord(exception4, "GetCommandMetadataError", ErrorCategory.MetadataError, null));
                }
                goto Label_0016;
            }
            catch (FormatException exception5)
            {
                if (emitErrors)
                {
                    base.WriteError(new ErrorRecord(exception5, "GetCommandBadFileFormat", ErrorCategory.InvalidData, null));
                }
                goto Label_0016;
            }
            CommandInfo current = searcher.Current;

            if ((!SessionState.IsVisible(base.MyInvocation.CommandOrigin, current) || !this.IsCommandMatch(ref current)) || this.IsCommandInResult(current))
            {
                goto Label_0016;
            }
            flag = true;
            if (this.IsParameterMatch(current))
            {
                currentCount++;
                if ((this.TotalCount >= 0) && (currentCount > this.TotalCount))
                {
                    goto Label_016F;
                }
                this.accumulatedResults.Add(current);
                if (this.ArgumentList != null)
                {
                    goto Label_016F;
                }
            }
            if (((isPattern || (this.All != false)) || ((this.totalCount != -1) || this.isCommandTypeSpecified)) || this.isModuleSpecified)
            {
                goto Label_0016;
            }
Label_016F:
            if (this.All != false)
            {
                foreach (CommandInfo info2 in this.GetMatchingCommandsFromModules(commandName))
                {
                    CommandInfo info3 = info2;
                    if (this.IsCommandMatch(ref info3))
                    {
                        flag = true;
                        if (!this.IsCommandInResult(info2) && this.IsParameterMatch(info3))
                        {
                            currentCount++;
                            if ((this.TotalCount >= 0) && (currentCount > this.TotalCount))
                            {
                                return(flag);
                            }
                            this.accumulatedResults.Add(info3);
                        }
                    }
                }
            }
            return(flag);
        }