private bool IsParameterMatch(ParameterMetadata parameterMetadata)
        {
            bool flag4;
            bool flag  = SessionStateUtilities.MatchesAnyWildcardPattern(parameterMetadata.Name, this._parameterNameWildcards, true);
            bool flag2 = false;

            foreach (string str in parameterMetadata.Aliases ?? Enumerable.Empty <string>())
            {
                if (SessionStateUtilities.MatchesAnyWildcardPattern(str, this._parameterNameWildcards, true))
                {
                    this._matchedParameterNames.Add(str);
                    flag2 = true;
                }
            }
            bool flag3 = flag || flag2;

            if (flag3)
            {
                this._matchedParameterNames.Add(parameterMetadata.Name);
            }
            if ((this._parameterTypes == null) || (this._parameterTypes.Length == 0))
            {
                flag4 = true;
            }
            else
            {
                flag4 = false;
                if ((this._parameterTypes != null) && (this._parameterTypes.Length > 0))
                {
                    flag4 |= this._parameterTypes.Any <PSTypeName>(new Func <PSTypeName, bool>(parameterMetadata.IsMatchingType));
                }
            }
            return(flag3 && flag4);
        }
Exemple #2
0
        private bool IsCommandNameMatchingParameters(string commandName)
        {
            if (SessionStateUtilities.MatchesAnyWildcardPattern(commandName, this.commandNamePatterns, false))
            {
                return(true);
            }
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(commandName);

            return(!fileNameWithoutExtension.Equals(commandName, StringComparison.OrdinalIgnoreCase) && SessionStateUtilities.MatchesAnyWildcardPattern(fileNameWithoutExtension, this.commandNamePatterns, false));
        }
        /// <summary>
        /// Get enabled experimental features based on the specified name patterns.
        /// </summary>
        private IEnumerable <ExperimentalFeature> GetEnabledExperimentalFeatures(IEnumerable <WildcardPattern> namePatterns)
        {
            var moduleFeatures = new List <string>();
            var moduleNames    = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            foreach (string featureName in ExperimentalFeature.EnabledExperimentalFeatureNames)
            {
                // Only process the feature names that matches any name patterns.
                if (SessionStateUtilities.MatchesAnyWildcardPattern(featureName, namePatterns, defaultValue: true))
                {
                    if (ExperimentalFeature.EngineExperimentalFeatureMap.TryGetValue(featureName, out ExperimentalFeature feature))
                    {
                        yield return(feature);
                    }
                    else
                    {
                        moduleFeatures.Add(featureName);
                        int lastDotIndex = featureName.LastIndexOf('.');
                        moduleNames.Add(featureName.Substring(0, lastDotIndex));
                    }
                }
            }

            if (moduleFeatures.Count > 0)
            {
                var featuresFromGivenModules = new Dictionary <string, ExperimentalFeature>(StringComparer.OrdinalIgnoreCase);
                foreach (string moduleFile in GetValidModuleFiles(moduleNames))
                {
                    foreach (var feature in ModuleIntrinsics.GetExperimentalFeature(moduleFile))
                    {
                        featuresFromGivenModules.TryAdd(feature.Name, feature);
                    }
                }

                foreach (string featureName in moduleFeatures)
                {
                    if (featuresFromGivenModules.TryGetValue(featureName, out ExperimentalFeature feature))
                    {
                        yield return(feature);
                    }
                    else
                    {
                        yield return(new ExperimentalFeature(featureName, description: null, source: null, isEnabled: true));
                    }
                }
            }
        }
        internal UpdatableHelpInfo CreateHelpInfo(string xml, string moduleName, Guid moduleGuid, string currentCulture, string pathOverride, bool verbose)
        {
            XmlDocument document = null;

            try
            {
                document = this.CreateValidXmlDocument(xml, HelpInfoXmlNamespace, HelpInfoXmlSchema, new ValidationEventHandler(this.HelpInfoValidationHandler), true);
            }
            catch (XmlException exception)
            {
                throw new UpdatableHelpSystemException("HelpInfoXmlValidationFailure", exception.Message, ErrorCategory.InvalidData, null, exception);
            }
            string resolvedUri = pathOverride;
            string innerText   = document["HelpInfo"]["HelpContentURI"].InnerText;

            if (string.IsNullOrEmpty(pathOverride))
            {
                resolvedUri = this.ResolveUri(innerText, verbose);
            }
            XmlNodeList childNodes = document["HelpInfo"]["SupportedUICultures"].ChildNodes;

            CultureSpecificUpdatableHelp[] cultures = new CultureSpecificUpdatableHelp[childNodes.Count];
            for (int i = 0; i < childNodes.Count; i++)
            {
                cultures[i] = new CultureSpecificUpdatableHelp(new CultureInfo(childNodes[i]["UICultureName"].InnerText), new Version(childNodes[i]["UICultureVersion"].InnerText));
            }
            UpdatableHelpInfo info = new UpdatableHelpInfo(innerText, cultures);

            if (!string.IsNullOrEmpty(currentCulture))
            {
                WildcardOptions options = WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase;
                IEnumerable <WildcardPattern> patterns = SessionStateUtilities.CreateWildcardsFromStrings(new string[] { currentCulture }, options);
                for (int j = 0; j < cultures.Length; j++)
                {
                    if (SessionStateUtilities.MatchesAnyWildcardPattern(cultures[j].Culture.Name, patterns, true))
                    {
                        info.HelpContentUriCollection.Add(new UpdatableHelpUri(moduleName, moduleGuid, cultures[j].Culture, resolvedUri));
                    }
                }
            }
            if (!string.IsNullOrEmpty(currentCulture) && (info.HelpContentUriCollection.Count == 0))
            {
                throw new UpdatableHelpSystemException("HelpCultureNotSupported", StringUtil.Format(HelpDisplayStrings.HelpCultureNotSupported, currentCulture, info.GetSupportedCultures()), ErrorCategory.InvalidOperation, null, null);
            }
            return(info);
        }
        /// <summary>
        /// Removes the tracelisteners from the specified trace sources.
        /// </summary>
        internal static void RemoveListenersByName(
            Collection <PSTraceSource> matchingSources,
            string[] listenerNames,
            bool fileListenersOnly)
        {
            Collection <WildcardPattern> listenerMatcher =
                SessionStateUtilities.CreateWildcardsFromStrings(
                    listenerNames,
                    WildcardOptions.IgnoreCase);

            // Loop through all the matching sources and remove the matching listeners

            foreach (PSTraceSource source in matchingSources)
            {
                // Get the indexes of the listeners that need to be removed.
                // This is done because we cannot remove the listeners while
                // we are enumerating them.

                for (int index = source.Listeners.Count - 1; index >= 0; --index)
                {
                    TraceListener listenerToRemove = source.Listeners[index];

                    if (fileListenersOnly && !(listenerToRemove is TextWriterTraceListener))
                    {
                        // Since we only want to remove file listeners, skip any that
                        // aren't file listeners
                        continue;
                    }

                    // Now match the names

                    if (SessionStateUtilities.MatchesAnyWildcardPattern(
                            listenerToRemove.Name,
                            listenerMatcher,
                            true))
                    {
                        listenerToRemove.Flush();
                        listenerToRemove.Dispose();
                        source.Listeners.RemoveAt(index);
                    }
                }
            }
        }
