/// <summary>
        /// Search an alias help target.
        /// </summary>
        /// <remarks>
        /// This will,
        ///     a. use _sessionState object to get a list of alias that match the target.
        ///     b. for each alias, retrieve help info as in ExactMatchHelp.
        /// </remarks>
        /// <param name="helpRequest">help request object</param>
        /// <param name="searchOnlyContent">
        /// If true, searches for pattern in the help content. Individual
        /// provider can decide which content to search in.
        ///
        /// If false, searches for pattern in the command names.
        /// </param>
        /// <returns>a IEnumerable of helpinfo object</returns>
        internal override IEnumerable <HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent)
        {
            // aliases do not have help content...so doing nothing in that case
            if (!searchOnlyContent)
            {
                string    target    = helpRequest.Target;
                string    pattern   = target;
                Hashtable hashtable = new Hashtable(StringComparer.OrdinalIgnoreCase);

                if (!WildcardPattern.ContainsWildcardCharacters(target))
                {
                    pattern += "*";
                }

                WildcardPattern matcher = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);
                IDictionary <string, AliasInfo> aliasTable = _sessionState.Internal.GetAliasTable();

                foreach (string name in aliasTable.Keys)
                {
                    if (matcher.IsMatch(name))
                    {
                        HelpRequest exactMatchHelpRequest = helpRequest.Clone();
                        exactMatchHelpRequest.Target = name;
                        // Duplicates??
                        foreach (HelpInfo helpInfo in ExactMatchHelp(exactMatchHelpRequest))
                        {
                            // Component/Role/Functionality match is done only for SearchHelp
                            // as "get-help * -category alias" should not forwad help to
                            // CommandHelpProvider..(ExactMatchHelp does forward help to
                            // CommandHelpProvider)
                            if (!Match(helpInfo, helpRequest))
                            {
                                continue;
                            }

                            if (hashtable.ContainsKey(name))
                            {
                                continue;
                            }

                            hashtable.Add(name, null);

                            yield return(helpInfo);
                        }
                    }
                }

                CommandSearcher searcher =
                    new CommandSearcher(
                        pattern,
                        SearchResolutionOptions.ResolveAliasPatterns, CommandTypes.Alias,
                        _context);

                while (searcher.MoveNext())
                {
                    CommandInfo current = ((IEnumerator <CommandInfo>)searcher).Current;

                    if (_context.CurrentPipelineStopping)
                    {
                        yield break;
                    }

                    AliasInfo alias = current as AliasInfo;

                    if (alias != null)
                    {
                        string      name = alias.Name;
                        HelpRequest exactMatchHelpRequest = helpRequest.Clone();
                        exactMatchHelpRequest.Target = name;

                        // Duplicates??
                        foreach (HelpInfo helpInfo in ExactMatchHelp(exactMatchHelpRequest))
                        {
                            // Component/Role/Functionality match is done only for SearchHelp
                            // as "get-help * -category alias" should not forwad help to
                            // CommandHelpProvider..(ExactMatchHelp does forward help to
                            // CommandHelpProvider)
                            if (!Match(helpInfo, helpRequest))
                            {
                                continue;
                            }

                            if (hashtable.ContainsKey(name))
                            {
                                continue;
                            }

                            hashtable.Add(name, null);

                            yield return(helpInfo);
                        }
                    }
                }

                foreach (CommandInfo current in ModuleUtils.GetMatchingCommands(pattern, _context, helpRequest.CommandOrigin))
                {
                    if (_context.CurrentPipelineStopping)
                    {
                        yield break;
                    }

                    AliasInfo alias = current as AliasInfo;

                    if (alias != null)
                    {
                        string name = alias.Name;

                        HelpInfo helpInfo = AliasHelpInfo.GetHelpInfo(alias);

                        if (hashtable.ContainsKey(name))
                        {
                            continue;
                        }

                        hashtable.Add(name, null);

                        yield return(helpInfo);
                    }
                }
            }
        }