Exemple #6
0
        /// <summary>
        /// Returns a list of verbs.
        /// </summary>
        protected override void ProcessRecord()
        {
            Type[] verbTypes = new Type[] { typeof(VerbsCommon), typeof(VerbsCommunications), typeof(VerbsData),
                                            typeof(VerbsDiagnostic), typeof(VerbsLifecycle), typeof(VerbsOther), typeof(VerbsSecurity) };

            Collection <WildcardPattern> matchingVerbs = SessionStateUtilities.CreateWildcardsFromStrings(
                this.Verb,
                WildcardOptions.IgnoreCase
                );

            foreach (Type type in verbTypes)
            {
                string groupName = type.Name.Substring(5);
                if (this.Group != null)
                {
                    if (!SessionStateUtilities.CollectionContainsValue(this.Group, groupName, StringComparer.OrdinalIgnoreCase))
                    {
                        continue;
                    }
                }

                foreach (FieldInfo field in type.GetFields())
                {
                    if (field.IsLiteral)
                    {
                        if (this.Verb != null)
                        {
                            if (!SessionStateUtilities.MatchesAnyWildcardPattern(field.Name, matchingVerbs, false))
                            {
                                continue;
                            }
                        }

                        VerbInfo verb = new VerbInfo();
                        verb.Verb        = field.Name;
                        verb.AliasPrefix = VerbAliasPrefixes.GetVerbAliasPrefix(field.Name);
                        verb.Group       = groupName;
                        verb.Description = VerbDescriptions.GetVerbDescription(field.Name);
                        WriteObject(verb);
                    }
                }
            }
        }
        private bool IsNounVerbMatch(CommandInfo command)
        {
            string verb;
            string noun;
            bool   flag = false;

            if (this.verbPatterns == null)
            {
                this.verbPatterns = SessionStateUtilities.CreateWildcardsFromStrings(this.Verb, WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase);
            }
            if (this.nounPatterns == null)
            {
                this.nounPatterns = SessionStateUtilities.CreateWildcardsFromStrings(this.Noun, WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase);
            }
            if (!string.IsNullOrEmpty(command.ModuleName))
            {
                if (!SessionStateUtilities.MatchesAnyWildcardPattern(command.ModuleName, this._modulePatterns, true))
                {
                    return(flag);
                }
            }
            else if (this._modulePatterns.Count > 0)
            {
                return(flag);
            }
            CmdletInfo info = command as CmdletInfo;

            if (info != null)
            {
                verb = info.Verb;
                noun = info.Noun;
            }
            else if (!CmdletInfo.SplitCmdletName(command.Name, out verb, out noun))
            {
                return(flag);
            }
            if (SessionStateUtilities.MatchesAnyWildcardPattern(verb, this.verbPatterns, true) && SessionStateUtilities.MatchesAnyWildcardPattern(noun, this.nounPatterns, true))
            {
                flag = true;
            }
            return(flag);
        }