Beispiel #2
0
        // Visit one the other variations:
        //  - Dotting scripts
        //  - Setting aliases
        //  - Importing modules
        //  - Exporting module members
        public override AstVisitAction VisitCommand(CommandAst commandAst)
        {
            string commandName =
                commandAst.GetCommandName() ??
                GetSafeValueVisitor.GetSafeValue(commandAst.CommandElements[0], null, GetSafeValueVisitor.SafeValueContext.ModuleAnalysis) as string;

            if (commandName == null)
                return AstVisitAction.SkipChildren;

            // They are trying to dot a script
            if (commandAst.InvocationOperator == TokenKind.Dot)
            {
                // . Foo-Bar4.ps1
                // . $psScriptRoot\Foo-Bar.ps1 -Bing Baz
                // . ""$psScriptRoot\Support Files\Foo-Bar2.ps1"" -Bing Baz
                // . '$psScriptRoot\Support Files\Foo-Bar3.ps1' -Bing Baz

                DiscoveredModules.Add(
                    new RequiredModuleInfo { Name = commandName, CommandsToPostFilter = new List<string>() });
                ModuleIntrinsics.Tracer.WriteLine("Module dots {0}", commandName);
            }

            // They are setting an alias.
            if (String.Equals(commandName, "New-Alias", StringComparison.OrdinalIgnoreCase) ||
                String.Equals(commandName, "Microsoft.PowerShell.Utility\\New-Alias", StringComparison.OrdinalIgnoreCase) ||
                String.Equals(commandName, "Set-Alias", StringComparison.OrdinalIgnoreCase) ||
                String.Equals(commandName, "Microsoft.PowerShell.Utility\\Set-Alias", StringComparison.OrdinalIgnoreCase) ||
                String.Equals(commandName, "nal", StringComparison.OrdinalIgnoreCase) ||
                String.Equals(commandName, "sal", StringComparison.OrdinalIgnoreCase))
            {
                // Set-Alias Foo-Bar5 Foo-Bar
                // Set-Alias -Name Foo-Bar6 -Value Foo-Bar
                // sal Foo-Bar7 Foo-Bar
                // sal -Value Foo-Bar -Name Foo-Bar8

                var boundParameters = DoPsuedoParameterBinding(commandAst, commandName);

                var name = boundParameters["Name"] as string;
                if (!string.IsNullOrEmpty(name))
                {
                    var value = boundParameters["Value"] as string;
                    if (!string.IsNullOrEmpty(value))
                    {
                        // These aren't stored in DiscoveredExports, as they are only
                        // exported after the user calls Export-ModuleMember.
                        DiscoveredAliases[name] = value;
                        ModuleIntrinsics.Tracer.WriteLine("Module defines alias: {0} = {1}", name, value);
                    }
                }

                return AstVisitAction.SkipChildren;
            }

            // They are importing a module
            if (String.Equals(commandName, "Import-Module", StringComparison.OrdinalIgnoreCase) ||
                String.Equals(commandName, "ipmo", StringComparison.OrdinalIgnoreCase))
            {
                // Import-Module Module1
                // Import-Module Module2 -Function Foo-Module2*, Foo-Module2Second* -Cmdlet Foo-Module2Cmdlet,Foo-Module2Cmdlet*
                // Import-Module Module3 -Function Foo-Module3Command1, Foo-Module3Command2
                // Import-Module Module4,
                //    Module5
                // Import-Module -Name Module6,
                //    Module7 -Global

                var boundParameters = DoPsuedoParameterBinding(commandAst, commandName);

                List<string> commandsToPostFilter = new List<string>();

                Action<string> onEachCommand = importedCommandName =>
                {
                    commandsToPostFilter.Add(importedCommandName);
                };

                // Process any exports from the module that we determine from
                // the -Function, -Cmdlet, or -Alias parameters
                ProcessCmdletArguments(boundParameters["Function"], onEachCommand);
                ProcessCmdletArguments(boundParameters["Cmdlet"], onEachCommand);
                ProcessCmdletArguments(boundParameters["Alias"], onEachCommand);

                // Now, go through all of the discovered modules on Import-Module
                // and register them for deeper investigation.
                Action<string> onEachModule = moduleName =>
                {
                    ModuleIntrinsics.Tracer.WriteLine("Discovered module import: {0}", moduleName);
                    DiscoveredModules.Add(
                        new RequiredModuleInfo
                        {
                            Name = moduleName,
                            CommandsToPostFilter = commandsToPostFilter
                        });
                };
                ProcessCmdletArguments(boundParameters["Name"], onEachModule);

                return AstVisitAction.SkipChildren;
            }

            // They are exporting a module member
            if (String.Equals(commandName, "Export-ModuleMember", StringComparison.OrdinalIgnoreCase) ||
                String.Equals(commandName, "Microsoft.PowerShell.Core\\Export-ModuleMember", StringComparison.OrdinalIgnoreCase) ||
                String.Equals(commandName, "$script:ExportModuleMember", StringComparison.OrdinalIgnoreCase))
            {
                // Export-ModuleMember *
                // Export-ModuleMember Exported-UnNamedModuleMember
                // Export-ModuleMember -Function Exported-FunctionModuleMember1, Exported-FunctionModuleMember2 -Cmdlet Exported-CmdletModuleMember `
                //    -Alias Exported-AliasModuleMember
                // & $script:ExportModuleMember -Function (...)

                var boundParameters = DoPsuedoParameterBinding(commandAst, commandName);

                Action<string> onEachFunction = exportedCommandName =>
                {
                    DiscoveredCommandFilters.Add(exportedCommandName);
                    ModuleIntrinsics.Tracer.WriteLine("Discovered explicit export: {0}", exportedCommandName);

                    // If the export doesn't contain wildcards, then add it to the
                    // discovered commands as well. It is likely that they created
                    // the command dynamically
                    if ((!WildcardPattern.ContainsWildcardCharacters(exportedCommandName)) &&
                        (!DiscoveredExports.Contains(exportedCommandName)))
                    {
                        DiscoveredExports.Add(exportedCommandName);
                    }
                };
                ProcessCmdletArguments(boundParameters["Function"], onEachFunction);
                ProcessCmdletArguments(boundParameters["Cmdlet"], onEachFunction);

                Action<string> onEachAlias = exportedAlias =>
                {
                    DiscoveredCommandFilters.Add(exportedAlias);

                    // If the export doesn't contain wildcards, then add it to the
                    // discovered commands as well. It is likely that they created
                    // the command dynamically
                    if (!WildcardPattern.ContainsWildcardCharacters(exportedAlias))
                    {
                        DiscoveredAliases[exportedAlias] = null;
                    }
                };
                ProcessCmdletArguments(boundParameters["Alias"], onEachAlias);

                return AstVisitAction.SkipChildren;
            }

            // They are exporting a module member using our advanced 'public' function
            // that we've presented in many demos
            if ((String.Equals(commandName, "public", StringComparison.OrdinalIgnoreCase)) &&
                (commandAst.CommandElements.Count > 2))
            {
                // public function Publicly-ExportedFunction
                // public alias Publicly-ExportedAlias
                string publicCommandName = commandAst.CommandElements[2].ToString().Trim();
                DiscoveredExports.Add(publicCommandName);
                DiscoveredCommandFilters.Add(publicCommandName);
            }

            return AstVisitAction.SkipChildren;
        }
        internal override IEnumerable <HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent)
        {
            string target  = helpRequest.Target;
            string pattern = target;
            int    countOfHelpInfoObjectsFound = 0;
            // this will be used only when searchOnlyContent == true
            WildcardPattern wildCardPattern = null;

            if ((!searchOnlyContent) && (!WildcardPattern.ContainsWildcardCharacters(target)))
            {
                // Search all the about conceptual topics. This pattern
                // makes about topics discoverable without actually
                // using the word "about_" as in "get-help while".
                pattern = "*" + pattern + "*";
            }

            if (searchOnlyContent)
            {
                string searchTarget = helpRequest.Target;
                if (!WildcardPattern.ContainsWildcardCharacters(helpRequest.Target))
                {
                    searchTarget = "*" + searchTarget + "*";
                }

                wildCardPattern = WildcardPattern.Get(searchTarget, WildcardOptions.Compiled | WildcardOptions.IgnoreCase);
                // search all about_* topics
                pattern = "*";
            }

            pattern += ".help.txt";

            Collection <string> files = MUIFileSearcher.SearchFiles(pattern, GetExtendedSearchPaths());

            var matchedFilesToRemove = FilterToLatestModuleVersion(files);

            if (files == null)
            {
                yield break;
            }

            foreach (string file in files)
            {
                if (matchedFilesToRemove.Contains(file))
                {
                    continue;
                }

                // Check whether the file is already loaded
                if (!_helpFiles.ContainsKey(file))
                {
                    try
                    {
                        LoadHelpFile(file);
                    }
                    catch (IOException ioException)
                    {
                        ReportHelpFileError(ioException, helpRequest.Target, file);
                    }
                    catch (System.Security.SecurityException securityException)
                    {
                        ReportHelpFileError(securityException, helpRequest.Target, file);
                    }
                }

                HelpFileHelpInfo helpInfo = GetCache(file) as HelpFileHelpInfo;

                if (helpInfo != null)
                {
                    if (searchOnlyContent)
                    {
                        if (!helpInfo.MatchPatternInContent(wildCardPattern))
                        {
                            continue;
                        }
                    }

                    countOfHelpInfoObjectsFound++;
                    yield return(helpInfo);

                    if (countOfHelpInfoObjectsFound >= helpRequest.MaxResults && helpRequest.MaxResults > 0)
                    {
                        yield break;
                    }
                }
            }
        }
        internal override IEnumerable <HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent)
        {
            string item = helpRequest.Target;
            Collection <string> iteratorVariable1 = new Collection <string>();
            WildcardPattern     pattern           = null;
            bool iteratorVariable3 = !WildcardPattern.ContainsWildcardCharacters(helpRequest.Target);

            if (!searchOnlyContent)
            {
                if (iteratorVariable3)
                {
                    if (item.IndexOf('-') >= 0)
                    {
                        iteratorVariable1.Add(item + "*");
                    }
                    else
                    {
                        iteratorVariable1.Add("*" + item + "*");
                    }
                }
                else
                {
                    iteratorVariable1.Add(item);
                }
            }
            else
            {
                iteratorVariable1.Add("*");
                string target = helpRequest.Target;
                if (iteratorVariable3)
                {
                    target = "*" + helpRequest.Target + "*";
                }
                pattern = new WildcardPattern(target, WildcardOptions.IgnoreCase | WildcardOptions.Compiled);
            }
            int       iteratorVariable4 = 0;
            Hashtable iteratorVariable5 = new Hashtable(StringComparer.OrdinalIgnoreCase);
            Hashtable iteratorVariable6 = new Hashtable(StringComparer.OrdinalIgnoreCase);

            foreach (string iteratorVariable7 in iteratorVariable1)
            {
                CommandSearcher commandSearcherForSearch = this.GetCommandSearcherForSearch(iteratorVariable7, this._context);
                while (commandSearcherForSearch.MoveNext())
                {
                    if (this._context.CurrentPipelineStopping)
                    {
                        break;
                    }
                    CommandInfo current    = commandSearcherForSearch.Current;
                    CmdletInfo  cmdletInfo = current as CmdletInfo;
                    HelpInfo    helpInfo   = null;
                    string      key        = null;
                    if (cmdletInfo != null)
                    {
                        helpInfo = this.GetHelpInfo(cmdletInfo, !iteratorVariable3);
                        key      = cmdletInfo.FullName;
                    }
                    else
                    {
                        IScriptCommandInfo scriptCommandInfo = current as IScriptCommandInfo;
                        if (scriptCommandInfo != null)
                        {
                            key      = current.Name;
                            helpInfo = this.GetHelpInfo(scriptCommandInfo, !iteratorVariable3, searchOnlyContent);
                        }
                    }
                    if (helpInfo != null)
                    {
                        if (!SessionState.IsVisible(helpRequest.CommandOrigin, current))
                        {
                            if (!iteratorVariable6.ContainsKey(key))
                            {
                                iteratorVariable6.Add(key, null);
                            }
                        }
                        else if ((!iteratorVariable5.ContainsKey(key) && Match(helpInfo, helpRequest, current)) && (!searchOnlyContent || helpInfo.MatchPatternInContent(pattern)))
                        {
                            iteratorVariable5.Add(key, null);
                            iteratorVariable4++;
                            yield return(helpInfo);

                            if ((iteratorVariable4 < helpRequest.MaxResults) || (helpRequest.MaxResults <= 0))
                            {
                                continue;
                            }
                            break;
                        }
                    }
                }
                if (this.HelpCategory == (System.Management.Automation.HelpCategory.Cmdlet | System.Management.Automation.HelpCategory.Alias))
                {
                    foreach (CommandInfo iteratorVariable13 in ModuleUtils.GetMatchingCommands(iteratorVariable7, this._context, helpRequest.CommandOrigin, false))
                    {
                        if (this._context.CurrentPipelineStopping)
                        {
                            break;
                        }
                        if (SessionState.IsVisible(helpRequest.CommandOrigin, iteratorVariable13))
                        {
                            CmdletInfo iteratorVariable14 = iteratorVariable13 as CmdletInfo;
                            HelpInfo   iteratorVariable15 = null;
                            string     fullName           = null;
                            if (iteratorVariable14 != null)
                            {
                                iteratorVariable15 = this.GetHelpInfo(iteratorVariable14, !iteratorVariable3);
                                fullName           = iteratorVariable14.FullName;
                            }
                            else
                            {
                                IScriptCommandInfo info2 = iteratorVariable13 as IScriptCommandInfo;
                                if (info2 != null)
                                {
                                    fullName           = iteratorVariable13.Name;
                                    iteratorVariable15 = this.GetHelpInfo(info2, !iteratorVariable3, searchOnlyContent);
                                }
                            }
                            if ((((iteratorVariable15 != null) && !iteratorVariable5.ContainsKey(fullName)) && (!iteratorVariable6.ContainsKey(fullName) && Match(iteratorVariable15, helpRequest, iteratorVariable13))) && (!searchOnlyContent || iteratorVariable15.MatchPatternInContent(pattern)))
                            {
                                iteratorVariable5.Add(fullName, null);
                                iteratorVariable4++;
                                yield return(iteratorVariable15);

                                if ((iteratorVariable4 >= helpRequest.MaxResults) && (helpRequest.MaxResults > 0))
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Search for provider help based on a search target.
        /// </summary>
        /// <param name="helpRequest">help request object</param>
        /// <param name="searchOnlyContent">
        /// If true, searches for pattern in the help content. Individual
        /// provider can decide which content to search in.
        ///
        /// If false, searches for pattern in the command names.
        /// </param>
        /// <returns></returns>
        internal override IEnumerable <HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent)
        {
            int    countOfHelpInfoObjectsFound = 0;
            string target  = helpRequest.Target;
            string pattern = target;
            // this will be used only when searchOnlyContent == true
            WildcardPattern wildCardPattern = null;

            bool decoratedSearch = !WildcardPattern.ContainsWildcardCharacters(target);

            if (!searchOnlyContent)
            {
                if (decoratedSearch)
                {
                    pattern += "*";
                }
            }
            else
            {
                string searchTarget = helpRequest.Target;
                if (decoratedSearch)
                {
                    searchTarget = "*" + helpRequest.Target + "*";
                }

                wildCardPattern = WildcardPattern.Get(searchTarget, WildcardOptions.Compiled | WildcardOptions.IgnoreCase);
                // search in all providers
                pattern = "*";
            }

            PSSnapinQualifiedName snapinQualifiedNameForPattern =
                PSSnapinQualifiedName.GetInstance(pattern);

            if (null == snapinQualifiedNameForPattern)
            {
                yield break;
            }

            foreach (ProviderInfo providerInfo in _sessionState.Provider.GetAll())
            {
                if (providerInfo.IsMatch(pattern))
                {
                    try
                    {
                        LoadHelpFile(providerInfo);
                    }
                    catch (IOException ioException)
                    {
                        if (!decoratedSearch)
                        {
                            ReportHelpFileError(ioException, providerInfo.Name, providerInfo.HelpFile);
                        }
                    }
                    catch (System.Security.SecurityException securityException)
                    {
                        if (!decoratedSearch)
                        {
                            ReportHelpFileError(securityException, providerInfo.Name, providerInfo.HelpFile);
                        }
                    }
                    catch (XmlException xmlException)
                    {
                        if (!decoratedSearch)
                        {
                            ReportHelpFileError(xmlException, providerInfo.Name, providerInfo.HelpFile);
                        }
                    }

                    HelpInfo helpInfo = GetCache(providerInfo.PSSnapInName + "\\" + providerInfo.Name);

                    if (helpInfo != null)
                    {
                        if (searchOnlyContent)
                        {
                            // ignore help objects that do not have pattern in its help
                            // content.
                            if (!helpInfo.MatchPatternInContent(wildCardPattern))
                            {
                                continue;
                            }
                        }

                        countOfHelpInfoObjectsFound++;
                        yield return(helpInfo);

                        if (countOfHelpInfoObjectsFound >= helpRequest.MaxResults && helpRequest.MaxResults > 0)
                        {
                            yield break;
                        }
                    }
                }
            }
        }
Beispiel #6
0
        /// <summary>
        /// On Windows, just append <paramref name="arg"/>.
        /// On Unix, do globbing as appropriate, otherwise just append <paramref name="arg"/>.
        /// </summary>
        /// <param name="arg">The argument that possibly needs expansion.</param>
        /// <param name="usedQuotes">True if the argument was a quoted string (single or double).</param>
        private void PossiblyGlobArg(string arg, bool usedQuotes)
        {
            var argExpanded = false;

#if UNIX
            // On UNIX systems, we expand arguments containing wildcard expressions against
            // the file system just like bash, etc.
            if (!usedQuotes && WildcardPattern.ContainsWildcardCharacters(arg))
            {
                // See if the current working directory is a filesystem provider location
                // We won't do the expansion if it isn't since native commands can only access the file system.
                var cwdinfo = Context.EngineSessionState.CurrentLocation;

                // If it's a filesystem location then expand the wildcards
                if (cwdinfo.Provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
                {
                    // On UNIX, paths starting with ~ or absolute paths are not normalized
                    bool normalizePath = arg.Length == 0 || !(arg[0] == '~' || arg[0] == '/');

                    // See if there are any matching paths otherwise just add the pattern as the argument
                    Collection <PSObject> paths = null;
                    try
                    {
                        paths = Context.EngineSessionState.InvokeProvider.ChildItem.Get(arg, false);
                    }
                    catch
                    {
                        // Fallthrough will append the pattern unchanged.
                    }

                    // Expand paths, but only from the file system.
                    if (paths?.Count > 0 && paths.All(p => p.BaseObject is FileSystemInfo))
                    {
                        var sep = string.Empty;
                        foreach (var path in paths)
                        {
                            _arguments.Append(sep);
                            sep = " ";
                            var expandedPath = (path.BaseObject as FileSystemInfo).FullName;
                            if (normalizePath)
                            {
                                expandedPath =
                                    Context.SessionState.Path.NormalizeRelativePath(expandedPath, cwdinfo.ProviderPath);
                            }
                            // If the path contains spaces, then add quotes around it.
                            if (NeedQuotes(expandedPath))
                            {
                                _arguments.Append("\"");
                                _arguments.Append(expandedPath);
                                _arguments.Append("\"");
                            }
                            else
                            {
                                _arguments.Append(expandedPath);
                            }

                            argExpanded = true;
                        }
                    }
                }
            }
            else if (!usedQuotes)
            {
                // Even if there are no wildcards, we still need to possibly
                // expand ~ into the filesystem provider home directory path
                ProviderInfo fileSystemProvider = Context.EngineSessionState.GetSingleProvider(FileSystemProvider.ProviderName);
                string       home = fileSystemProvider.Home;
                if (string.Equals(arg, "~"))
                {
                    _arguments.Append(home);
                    argExpanded = true;
                }
                else if (arg.StartsWith("~/", StringComparison.OrdinalIgnoreCase))
                {
                    var replacementString = home + arg.Substring(1);
                    _arguments.Append(replacementString);
                    argExpanded = true;
                }
            }
#endif // UNIX

            if (!argExpanded)
            {
                _arguments.Append(arg);
            }
        }
Beispiel #7
0
        /// <summary>
        /// Resets the current working drive and directory to the first
        /// entry on the working directory stack and removes that entry
        /// from the stack.
        /// </summary>
        /// <param name="stackName">
        /// The ID of the stack to pop the location from. If it is null or
        /// empty the default stack is used.
        /// </param>
        /// <returns>
        /// A PathInfo object representing the location that was popped
        /// from the location stack and set as the new location.
        /// </returns>
        /// <exception cref="ArgumentException">
        /// If the path on the stack does not exist, is not a container, or
        /// resolved to multiple containers.
        /// or
        /// If <paramref name="stackName"/> contains wildcard characters and resolves
        /// to multiple location stacks.
        /// or
        /// A stack was not found with the specified name.
        /// </exception>
        /// <exception cref="ProviderNotFoundException">
        /// If the path on the stack refers to a provider that does not exist.
        /// </exception>
        /// <exception cref="DriveNotFoundException">
        /// If the path on the stack refers to a drive that does not exist.
        /// </exception>
        /// <exception cref="ProviderInvocationException">
        /// If the provider associated with the path on the stack threw an
        /// exception.
        /// </exception>
        internal PathInfo PopLocation(string stackName)
        {
            if (string.IsNullOrEmpty(stackName))
            {
                stackName = _defaultStackName;
            }

            if (WildcardPattern.ContainsWildcardCharacters(stackName))
            {
                // Need to glob the stack name, but it can only glob to a single.
                bool haveMatch = false;

                WildcardPattern stackNamePattern =
                    WildcardPattern.Get(stackName, WildcardOptions.IgnoreCase);

                foreach (string key in _workingLocationStack.Keys)
                {
                    if (stackNamePattern.IsMatch(key))
                    {
                        if (haveMatch)
                        {
                            throw
                                PSTraceSource.NewArgumentException(
                                    "stackName",
                                    SessionStateStrings.StackNameResolvedToMultiple,
                                    stackName);
                        }

                        haveMatch = true;
                        stackName = key;
                    }
                }
            }

            PathInfo result = CurrentLocation;

            try
            {
                Stack <PathInfo> locationStack = null;
                if (!_workingLocationStack.TryGetValue(stackName, out locationStack))
                {
                    if (!string.Equals(stackName, startingDefaultStackName, StringComparison.OrdinalIgnoreCase))
                    {
                        throw
                            PSTraceSource.NewArgumentException(
                                "stackName",
                                SessionStateStrings.StackNotFound,
                                stackName);
                    }

                    return(null);
                }

                PathInfo poppedWorkingDirectory = locationStack.Pop();

                Dbg.Diagnostics.Assert(
                    poppedWorkingDirectory != null,
                    "All items in the workingLocationStack should be " +
                    "of type PathInfo");

                string newPath =
                    LocationGlobber.GetMshQualifiedPath(
                        WildcardPattern.Escape(poppedWorkingDirectory.Path),
                        poppedWorkingDirectory.GetDrive());

                result = SetLocation(newPath);

                if (locationStack.Count == 0 &&
                    !string.Equals(stackName, startingDefaultStackName, StringComparison.OrdinalIgnoreCase))
                {
                    // Remove the stack from the stack list if it
                    // no longer contains any paths.
                    _workingLocationStack.Remove(stackName);
                }
            }
            catch (InvalidOperationException)
            {
                // This is a no-op. We stay with the current working
                // directory.
            }

            return(result);
        }
Beispiel #8
0
        internal override IEnumerable <HelpInfo> SearchHelp(
            HelpRequest helpRequest,
            bool searchOnlyContent)
        {
            using (HelpFileHelpProvider.tracer.TraceMethod())
            {
                string          target  = helpRequest.Target;
                string          pattern = target;
                int             countOfHelpInfoObjectsFound = 0;
                WildcardPattern wildCardPattern             = (WildcardPattern)null;
                if (!searchOnlyContent && !WildcardPattern.ContainsWildcardCharacters(target))
                {
                    pattern = "*" + pattern + "*";
                }
                if (searchOnlyContent)
                {
                    string pattern1 = helpRequest.Target;
                    if (!WildcardPattern.ContainsWildcardCharacters(helpRequest.Target))
                    {
                        pattern1 = "*" + pattern1 + "*";
                    }
                    wildCardPattern = new WildcardPattern(pattern1, WildcardOptions.Compiled | WildcardOptions.IgnoreCase);
                    pattern         = "*";
                }
                // ISSUE: reference to a compiler-generated field
                this.\u003Cpattern\u003E5__e += ".help.txt";
                Collection <string> files = MUIFileSearcher.SearchFiles(pattern, this.GetSearchPaths());
                if (files != null)
                {
                    foreach (string str in files)
                    {
                        if (!this._helpFiles.ContainsKey((object)str))
                        {
                            try
                            {
                                this.LoadHelpFile(str);
                            }
                            catch (IOException ex)
                            {
                                this.ReportHelpFileError((Exception)ex, helpRequest.Target, str);
                            }
                            catch (SecurityException ex)
                            {
                                this.ReportHelpFileError((Exception)ex, helpRequest.Target, str);
                            }
                        }
                        HelpFileHelpInfo helpInfo = this.GetCache(str) as HelpFileHelpInfo;
                        if (helpInfo != null && (!searchOnlyContent || helpInfo.MatchPatternInContent(wildCardPattern)))
                        {
                            ++countOfHelpInfoObjectsFound;
                            yield return((HelpInfo)helpInfo);

                            if (countOfHelpInfoObjectsFound >= helpRequest.MaxResults && helpRequest.MaxResults > 0)
                            {
                                break;
                            }
                        }
                    }
                }
            }
        }
Beispiel #9
0
        public override AstVisitAction VisitCommand(CommandAst commandAst)
        {
            string commandName = commandAst.GetCommandName();

            if (string.IsNullOrEmpty(commandName))
            {
                commandName = commandAst.CommandElements[0].ToString().Trim(new char[] { '"', '\'' });
            }
            if (commandAst.InvocationOperator == TokenKind.Dot)
            {
                commandName = Regex.Replace(commandName, @"\$[^\\]*\\", "", RegexOptions.IgnoreCase);
                RequiredModuleInfo item = new RequiredModuleInfo {
                    Name = commandName,
                    CommandsToPostFilter = new List <string>()
                };
                this.DiscoveredModules.Add(item);
                ModuleIntrinsics.Tracer.WriteLine("Module dots " + commandName, new object[0]);
            }
            if (((string.Equals(commandName, "New-Alias", StringComparison.OrdinalIgnoreCase) || string.Equals(commandName, @"Microsoft.PowerShell.Utility\New-Alias", StringComparison.OrdinalIgnoreCase)) || (string.Equals(commandName, "Set-Alias", StringComparison.OrdinalIgnoreCase) || string.Equals(commandName, @"Microsoft.PowerShell.Utility\Set-Alias", StringComparison.OrdinalIgnoreCase))) || (string.Equals(commandName, "nal", StringComparison.OrdinalIgnoreCase) || string.Equals(commandName, "sal", StringComparison.OrdinalIgnoreCase)))
            {
                string str2 = this.GetParameterByNameOrPosition("Name", 0, commandAst);
                string str3 = this.GetParameterByNameOrPosition("Value", 1, commandAst);
                if (!string.IsNullOrEmpty(str2))
                {
                    this.DiscoveredAliases[str2] = str3;
                    ModuleIntrinsics.Tracer.WriteLine("Module defines alias: " + str2 + "=" + str3, new object[0]);
                }
            }
            if (string.Equals(commandName, "Import-Module", StringComparison.OrdinalIgnoreCase) || string.Equals(commandName, "ipmo", StringComparison.OrdinalIgnoreCase))
            {
                List <string> list = new List <string>();
                string        str4 = this.GetParameterByNameOrPosition("Function", -1, commandAst);
                if (!string.IsNullOrEmpty(str4))
                {
                    list.AddRange(this.ProcessExportedCommandList(str4));
                }
                string str5 = this.GetParameterByNameOrPosition("Cmdlet", -1, commandAst);
                if (!string.IsNullOrEmpty(str5))
                {
                    list.AddRange(this.ProcessExportedCommandList(str5));
                }
                string str6 = this.GetParameterByNameOrPosition("Alias", -1, commandAst);
                if (!string.IsNullOrEmpty(str6))
                {
                    list.AddRange(this.ProcessExportedCommandList(str6));
                }
                string str7 = this.GetParameterByNameOrPosition("Name", 0, commandAst);
                if (!string.IsNullOrEmpty(str7))
                {
                    foreach (string str8 in str7.Split(new char[] { ',' }))
                    {
                        ModuleIntrinsics.Tracer.WriteLine("Discovered module import: " + str8, new object[0]);
                        RequiredModuleInfo info2 = new RequiredModuleInfo {
                            Name = str8.Trim(),
                            CommandsToPostFilter = list
                        };
                        this.DiscoveredModules.Add(info2);
                    }
                }
            }
            if ((string.Equals(commandName, "Export-ModuleMember", StringComparison.OrdinalIgnoreCase) || string.Equals(commandName, @"Microsoft.PowerShell.Core\Export-ModuleMember", StringComparison.OrdinalIgnoreCase)) || string.Equals(commandName, "$script:ExportModuleMember", StringComparison.OrdinalIgnoreCase))
            {
                List <string> list2     = new List <string>();
                string        arguments = this.GetParameterByNameOrPosition("Function", 0, commandAst);
                list2.AddRange(this.ExtractArgumentList(arguments));
                string str10 = this.GetParameterByNameOrPosition("Cmdlet", -1, commandAst);
                list2.AddRange(this.ExtractArgumentList(str10));
                foreach (string str11 in list2)
                {
                    this.DiscoveredCommandFilters.Add(str11);
                    ModuleIntrinsics.Tracer.WriteLine("Discovered explicit export: " + str11, new object[0]);
                    if (!WildcardPattern.ContainsWildcardCharacters(str11) && !this.DiscoveredExports.Contains(str11))
                    {
                        this.DiscoveredExports.Add(str11);
                    }
                }
                list2 = new List <string>();
                string str12 = this.GetParameterByNameOrPosition("Alias", -1, commandAst);
                list2.AddRange(this.ExtractArgumentList(str12));
                foreach (string str13 in list2)
                {
                    this.DiscoveredCommandFilters.Add(str13);
                    if (!WildcardPattern.ContainsWildcardCharacters(str13) && !this.DiscoveredAliases.ContainsKey(str13))
                    {
                        this.DiscoveredAliases.Add(str13, null);
                    }
                }
            }
            if (string.Equals(commandName, "public", StringComparison.OrdinalIgnoreCase) && (commandAst.CommandElements.Count > 2))
            {
                string str14 = commandAst.CommandElements[2].ToString().Trim();
                this.DiscoveredExports.Add(str14);
                this.DiscoveredCommandFilters.Add(str14);
            }
            return(AstVisitAction.Continue);
        }
Beispiel #10
0
        internal override IEnumerable <HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent)
        {
            int             iteratorVariable0 = 0;
            string          pattern           = helpRequest.Target;
            string          name = pattern;
            WildcardPattern iteratorVariable3 = null;
            bool            iteratorVariable4 = !WildcardPattern.ContainsWildcardCharacters(pattern);

            if (!searchOnlyContent)
            {
                if (iteratorVariable4)
                {
                    name = name + "*";
                }
            }
            else
            {
                string target = helpRequest.Target;
                if (iteratorVariable4)
                {
                    target = "*" + helpRequest.Target + "*";
                }
                iteratorVariable3 = new WildcardPattern(target, WildcardOptions.IgnoreCase | WildcardOptions.Compiled);
                name = "*";
            }
            PSSnapinQualifiedName instance = PSSnapinQualifiedName.GetInstance(name);

            if (instance != null)
            {
                foreach (ProviderInfo iteratorVariable6 in this._sessionState.Provider.GetAll())
                {
                    if (!iteratorVariable6.IsMatch(name))
                    {
                        continue;
                    }
                    try
                    {
                        this.LoadHelpFile(iteratorVariable6);
                    }
                    catch (IOException exception)
                    {
                        if (!iteratorVariable4)
                        {
                            this.ReportHelpFileError(exception, iteratorVariable6.Name, iteratorVariable6.HelpFile);
                        }
                    }
                    catch (SecurityException exception2)
                    {
                        if (!iteratorVariable4)
                        {
                            this.ReportHelpFileError(exception2, iteratorVariable6.Name, iteratorVariable6.HelpFile);
                        }
                    }
                    catch (XmlException exception3)
                    {
                        if (!iteratorVariable4)
                        {
                            this.ReportHelpFileError(exception3, iteratorVariable6.Name, iteratorVariable6.HelpFile);
                        }
                    }
                    HelpInfo cache = this.GetCache(iteratorVariable6.PSSnapInName + @"\" + iteratorVariable6.Name);
                    if ((cache != null) && (!searchOnlyContent || cache.MatchPatternInContent(iteratorVariable3)))
                    {
                        iteratorVariable0++;
                        yield return(cache);

                        if ((iteratorVariable0 >= helpRequest.MaxResults) && (helpRequest.MaxResults > 0))
                        {
                            break;
                        }
                    }
                }
            }
        }
Beispiel #11
0
        internal override IEnumerable <HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent)
        {
            if (!searchOnlyContent)
            {
                string    target            = helpRequest.Target;
                string    pattern           = target;
                Hashtable iteratorVariable2 = new Hashtable(StringComparer.OrdinalIgnoreCase);
                if (!WildcardPattern.ContainsWildcardCharacters(target))
                {
                    pattern = pattern + "*";
                }
                WildcardPattern iteratorVariable3          = new WildcardPattern(pattern, WildcardOptions.IgnoreCase);
                IDictionary <string, AliasInfo> aliasTable = this._sessionState.Internal.GetAliasTable();
                foreach (string iteratorVariable5 in aliasTable.Keys)
                {
                    if (iteratorVariable3.IsMatch(iteratorVariable5))
                    {
                        HelpRequest iteratorVariable6 = helpRequest.Clone();
                        iteratorVariable6.Target = iteratorVariable5;
                        foreach (HelpInfo iteratorVariable7 in this.ExactMatchHelp(iteratorVariable6))
                        {
                            if (!Match(iteratorVariable7, helpRequest) || iteratorVariable2.ContainsKey(iteratorVariable5))
                            {
                                continue;
                            }
                            iteratorVariable2.Add(iteratorVariable5, null);
                            yield return(iteratorVariable7);
                        }
                    }
                }
                CommandSearcher iteratorVariable8 = new CommandSearcher(pattern, SearchResolutionOptions.ResolveAliasPatterns, CommandTypes.Alias, this._context);
                while (iteratorVariable8.MoveNext())
                {
                    CommandInfo current = iteratorVariable8.Current;
                    if (this._context.CurrentPipelineStopping)
                    {
                        goto Label_0423;
                    }
                    AliasInfo iteratorVariable10 = current as AliasInfo;
                    if (iteratorVariable10 != null)
                    {
                        string      name = iteratorVariable10.Name;
                        HelpRequest iteratorVariable12 = helpRequest.Clone();
                        iteratorVariable12.Target = name;
                        foreach (HelpInfo iteratorVariable13 in this.ExactMatchHelp(iteratorVariable12))
                        {
                            if (!Match(iteratorVariable13, helpRequest) || iteratorVariable2.ContainsKey(name))
                            {
                                continue;
                            }
                            iteratorVariable2.Add(name, null);
                            yield return(iteratorVariable13);
                        }
                    }
                }
                foreach (CommandInfo iteratorVariable14 in ModuleUtils.GetMatchingCommands(pattern, this._context, helpRequest.CommandOrigin, false))
                {
                    if (this._context.CurrentPipelineStopping)
                    {
                        break;
                    }
                    AliasInfo aliasInfo = iteratorVariable14 as AliasInfo;
                    if (aliasInfo != null)
                    {
                        string   key      = aliasInfo.Name;
                        HelpInfo helpInfo = AliasHelpInfo.GetHelpInfo(aliasInfo);
                        if (!iteratorVariable2.ContainsKey(key))
                        {
                            iteratorVariable2.Add(key, null);
                            yield return(helpInfo);
                        }
                    }
                }
            }
Label_0423:
            yield break;
        }