Exemple #8
0
        /// <summary>
        /// Get available experimental features based on the specified name patterns.
        /// </summary>
        internal IEnumerable <ExperimentalFeature> GetAvailableExperimentalFeatures(IEnumerable <WildcardPattern> namePatterns)
        {
            foreach (ExperimentalFeature feature in ExperimentalFeature.EngineExperimentalFeatures)
            {
                if (SessionStateUtilities.MatchesAnyWildcardPattern(feature.Name, namePatterns, defaultValue: true))
                {
                    yield return(feature);
                }
            }

            foreach (string moduleFile in GetValidModuleFiles(moduleNamesToFind: null))
            {
                ExperimentalFeature[] features = ModuleIntrinsics.GetExperimentalFeature(moduleFile);
                foreach (var feature in features)
                {
                    if (SessionStateUtilities.MatchesAnyWildcardPattern(feature.Name, namePatterns, defaultValue: true))
                    {
                        yield return(feature);
                    }
                }
            }
        }
Exemple #9
0
        private void WriteMatches(string value, string parametersetname)
        {
            // First get the alias table (from the proper scope if necessary)
            IDictionary <string, AliasInfo> aliasTable = null;

            // get the command origin
            CommandOrigin origin        = MyInvocation.CommandOrigin;
            string        displayString = "name";

            if (!string.IsNullOrEmpty(Scope))
            {
                // This can throw PSArgumentException and PSArgumentOutOfRangeException
                // but just let them go as this is terminal for the pipeline and the
                // exceptions are already properly adorned with an ErrorRecord.

                aliasTable = SessionState.Internal.GetAliasTableAtScope(Scope);
            }
            else
            {
                aliasTable = SessionState.Internal.GetAliasTable();
            }

            bool            matchfound       = false;
            bool            ContainsWildcard = WildcardPattern.ContainsWildcardCharacters(value);
            WildcardPattern wcPattern        = WildcardPattern.Get(value, WildcardOptions.IgnoreCase);

            // excluding patter for Default paramset.
            Collection <WildcardPattern> excludePatterns =
                SessionStateUtilities.CreateWildcardsFromStrings(
                    _excludes,
                    WildcardOptions.IgnoreCase);

            List <AliasInfo> results = new List <AliasInfo>();

            foreach (KeyValuePair <string, AliasInfo> tableEntry in aliasTable)
            {
                if (parametersetname.Equals("Definition", StringComparison.OrdinalIgnoreCase))
                {
                    displayString = "definition";
                    if (!wcPattern.IsMatch(tableEntry.Value.Definition))
                    {
                        continue;
                    }

                    if (SessionStateUtilities.MatchesAnyWildcardPattern(tableEntry.Value.Definition, excludePatterns, false))
                    {
                        continue;
                    }
                }
                else
                {
                    if (!wcPattern.IsMatch(tableEntry.Key))
                    {
                        continue;
                    }
                    // excludes pattern
                    if (SessionStateUtilities.MatchesAnyWildcardPattern(tableEntry.Key, excludePatterns, false))
                    {
                        continue;
                    }
                }

                if (ContainsWildcard)
                {
                    // Only write the command if it is visible to the requestor
                    if (SessionState.IsVisible(origin, tableEntry.Value))
                    {
                        matchfound = true;
                        results.Add(tableEntry.Value);
                    }
                }
                else
                {
                    // For specifically named elements, generate an error for elements that aren't visible...
                    try
                    {
                        SessionState.ThrowIfNotVisible(origin, tableEntry.Value);
                        results.Add(tableEntry.Value);
                        matchfound = true;
                    }
                    catch (SessionStateException sessionStateException)
                    {
                        WriteError(
                            new ErrorRecord(
                                sessionStateException.ErrorRecord,
                                sessionStateException));
                        // Even though it resulted in an error, a result was found
                        // so we don't want to generate the nothing found error
                        // at the end...
                        matchfound = true;
                        continue;
                    }
                }
            }

            results.Sort(
                delegate(AliasInfo left, AliasInfo right)
            {
                return(StringComparer.CurrentCultureIgnoreCase.Compare(left.Name, right.Name));
            });
            foreach (AliasInfo alias in results)
            {
                this.WriteObject(alias);
            }

            if (!matchfound && !ContainsWildcard && (excludePatterns == null || excludePatterns.Count == 0))
            {
                // Need to write an error if the user tries to get an alias
                // tat doesn't exist and they are not globbing.

                ItemNotFoundException itemNotFound = new ItemNotFoundException(StringUtil.Format(AliasCommandStrings.NoAliasFound, displayString, value));
                ErrorRecord           er           = new ErrorRecord(itemNotFound, "ItemNotFoundException", ErrorCategory.ObjectNotFound, value);
                WriteError(er);
            }
        }
Exemple #10
0
 private bool IsTypeNameMatchingParameters(string name)
 {
     return(SessionStateUtilities.MatchesAnyWildcardPattern(name, this.formatTypeNamePatterns, false));
 }
Exemple #11
0
        private void WriteMatches(string value, string parametersetname)
        {
            IDictionary <string, AliasInfo> aliasTableAtScope = null;
            CommandOrigin commandOrigin = base.MyInvocation.CommandOrigin;
            string        str           = "name";

            if (!string.IsNullOrEmpty(this.scope))
            {
                aliasTableAtScope = base.SessionState.Internal.GetAliasTableAtScope(this.scope);
            }
            else
            {
                aliasTableAtScope = base.SessionState.Internal.GetAliasTable();
            }
            bool            flag    = false;
            bool            flag2   = WildcardPattern.ContainsWildcardCharacters(value);
            WildcardPattern pattern = new WildcardPattern(value, WildcardOptions.IgnoreCase);
            Collection <WildcardPattern> patterns = SessionStateUtilities.CreateWildcardsFromStrings(this.excludes, WildcardOptions.IgnoreCase);
            List <AliasInfo>             list     = new List <AliasInfo>();

            foreach (KeyValuePair <string, AliasInfo> pair in aliasTableAtScope)
            {
                if (parametersetname.Equals("Definition", StringComparison.OrdinalIgnoreCase))
                {
                    str = "definition";
                    if (pattern.IsMatch(pair.Value.Definition) && !SessionStateUtilities.MatchesAnyWildcardPattern(pair.Value.Definition, patterns, false))
                    {
                        goto Label_00EE;
                    }
                    continue;
                }
                if (!pattern.IsMatch(pair.Key) || SessionStateUtilities.MatchesAnyWildcardPattern(pair.Key, patterns, false))
                {
                    continue;
                }
Label_00EE:
                if (flag2)
                {
                    if (SessionState.IsVisible(commandOrigin, (CommandInfo)pair.Value))
                    {
                        flag = true;
                        list.Add(pair.Value);
                    }
                }
                else
                {
                    try
                    {
                        SessionState.ThrowIfNotVisible(commandOrigin, pair.Value);
                        list.Add(pair.Value);
                        flag = true;
                    }
                    catch (SessionStateException exception)
                    {
                        base.WriteError(new ErrorRecord(exception.ErrorRecord, exception));
                        flag = true;
                    }
                }
            }
            list.Sort((Comparison <AliasInfo>)((left, right) => StringComparer.CurrentCultureIgnoreCase.Compare(left.Name, right.Name)));
            foreach (AliasInfo info in list)
            {
                base.WriteObject(info);
            }
            if ((!flag && !flag2) && ((patterns == null) || (patterns.Count == 0)))
            {
                ItemNotFoundException exception2  = new ItemNotFoundException(StringUtil.Format(AliasCommandStrings.NoAliasFound, str, value));
                ErrorRecord           errorRecord = new ErrorRecord(exception2, "ItemNotFoundException", ErrorCategory.ObjectNotFound, value);
                base.WriteError(errorRecord);
            }
        }
        private bool IsCommandMatch(ref CommandInfo current)
        {
            bool flag = false;

            if (!this.IsDuplicate(current))
            {
                if ((current.CommandType & this.CommandType) != 0)
                {
                    flag = true;
                }
                if ((current.CommandType == CommandTypes.Cmdlet) || (((this.verbs.Length > 0) || (this.nouns.Length > 0)) && (((current.CommandType == CommandTypes.Function) || (current.CommandType == CommandTypes.Filter)) || ((current.CommandType == CommandTypes.Workflow) || (current.CommandType == CommandTypes.Alias)))))
                {
                    if (!this.IsNounVerbMatch(current))
                    {
                        flag = false;
                    }
                }
                else if (((this._modulePatterns != null) && (this._modulePatterns.Count > 0)) && !SessionStateUtilities.MatchesAnyWildcardPattern(current.ModuleName, this._modulePatterns, true))
                {
                    flag = false;
                }
                if (flag)
                {
                    if (this.ArgumentList != null)
                    {
                        AliasInfo info = current as AliasInfo;
                        if (info != null)
                        {
                            current = info.ResolvedCommand;
                            if (current == null)
                            {
                                return(false);
                            }
                        }
                        else if (!(current is CmdletInfo) && !(current is IScriptCommandInfo))
                        {
                            base.ThrowTerminatingError(new ErrorRecord(PSTraceSource.NewArgumentException("ArgumentList", "DiscoveryExceptions", "CommandArgsOnlyForSingleCmdlet", new object[0]), "CommandArgsOnlyForSingleCmdlet", ErrorCategory.InvalidArgument, current));
                        }
                    }
                    bool implementsDynamicParameters = false;
                    try
                    {
                        implementsDynamicParameters = current.ImplementsDynamicParameters;
                    }
                    catch (PSSecurityException)
                    {
                    }
                    catch (RuntimeException)
                    {
                    }
                    if (!implementsDynamicParameters)
                    {
                        return(flag);
                    }
                    try
                    {
                        CommandInfo info2 = current.CreateGetCommandCopy(this.ArgumentList);
                        if (this.ArgumentList != null)
                        {
                            ReadOnlyCollection <CommandParameterSetInfo> parameterSets = info2.ParameterSets;
                        }
                        current = info2;
                    }
                    catch (MetadataException exception)
                    {
                        base.WriteError(new ErrorRecord(exception, "GetCommandMetadataError", ErrorCategory.MetadataError, current));
                    }
                    catch (ParameterBindingException exception2)
                    {
                        if (!exception2.ErrorRecord.FullyQualifiedErrorId.StartsWith("GetDynamicParametersException", StringComparison.Ordinal))
                        {
                            throw;
                        }
                    }
                }
            }
            return(flag);
        }
        private IEnumerable <CommandInfo> GetMatchingCommandsFromModules(string commandName)
        {
            WildcardPattern iteratorVariable0 = new WildcardPattern(commandName, WildcardOptions.IgnoreCase);

            for (int i = this.Context.EngineSessionState.ModuleTableKeys.Count - 1; i >= 0; i--)
            {
                PSModuleInfo iteratorVariable2 = null;
                if ((this.Context.EngineSessionState.ModuleTable.TryGetValue(this.Context.EngineSessionState.ModuleTableKeys[i], out iteratorVariable2) && SessionStateUtilities.MatchesAnyWildcardPattern(iteratorVariable2.Name, this._modulePatterns, true)) && (iteratorVariable2.SessionState != null))
                {
                    if ((this.CommandType & (CommandTypes.Filter | CommandTypes.Function)) != 0)
                    {
                        IDictionaryEnumerator enumerator = iteratorVariable2.SessionState.Internal.GetFunctionTable().GetEnumerator();
                        while (enumerator.MoveNext())
                        {
                            DictionaryEntry current           = (DictionaryEntry)enumerator.Current;
                            FunctionInfo    iteratorVariable4 = (FunctionInfo)current.Value;
                            if ((iteratorVariable0.IsMatch((string)current.Key) && iteratorVariable4.IsImported) && iteratorVariable4.Module.Path.Equals(iteratorVariable2.Path, StringComparison.OrdinalIgnoreCase))
                            {
                                yield return((CommandInfo)current.Value);
                            }
                        }
                    }
                    if ((this.CommandType & CommandTypes.Alias) != 0)
                    {
                        foreach (KeyValuePair <string, AliasInfo> iteratorVariable5 in iteratorVariable2.SessionState.Internal.GetAliasTable())
                        {
                            if ((!iteratorVariable0.IsMatch(iteratorVariable5.Key) || !iteratorVariable5.Value.IsImported) || !iteratorVariable5.Value.Module.Path.Equals(iteratorVariable2.Path, StringComparison.OrdinalIgnoreCase))
                            {
                                continue;
                            }
                            yield return(iteratorVariable5.Value);
                        }
                    }
                }
            }
        }
Exemple #14
0
        internal List <PSVariable> GetMatchingVariables(string name, string lookupScope, out bool wasFiltered, bool quiet)
        {
            wasFiltered = false;
            List <PSVariable> list = new List <PSVariable>();

            if (string.IsNullOrEmpty(name))
            {
                name = "*";
            }
            bool            flag    = WildcardPattern.ContainsWildcardCharacters(name);
            WildcardPattern pattern = new WildcardPattern(name, WildcardOptions.IgnoreCase);
            Collection <WildcardPattern> patterns    = SessionStateUtilities.CreateWildcardsFromStrings(this.include, WildcardOptions.IgnoreCase);
            Collection <WildcardPattern> collection2 = SessionStateUtilities.CreateWildcardsFromStrings(this.exclude, WildcardOptions.IgnoreCase);

            if (!flag)
            {
                bool flag2 = SessionStateUtilities.MatchesAnyWildcardPattern(name, patterns, true);
                bool flag3 = SessionStateUtilities.MatchesAnyWildcardPattern(name, collection2, false);
                if (!flag2 || flag3)
                {
                    wasFiltered = true;
                    return(list);
                }
            }
            IDictionary <string, PSVariable> variableTable = null;

            if (string.IsNullOrEmpty(lookupScope))
            {
                variableTable = base.SessionState.Internal.GetVariableTable();
            }
            else
            {
                variableTable = base.SessionState.Internal.GetVariableTableAtScope(lookupScope);
            }
            CommandOrigin commandOrigin = base.MyInvocation.CommandOrigin;

            foreach (KeyValuePair <string, PSVariable> pair in variableTable)
            {
                bool flag4 = pattern.IsMatch(pair.Key);
                bool flag5 = SessionStateUtilities.MatchesAnyWildcardPattern(pair.Key, patterns, true);
                bool flag6 = SessionStateUtilities.MatchesAnyWildcardPattern(pair.Key, collection2, false);
                if (flag4)
                {
                    if (flag5 && !flag6)
                    {
                        if (!SessionState.IsVisible(commandOrigin, pair.Value))
                        {
                            if (quiet || flag)
                            {
                                wasFiltered = true;
                                continue;
                            }
                            try
                            {
                                SessionState.ThrowIfNotVisible(commandOrigin, pair.Value);
                            }
                            catch (SessionStateException exception)
                            {
                                base.WriteError(new ErrorRecord(exception.ErrorRecord, exception));
                                wasFiltered = true;
                                continue;
                            }
                        }
                        list.Add(pair.Value);
                    }
                    else
                    {
                        wasFiltered = true;
                    }
                }
                else if (flag)
                {
                    wasFiltered = true;
                }
            }
            return(list);
        }
        /// <summary>
        /// Gets a list of modules from the given pattern
        /// </summary>
        /// <param name="context">Execution context.</param>
        /// <param name="pattern">Pattern to search.</param>
        /// <param name="fullyQualifiedName">Module Specification.</param>
        /// <param name="noErrors">Do not generate errors for modules without HelpInfoUri.</param>
        /// <returns>A list of modules.</returns>
        private Dictionary <Tuple <string, Version>, UpdatableHelpModuleInfo> GetModuleInfo(ExecutionContext context, string pattern, ModuleSpecification fullyQualifiedName, bool noErrors)
        {
            List <PSModuleInfo> modules = null;
            string moduleNamePattern    = null;

            if (pattern != null)
            {
                moduleNamePattern = pattern;
                modules           = Utils.GetModules(pattern, context);
            }
            else if (fullyQualifiedName != null)
            {
                moduleNamePattern = fullyQualifiedName.Name;
                modules           = Utils.GetModules(fullyQualifiedName, context);
            }

            var helpModules = new Dictionary <Tuple <string, Version>, UpdatableHelpModuleInfo>();

            if (modules != null)
            {
                foreach (PSModuleInfo module in modules)
                {
                    ProcessSingleModuleObject(module, context, helpModules, noErrors);
                }
            }

            // Match wildcards
            WildcardOptions wildcardOptions           = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant;
            IEnumerable <WildcardPattern> patternList = SessionStateUtilities.CreateWildcardsFromStrings(new string[1] {
                moduleNamePattern
            }, wildcardOptions);

            foreach (KeyValuePair <string, string> name in s_metadataCache)
            {
                if (SessionStateUtilities.MatchesAnyWildcardPattern(name.Key, patternList, true))
                {
                    // For core snapin, there are no GUIDs. So, we need to construct the HelpInfo slightly differently
                    if (!name.Key.Equals(InitialSessionState.CoreSnapin, StringComparison.OrdinalIgnoreCase))
                    {
                        var keyTuple = new Tuple <string, Version>(name.Key, new Version("1.0"));
                        if (!helpModules.ContainsKey(keyTuple))
                        {
                            List <PSModuleInfo> availableModules = Utils.GetModules(name.Key, context);
                            if (availableModules != null)
                            {
                                foreach (PSModuleInfo module in availableModules)
                                {
                                    keyTuple = new Tuple <string, Version>(module.Name, module.Version);
                                    if (!helpModules.ContainsKey(keyTuple))
                                    {
                                        WriteDebug(StringUtil.Format("Found engine module: {0}, {1}.", module.Name, module.Guid));

                                        helpModules.Add(keyTuple, new UpdatableHelpModuleInfo(module.Name,
                                                                                              module.Guid, Utils.GetApplicationBase(context.ShellID), s_metadataCache[module.Name]));
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        var keyTuple2 = new Tuple <string, Version>(name.Key, new Version("1.0"));
                        if (!helpModules.ContainsKey(keyTuple2))
                        {
                            helpModules.Add(keyTuple2,
                                            new UpdatableHelpModuleInfo(name.Key, Guid.Empty,
                                                                        Utils.GetApplicationBase(context.ShellID),
                                                                        name.Value));
                        }
                    }
                }
            }

            return(helpModules);
        }
        private Dictionary <string, UpdatableHelpModuleInfo> GetModuleInfo(System.Management.Automation.ExecutionContext context, string pattern, bool loaded, bool noErrors)
        {
            List <PSModuleInfo> modules = context.Modules.GetModules(new string[] { pattern }, false);
            Dictionary <string, UpdatableHelpModuleInfo> dictionary = new Dictionary <string, UpdatableHelpModuleInfo>();

            if (modules.Count != 0)
            {
                base.WriteDebug(StringUtil.Format("Found {0} loaded modules.", modules.Count));
                foreach (PSModuleInfo info in modules)
                {
                    if (InitialSessionState.IsEngineModule(info.Name) && !InitialSessionState.IsNestedEngineModule(info.Name))
                    {
                        base.WriteDebug(StringUtil.Format("Found engine module: {0}, {1}.", info.Name, info.Guid));
                        if (!dictionary.ContainsKey(info.Name))
                        {
                            dictionary.Add(info.Name, new UpdatableHelpModuleInfo(info.Name, info.Guid, Utils.GetApplicationBase(context.ShellID), metadataCache[info.Name]));
                        }
                    }
                    else if (!InitialSessionState.IsNestedEngineModule(info.Name))
                    {
                        if (string.IsNullOrEmpty(info.HelpInfoUri))
                        {
                            if (!noErrors)
                            {
                                this.ProcessException(info.Name, null, new UpdatableHelpSystemException("HelpInfoUriNotFound", StringUtil.Format(HelpDisplayStrings.HelpInfoUriNotFound, new object[0]), ErrorCategory.NotSpecified, new Uri("HelpInfoUri", UriKind.Relative), null));
                            }
                        }
                        else if (!info.HelpInfoUri.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
                        {
                            if (!noErrors)
                            {
                                this.ProcessException(info.Name, null, new UpdatableHelpSystemException("InvalidHelpInfoUriFormat", StringUtil.Format(HelpDisplayStrings.InvalidHelpInfoUriFormat, info.HelpInfoUri), ErrorCategory.NotSpecified, new Uri("HelpInfoUri", UriKind.Relative), null));
                            }
                        }
                        else if (!dictionary.ContainsKey(info.Name))
                        {
                            dictionary.Add(info.Name, new UpdatableHelpModuleInfo(info.Name, info.Guid, info.ModuleBase, info.HelpInfoUri));
                        }
                    }
                }
            }
            WildcardOptions options = WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase;
            IEnumerable <WildcardPattern> patterns = SessionStateUtilities.CreateWildcardsFromStrings(new string[] { pattern }, options);

            if (!loaded)
            {
                Collection <PSObject>     collection  = base.InvokeCommand.InvokeScript("Get-Module -ListAvailable");
                Collection <PSModuleInfo> collection2 = new Collection <PSModuleInfo>();
                if (collection != null)
                {
                    foreach (PSObject obj2 in collection)
                    {
                        try
                        {
                            collection2.Add((PSModuleInfo)LanguagePrimitives.ConvertTo(obj2, typeof(PSModuleInfo), CultureInfo.InvariantCulture));
                        }
                        catch (PSInvalidCastException)
                        {
                        }
                    }
                }
                base.WriteDebug(StringUtil.Format("Found {0} available (Get-Module -ListAvailable) modules.", collection2.Count));
                foreach (PSModuleInfo info2 in collection2)
                {
                    if (SessionStateUtilities.MatchesAnyWildcardPattern(info2.Name, patterns, true))
                    {
                        if (InitialSessionState.IsEngineModule(info2.Name) && !InitialSessionState.IsNestedEngineModule(info2.Name))
                        {
                            base.WriteDebug(StringUtil.Format("Found engine module: {0}, {1}.", info2.Name, info2.Guid));
                            if (!dictionary.ContainsKey(info2.Name))
                            {
                                dictionary.Add(info2.Name, new UpdatableHelpModuleInfo(info2.Name, info2.Guid, Utils.GetApplicationBase(context.ShellID), metadataCache[info2.Name]));
                            }
                        }
                        else if (!InitialSessionState.IsNestedEngineModule(info2.Name))
                        {
                            if (string.IsNullOrEmpty(info2.HelpInfoUri))
                            {
                                if (!noErrors)
                                {
                                    this.ProcessException(info2.Name, null, new UpdatableHelpSystemException("HelpInfoUriNotFound", StringUtil.Format(HelpDisplayStrings.HelpInfoUriNotFound, new object[0]), ErrorCategory.NotSpecified, new Uri("HelpInfoUri", UriKind.Relative), null));
                                }
                            }
                            else if (!info2.HelpInfoUri.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
                            {
                                if (!noErrors)
                                {
                                    this.ProcessException(info2.Name, null, new UpdatableHelpSystemException("InvalidHelpInfoUriFormat", StringUtil.Format(HelpDisplayStrings.InvalidHelpInfoUriFormat, info2.HelpInfoUri), ErrorCategory.NotSpecified, new Uri("HelpInfoUri", UriKind.Relative), null));
                                }
                            }
                            else if (!dictionary.ContainsKey(info2.Name))
                            {
                                dictionary.Add(info2.Name, new UpdatableHelpModuleInfo(info2.Name, info2.Guid, info2.ModuleBase, info2.HelpInfoUri));
                            }
                        }
                    }
                }
            }
            foreach (KeyValuePair <string, string> pair in metadataCache)
            {
                if (SessionStateUtilities.MatchesAnyWildcardPattern(pair.Key, patterns, true))
                {
                    if (!pair.Key.Equals(InitialSessionState.CoreSnapin, StringComparison.OrdinalIgnoreCase))
                    {
                        Collection <PSObject>     collection3 = base.InvokeCommand.InvokeScript(StringUtil.Format("Get-Module {0} -ListAvailable", pair.Key));
                        Collection <PSModuleInfo> collection4 = new Collection <PSModuleInfo>();
                        if (collection3 != null)
                        {
                            foreach (PSObject obj3 in collection3)
                            {
                                try
                                {
                                    collection4.Add((PSModuleInfo)LanguagePrimitives.ConvertTo(obj3, typeof(PSModuleInfo), CultureInfo.InvariantCulture));
                                }
                                catch (PSInvalidCastException)
                                {
                                }
                            }
                        }
                        foreach (PSModuleInfo info3 in collection4)
                        {
                            if (!dictionary.ContainsKey(info3.Name))
                            {
                                base.WriteDebug(StringUtil.Format("Found engine module: {0}, {1}.", info3.Name, info3.Guid));
                                dictionary.Add(pair.Key, new UpdatableHelpModuleInfo(info3.Name, info3.Guid, Utils.GetApplicationBase(context.ShellID), metadataCache[info3.Name]));
                            }
                        }
                    }
                    else if (!dictionary.ContainsKey(pair.Key))
                    {
                        dictionary.Add(pair.Key, new UpdatableHelpModuleInfo(pair.Key, Guid.Empty, Utils.GetApplicationBase(context.ShellID), pair.Value));
                    }
                }
            }
            return(dictionary);
        }
Exemple #17
0
        /// <summary>
        /// Gets the matching variable for the specified name, using the
        /// Include, Exclude, and Scope parameters defined in the base class.
        /// </summary>
        /// <param name="name">
        /// The name or pattern of the variables to retrieve.
        /// </param>
        /// <param name="lookupScope">
        /// The scope to do the lookup in. If null or empty the normal scoping rules apply.
        /// </param>
        /// <param name="wasFiltered">
        /// True is returned if a variable exists of the given name but was filtered
        /// out via globbing, include, or exclude.
        /// </param>
        /// <param name="quiet">
        /// If true, don't report errors when trying to access private variables.
        /// </param>
        /// <returns>
        /// A collection of the variables matching the name, include, and exclude
        /// pattern in the specified scope.
        /// </returns>
        internal List <PSVariable> GetMatchingVariables(string name, string lookupScope, out bool wasFiltered, bool quiet)
        {
            wasFiltered = false;

            List <PSVariable> result = new List <PSVariable>();

            if (string.IsNullOrEmpty(name))
            {
                name = "*";
            }

            bool nameContainsWildcard = WildcardPattern.ContainsWildcardCharacters(name);

            // Now create the filters

            WildcardPattern nameFilter =
                WildcardPattern.Get(
                    name,
                    WildcardOptions.IgnoreCase);

            Collection <WildcardPattern> includeFilters =
                SessionStateUtilities.CreateWildcardsFromStrings(
                    _include,
                    WildcardOptions.IgnoreCase);

            Collection <WildcardPattern> excludeFilters =
                SessionStateUtilities.CreateWildcardsFromStrings(
                    _exclude,
                    WildcardOptions.IgnoreCase);

            if (!nameContainsWildcard)
            {
                // Filter the name here against the include and exclude so that
                // we can report if the name was filtered vs. there being no
                // variable existing of that name.

                bool isIncludeMatch =
                    SessionStateUtilities.MatchesAnyWildcardPattern(
                        name,
                        includeFilters,
                        true);

                bool isExcludeMatch =
                    SessionStateUtilities.MatchesAnyWildcardPattern(
                        name,
                        excludeFilters,
                        false);

                if (!isIncludeMatch || isExcludeMatch)
                {
                    wasFiltered = true;
                    return(result);
                }
            }

            // First get the appropriate view of the variables. If no scope
            // is specified, flatten all scopes to produce a currently active
            // view.

            IDictionary <string, PSVariable> variableTable = null;

            if (string.IsNullOrEmpty(lookupScope))
            {
                variableTable = SessionState.Internal.GetVariableTable();
            }
            else
            {
                variableTable = SessionState.Internal.GetVariableTableAtScope(lookupScope);
            }

            CommandOrigin origin = MyInvocation.CommandOrigin;

            foreach (KeyValuePair <string, PSVariable> entry in variableTable)
            {
                bool isNameMatch    = nameFilter.IsMatch(entry.Key);
                bool isIncludeMatch =
                    SessionStateUtilities.MatchesAnyWildcardPattern(
                        entry.Key,
                        includeFilters,
                        true);

                bool isExcludeMatch =
                    SessionStateUtilities.MatchesAnyWildcardPattern(
                        entry.Key,
                        excludeFilters,
                        false);

                if (isNameMatch)
                {
                    if (isIncludeMatch && !isExcludeMatch)
                    {
                        // See if the variable is visible
                        if (!SessionState.IsVisible(origin, entry.Value))
                        {
                            // In quiet mode, don't report private variable accesses unless they are specific matches...
                            if (quiet || nameContainsWildcard)
                            {
                                wasFiltered = true;
                                continue;
                            }
                            else
                            {
                                // Generate an error for elements that aren't visible...
                                try
                                {
                                    SessionState.ThrowIfNotVisible(origin, entry.Value);
                                }
                                catch (SessionStateException sessionStateException)
                                {
                                    WriteError(
                                        new ErrorRecord(
                                            sessionStateException.ErrorRecord,
                                            sessionStateException));
                                    // Only report the error once...
                                    wasFiltered = true;
                                    continue;
                                }
                            }
                        }

                        result.Add(entry.Value);
                    }
                    else
                    {
                        wasFiltered = true;
                    }
                }
                else
                {
                    if (nameContainsWildcard)
                    {
                        wasFiltered = true;
                    }
                }
            }

            return(result);
        }
        internal static void RemoveListenersByName(Collection <PSTraceSource> matchingSources, string[] listenerNames, bool fileListenersOnly)
        {
            Collection <WildcardPattern> patterns = SessionStateUtilities.CreateWildcardsFromStrings(listenerNames, WildcardOptions.IgnoreCase);

            foreach (PSTraceSource source in matchingSources)
            {
                for (int i = source.Listeners.Count - 1; i >= 0; i--)
                {
                    TraceListener listener = source.Listeners[i];
                    if ((!fileListenersOnly || (listener is TextWriterTraceListener)) && SessionStateUtilities.MatchesAnyWildcardPattern(listener.Name, patterns, true))
                    {
                        listener.Flush();
                        listener.Close();
                        source.Listeners.RemoveAt(i);
                    }
                }
            }
        }