Пример #1
0
 protected override void EndProcessing()
 {
     if ((this._numberRemoved == 0) && !base.MyInvocation.BoundParameters.ContainsKey("WhatIf"))
     {
         bool flag  = true;
         bool flag2 = true;
         foreach (string str in this._name)
         {
             if (!InitialSessionState.IsEngineModule(str))
             {
                 flag2 = false;
             }
             if (!WildcardPattern.ContainsWildcardCharacters(str))
             {
                 flag = false;
             }
         }
         if (!flag2 && (!flag || (this._moduleInfo.Length != 0)))
         {
             InvalidOperationException exception = new InvalidOperationException(StringUtil.Format(Modules.NoModulesRemoved, new object[0]));
             ErrorRecord errorRecord             = new ErrorRecord(exception, "Modules_NoModulesRemoved", ErrorCategory.ResourceUnavailable, null);
             base.WriteError(errorRecord);
         }
     }
 }
        /// <summary>
        /// Reports an error if no modules were removed...
        /// </summary>
        protected override void EndProcessing()
        {
            // Write an error record if specific modules were to be removed.
            // By specific, we mean either a name sting with no wildcards or
            // or a PSModuleInfo object. If the removal request only includes patterns
            // then we won't write the error.

            if (_numberRemoved == 0 && !MyInvocation.BoundParameters.ContainsKey("WhatIf"))
            {
                bool hasWildcards   = true;
                bool isEngineModule = true;
                foreach (string n in _name)
                {
                    if (!InitialSessionState.IsEngineModule(n))
                    {
                        isEngineModule = false;
                    }

                    if (!WildcardPattern.ContainsWildcardCharacters(n))
                    {
                        hasWildcards = false;
                    }
                }

                if (FullyQualifiedName != null && (FullyQualifiedName.Any(static moduleSpec => !InitialSessionState.IsEngineModule(moduleSpec.Name))))
Пример #3
0
        private void ProcessSingleModuleObject(PSModuleInfo module, ExecutionContext context, Dictionary <Tuple <string, Version>, UpdatableHelpModuleInfo> helpModules, bool noErrors)
        {
            if (InitialSessionState.IsEngineModule(module.Name) && !InitialSessionState.IsNestedEngineModule(module.Name))
            {
                WriteDebug(StringUtil.Format("Found engine module: {0}, {1}.", module.Name, module.Guid));

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

                return;
            }
            else if (InitialSessionState.IsNestedEngineModule(module.Name))
            {
                return;
            }

            if (string.IsNullOrEmpty(module.HelpInfoUri))
            {
                if (!noErrors)
                {
                    ProcessException(module.Name, null, new UpdatableHelpSystemException(
                                         "HelpInfoUriNotFound", StringUtil.Format(HelpDisplayStrings.HelpInfoUriNotFound),
                                         ErrorCategory.NotSpecified, new Uri("HelpInfoUri", UriKind.Relative), null));
                }

                return;
            }

            if (!(module.HelpInfoUri.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || module.HelpInfoUri.StartsWith("https://", StringComparison.OrdinalIgnoreCase)))
            {
                if (!noErrors)
                {
                    ProcessException(module.Name, null, new UpdatableHelpSystemException(
                                         "InvalidHelpInfoUriFormat", StringUtil.Format(HelpDisplayStrings.InvalidHelpInfoUriFormat, module.HelpInfoUri),
                                         ErrorCategory.NotSpecified, new Uri("HelpInfoUri", UriKind.Relative), null));
                }

                return;
            }

            var keyTuple2 = new Tuple <string, Version>(module.Name, module.Version);

            if (!helpModules.ContainsKey(keyTuple2))
            {
                helpModules.Add(keyTuple2, new UpdatableHelpModuleInfo(module.Name, module.Guid, module.ModuleBase, module.HelpInfoUri));
            }
        }
Пример #4
0
        private string FindHelpFile(CmdletInfo cmdletInfo)
        {
            if (cmdletInfo == null)
            {
                throw PSTraceSource.NewArgumentNullException("cmdletInfo");
            }
            string helpFile = cmdletInfo.HelpFile;

            if (string.IsNullOrEmpty(helpFile))
            {
                if ((cmdletInfo.Module != null) && InitialSessionState.IsEngineModule(cmdletInfo.Module.Name))
                {
                    return(Path.Combine(cmdletInfo.Module.ModuleBase, Thread.CurrentThread.CurrentCulture.Name, engineModuleHelpFileCache[cmdletInfo.Module.Name]));
                }
                return(helpFile);
            }
            string              file        = helpFile;
            PSSnapInInfo        pSSnapIn    = cmdletInfo.PSSnapIn;
            Collection <string> searchPaths = new Collection <string>();

            if (pSSnapIn != null)
            {
                file = Path.Combine(pSSnapIn.ApplicationBase, helpFile);
            }
            else if ((cmdletInfo.Module != null) && !string.IsNullOrEmpty(cmdletInfo.Module.Path))
            {
                file = Path.Combine(cmdletInfo.Module.ModuleBase, helpFile);
            }
            else
            {
                searchPaths.Add(base.GetDefaultShellSearchPath());
                searchPaths.Add(GetCmdletAssemblyPath(cmdletInfo));
            }
            string str3 = MUIFileSearcher.LocateFile(file, searchPaths);

            if (string.IsNullOrEmpty(str3))
            {
                tracer.WriteLine("Unable to load file {0}", new object[] { file });
            }
            return(str3);
        }
Пример #5
0
        /// <summary>
        /// Reports an error if no modules were removed...
        /// </summary>
        protected override void EndProcessing()
        {
            // Write an error record if specific modules were to be removed.
            // By specific, we mean either a name sting with no wildcards or
            // or a PSModuleInfo object. If the removal request only includes patterns
            // then we won't write the error.

            if (_numberRemoved == 0 && !MyInvocation.BoundParameters.ContainsKey("WhatIf"))
            {
                bool hasWildcards   = true;
                bool isEngineModule = true;
                foreach (string n in _name)
                {
                    if (!InitialSessionState.IsEngineModule(n))
                    {
                        isEngineModule = false;
                    }

                    if (!WildcardPattern.ContainsWildcardCharacters(n))
                    {
                        hasWildcards = false;
                    }
                }

                if (FullyQualifiedName != null && (FullyQualifiedName.Any(moduleSpec => !InitialSessionState.IsEngineModule(moduleSpec.Name))))
                {
                    isEngineModule = false;
                }

                if (!isEngineModule && (!hasWildcards || _moduleInfo.Length != 0 || (FullyQualifiedName != null && FullyQualifiedName.Length != 0)))
                {
                    string message = StringUtil.Format(Modules.NoModulesRemoved);
                    InvalidOperationException invalidOp = new InvalidOperationException(message);
                    ErrorRecord er = new ErrorRecord(invalidOp, "Modules_NoModulesRemoved",
                                                     ErrorCategory.ResourceUnavailable, null);
                    WriteError(er);
                }
            }
        }
Пример #6
0
        private int _numberRemoved = 0;  // Maintains a count of the number of modules removed...

        /// <summary>
        /// Remove the specified modules. Modules can be specified either through a ModuleInfo or a name.
        /// </summary>
        protected override void ProcessRecord()
        {
            // This dictionary has the list of modules to be removed.
            // Key - Module specified as a parameter to Remove-Module
            // Values - List of all modules that need to be removed for this key (includes all nested modules of this module)
            Dictionary <PSModuleInfo, List <PSModuleInfo> > modulesToRemove = new Dictionary <PSModuleInfo, List <PSModuleInfo> >();

            foreach (var m in Context.Modules.GetModules(_name, false))
            {
                modulesToRemove.Add(m, new List <PSModuleInfo> {
                    m
                });
            }

            if (FullyQualifiedName != null)
            {
                foreach (var m in Context.Modules.GetModules(FullyQualifiedName, false))
                {
                    modulesToRemove.Add(m, new List <PSModuleInfo> {
                        m
                    });
                }
            }

            foreach (var m in _moduleInfo)
            {
                modulesToRemove.Add(m, new List <PSModuleInfo> {
                    m
                });
            }

            // Add any of the child modules of a manifests to the list of modules to remove...
            Dictionary <PSModuleInfo, List <PSModuleInfo> > nestedModules = new Dictionary <PSModuleInfo, List <PSModuleInfo> >();

            foreach (var entry in modulesToRemove)
            {
                var module = entry.Key;
                if (module.NestedModules != null && module.NestedModules.Count > 0)
                {
                    List <PSModuleInfo> nestedModulesWithNoCircularReference = new List <PSModuleInfo>();
                    GetAllNestedModules(module, ref nestedModulesWithNoCircularReference);
                    nestedModules.Add(module, nestedModulesWithNoCircularReference);
                }
            }

            // dont add duplicates to our original modulesToRemove list..so that the
            // evaluation loop below will not duplicate in case of WriteError and WriteWarning.
            // A global list of modules to be removed is maintained for this purpose
            HashSet <PSModuleInfo> globalListOfModules = new HashSet <PSModuleInfo>(new PSModuleInfoComparer());

            if (nestedModules.Count > 0)
            {
                foreach (var entry in nestedModules)
                {
                    List <PSModuleInfo> values = null;
                    if (modulesToRemove.TryGetValue(entry.Key, out values))
                    {
                        foreach (var module in entry.Value)
                        {
                            if (!globalListOfModules.Contains(module))
                            {
                                values.Add(module);
                                globalListOfModules.Add(module);
                            }
                        }
                    }
                }
            }

            // Check the list of modules to remove and exclude those that cannot or should not be removed
            Dictionary <PSModuleInfo, List <PSModuleInfo> > actualModulesToRemove = new Dictionary <PSModuleInfo, List <PSModuleInfo> >();

            // We want to remove the modules starting from the nested modules
            // If we start from the parent module, the nested modules do not get removed and are left orphaned in the parent modules's sessionstate.
            foreach (var entry in modulesToRemove)
            {
                List <PSModuleInfo> moduleList = new List <PSModuleInfo>();
                for (int i = entry.Value.Count - 1; i >= 0; i--)
                {
                    PSModuleInfo module = entry.Value[i];
                    // See if the module is constant...
                    if (module.AccessMode == ModuleAccessMode.Constant)
                    {
                        string message = StringUtil.Format(Modules.ModuleIsConstant, module.Name);
                        InvalidOperationException moduleNotRemoved = new InvalidOperationException(message);
                        ErrorRecord er = new ErrorRecord(moduleNotRemoved, "Modules_ModuleIsConstant",
                                                         ErrorCategory.PermissionDenied, module);
                        WriteError(er);
                        continue;
                    }

                    // See if the module is readonly...
                    if (module.AccessMode == ModuleAccessMode.ReadOnly && !BaseForce)
                    {
                        string message = StringUtil.Format(Modules.ModuleIsReadOnly, module.Name);

                        if (InitialSessionState.IsConstantEngineModule(module.Name))
                        {
                            WriteWarning(message);
                        }
                        else
                        {
                            InvalidOperationException moduleNotRemoved = new InvalidOperationException(message);
                            ErrorRecord er = new ErrorRecord(moduleNotRemoved, "Modules_ModuleIsReadOnly",
                                                             ErrorCategory.PermissionDenied, module);
                            WriteError(er);
                        }
                        continue;
                    }

                    if (!ShouldProcess(StringUtil.Format(Modules.ConfirmRemoveModule, module.Name, module.Path)))
                    {
                        continue;
                    }

                    // If this module provides the current session drive, then we cannot remove it.
                    // Abort this command since we don't want to do a partial removal of a module manifest.
                    if (ModuleProvidesCurrentSessionDrive(module))
                    {
                        if (InitialSessionState.IsEngineModule(module.Name))
                        {
                            if (!BaseForce)
                            {
                                string message = StringUtil.Format(Modules.CoreModuleCannotBeRemoved, module.Name);
                                this.WriteWarning(message);
                            }
                            continue;
                        }
                        // Specify the overall module name if there is only one.
                        // Otherwise specify the particular module name.
                        string moduleName = (_name.Length == 1) ? _name[0] : module.Name;

                        PSInvalidOperationException invalidOperation =
                            PSTraceSource.NewInvalidOperationException(
                                Modules.ModuleDriveInUse,
                                moduleName);

                        throw (invalidOperation);
                    }

                    // Add module to remove list.
                    moduleList.Add(module);
                }
                actualModulesToRemove[entry.Key] = moduleList;
            }

            // Now remove the modules, first checking the RequiredModules dependencies
            Dictionary <PSModuleInfo, List <PSModuleInfo> > requiredDependencies = GetRequiredDependencies();

            foreach (var entry in actualModulesToRemove)
            {
                foreach (var module in entry.Value)
                {
                    if (!BaseForce)
                    {
                        List <PSModuleInfo> requiredBy = null;

                        if (requiredDependencies.TryGetValue(module, out requiredBy))
                        {
                            for (int i = requiredBy.Count - 1; i >= 0; i--)
                            {
                                if (actualModulesToRemove.ContainsKey(requiredBy[i]))
                                {
                                    requiredBy.RemoveAt(i);
                                }
                            }

                            if (requiredBy.Count > 0)
                            {
                                string message = StringUtil.Format(Modules.ModuleIsRequired, module.Name, requiredBy[0].Name);
                                InvalidOperationException moduleNotRemoved = new InvalidOperationException(message);
                                ErrorRecord er = new ErrorRecord(moduleNotRemoved, "Modules_ModuleIsRequired",
                                                                 ErrorCategory.PermissionDenied, module);
                                WriteError(er);
                                continue;
                            }
                        }
                    }

                    _numberRemoved++;

                    this.RemoveModule(module, entry.Key.Name);
                }
            }
        }
Пример #7
0
        /// <summary>
        /// Gets a list of matching commands.
        /// </summary>
        /// <param name="pattern">Command pattern.</param>
        /// <param name="context">Execution context.</param>
        /// <param name="commandOrigin">Command origin.</param>
        /// <param name="rediscoverImportedModules">If true, rediscovers imported modules.</param>
        /// <param name="moduleVersionRequired">Specific module version to be required.</param>
        /// <param name="useFuzzyMatching">Use fuzzy matching.</param>
        /// <param name="useAbbreviationExpansion">Use abbreviation expansion for matching.</param>
        /// <returns>Returns matching CommandInfo IEnumerable.</returns>
        internal static IEnumerable <CommandInfo> GetMatchingCommands(string pattern, ExecutionContext context, CommandOrigin commandOrigin, bool rediscoverImportedModules = false, bool moduleVersionRequired = false, bool useFuzzyMatching = false, bool useAbbreviationExpansion = false)
        {
            // Otherwise, if it had wildcards, just return the "AvailableCommand"
            // type of command info.
            WildcardPattern commandPattern = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);

            CmdletInfo cmdletInfo = context.SessionState.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\\Get-Module");
            PSModuleAutoLoadingPreference moduleAutoLoadingPreference = CommandDiscovery.GetCommandDiscoveryPreference(context, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference");

            if ((moduleAutoLoadingPreference != PSModuleAutoLoadingPreference.None) &&
                ((commandOrigin == CommandOrigin.Internal) || ((cmdletInfo != null) && (cmdletInfo.Visibility == SessionStateEntryVisibility.Public))))
            {
                foreach (string modulePath in GetDefaultAvailableModuleFiles(isForAutoDiscovery: false, context))
                {
                    // Skip modules that have already been loaded so that we don't expose private commands.
                    string moduleName                  = Path.GetFileNameWithoutExtension(modulePath);
                    List <PSModuleInfo> modules        = context.Modules.GetExactMatchModules(moduleName, all: false, exactMatch: true);
                    PSModuleInfo        tempModuleInfo = null;

                    if (modules.Count != 0)
                    {
                        // 1. We continue to the next module path if we don't want to re-discover those imported modules
                        // 2. If we want to re-discover the imported modules, but one or more commands from the module were made private,
                        //    then we don't do re-discovery
                        if (!rediscoverImportedModules || modules.Exists(module => module.ModuleHasPrivateMembers))
                        {
                            continue;
                        }

                        if (modules.Count == 1)
                        {
                            PSModuleInfo psModule = modules[0];
                            tempModuleInfo = new PSModuleInfo(psModule.Name, psModule.Path, context: null, sessionState: null);
                            tempModuleInfo.SetModuleBase(psModule.ModuleBase);

                            foreach (KeyValuePair <string, CommandInfo> entry in psModule.ExportedCommands)
                            {
                                if (commandPattern.IsMatch(entry.Value.Name) ||
                                    (useFuzzyMatching && FuzzyMatcher.IsFuzzyMatch(entry.Value.Name, pattern)) ||
                                    (useAbbreviationExpansion && string.Equals(pattern, AbbreviateName(entry.Value.Name), StringComparison.OrdinalIgnoreCase)))
                                {
                                    CommandInfo current = null;
                                    switch (entry.Value.CommandType)
                                    {
                                    case CommandTypes.Alias:
                                        current = new AliasInfo(entry.Value.Name, definition: null, context);
                                        break;

                                    case CommandTypes.Function:
                                        current = new FunctionInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                        break;

                                    case CommandTypes.Filter:
                                        current = new FilterInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                        break;

                                    case CommandTypes.Configuration:
                                        current = new ConfigurationInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                        break;

                                    case CommandTypes.Cmdlet:
                                        current = new CmdletInfo(entry.Value.Name, implementingType: null, helpFile: null, PSSnapin: null, context);
                                        break;

                                    default:
                                        Dbg.Assert(false, "cannot be hit");
                                        break;
                                    }

                                    current.Module = tempModuleInfo;
                                    yield return(current);
                                }
                            }

                            continue;
                        }
                    }

                    string moduleShortName = Path.GetFileNameWithoutExtension(modulePath);

                    IDictionary <string, CommandTypes> exportedCommands = AnalysisCache.GetExportedCommands(modulePath, testOnly: false, context);

                    if (exportedCommands == null)
                    {
                        continue;
                    }

                    tempModuleInfo = new PSModuleInfo(moduleShortName, modulePath, sessionState: null, context: null);
                    if (InitialSessionState.IsEngineModule(moduleShortName))
                    {
                        tempModuleInfo.SetModuleBase(Utils.DefaultPowerShellAppBase);
                    }

                    // moduleVersionRequired is bypassed by FullyQualifiedModule from calling method. This is the only place where guid will be involved.
                    if (moduleVersionRequired && modulePath.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase))
                    {
                        tempModuleInfo.SetVersion(ModuleIntrinsics.GetManifestModuleVersion(modulePath));
                        tempModuleInfo.SetGuid(ModuleIntrinsics.GetManifestGuid(modulePath));
                    }

                    foreach (KeyValuePair <string, CommandTypes> pair in exportedCommands)
                    {
                        string       commandName  = pair.Key;
                        CommandTypes commandTypes = pair.Value;

                        if (commandPattern.IsMatch(commandName) ||
                            (useFuzzyMatching && FuzzyMatcher.IsFuzzyMatch(commandName, pattern)) ||
                            (useAbbreviationExpansion && string.Equals(pattern, AbbreviateName(commandName), StringComparison.OrdinalIgnoreCase)))
                        {
                            bool shouldExportCommand = true;

                            // Verify that we don't already have it represented in the initial session state.
                            if ((context.InitialSessionState != null) && (commandOrigin == CommandOrigin.Runspace))
                            {
                                foreach (SessionStateCommandEntry commandEntry in context.InitialSessionState.Commands[commandName])
                                {
                                    string moduleCompareName = null;

                                    if (commandEntry.Module != null)
                                    {
                                        moduleCompareName = commandEntry.Module.Name;
                                    }
                                    else if (commandEntry.PSSnapIn != null)
                                    {
                                        moduleCompareName = commandEntry.PSSnapIn.Name;
                                    }

                                    if (string.Equals(moduleShortName, moduleCompareName, StringComparison.OrdinalIgnoreCase))
                                    {
                                        if (commandEntry.Visibility == SessionStateEntryVisibility.Private)
                                        {
                                            shouldExportCommand = false;
                                        }
                                    }
                                }
                            }

                            if (shouldExportCommand)
                            {
                                if ((commandTypes & CommandTypes.Alias) == CommandTypes.Alias)
                                {
                                    yield return(new AliasInfo(commandName, null, context)
                                    {
                                        Module = tempModuleInfo
                                    });
                                }

                                if ((commandTypes & CommandTypes.Cmdlet) == CommandTypes.Cmdlet)
                                {
                                    yield return(new CmdletInfo(commandName, implementingType: null, helpFile: null, PSSnapin: null, context: context)
                                    {
                                        Module = tempModuleInfo
                                    });
                                }

                                if ((commandTypes & CommandTypes.Function) == CommandTypes.Function)
                                {
                                    yield return(new FunctionInfo(commandName, ScriptBlock.EmptyScriptBlock, context)
                                    {
                                        Module = tempModuleInfo
                                    });
                                }

                                if ((commandTypes & CommandTypes.Configuration) == CommandTypes.Configuration)
                                {
                                    yield return(new ConfigurationInfo(commandName, ScriptBlock.EmptyScriptBlock, context)
                                    {
                                        Module = tempModuleInfo
                                    });
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #8
0
            public bool MoveNext()
            {
                try
                {
                    int num = this.__1__state;
                    if (num != 0)
                    {
                        if (num == 3)
                        {
                            this.__1__state = 2;
                            this.__m__Finally1e();
                        }
                        if (num == 7)
                        {
                            this.__1__state = 5;
                            this.__m__Finally22();
                        }
                    }
                    else
                    {
                        this.__1__state           = -1;
                        this._commandPattern_5__b = new WildcardPattern(this.pattern, WildcardOptions.IgnoreCase);
                        this._cmdletInfo_5__c     = this.context.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Get-Module");
                        aa__ = CommandDiscovery.GetCommandDiscoveryPreference(this.context, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference");
                        if ((aa__ != PSModuleAutoLoadingPreference.None) && ((this.commandOrigin == CommandOrigin.Internal) || ((this._cmdletInfo_5__c != null) && (this._cmdletInfo_5__c.Visibility == SessionStateEntryVisibility.Public))))
                        {
                            this.__7__wrap1b = ModuleUtils.GetDefaultAvailableModuleFiles(true, false, this.context).GetEnumerator();
                            this.__1__state  = 1;
                            while (this.__7__wrap1b.MoveNext())
                            {
                                this._modulePath_5__e      = this.__7__wrap1b.Current;
                                this._moduleName_5__f      = Path.GetFileNameWithoutExtension(this._modulePath_5__e);
                                this._modules_5__10        = this.context.Modules.GetExactMatchModules(this._moduleName_5__f, false, true);
                                this._tempModuleInfo_5__11 = null;
                                if (this._modules_5__10.Count != 0)
                                {
                                    if (!this.rediscoverImportedModules)
                                    {
                                        continue;
                                    }
                                    if (this._modules_5__10.Exists(new Predicate <PSModuleInfo>(ModuleUtils.GetMatchingCommands_b__8)))
                                    {
                                        continue;
                                    }
                                    if (this._modules_5__10.Count == 1)
                                    {
                                        this._psModule_5__12       = this._modules_5__10[0];
                                        this._tempModuleInfo_5__11 = new PSModuleInfo(this._psModule_5__12.Name, this._psModule_5__12.Path, null, null);
                                        this._tempModuleInfo_5__11.SetModuleBase(this._psModule_5__12.ModuleBase);
                                        this.__7__wrap1d = this._psModule_5__12.ExportedCommands.GetEnumerator();
                                        this.__1__state  = 2;
                                        while (this.__7__wrap1d.MoveNext())
                                        {
                                            this._entry_5__13 = this.__7__wrap1d.Current;
                                            if (!this._commandPattern_5__b.IsMatch(this._entry_5__13.Value.Name))
                                            {
                                                continue;
                                            }
                                            this._current_5__14 = null;
                                            switch (this._entry_5__13.Value.CommandType)
                                            {
                                            case CommandTypes.Alias:
                                                this._current_5__14 = new AliasInfo(this._entry_5__13.Value.Name, null, this.context);
                                                break;

                                            case CommandTypes.Function:
                                                this._current_5__14 = new FunctionInfo(this._entry_5__13.Value.Name, ScriptBlock.Create(""), this.context);
                                                break;

                                            case CommandTypes.Filter:
                                                this._current_5__14 = new FilterInfo(this._entry_5__13.Value.Name, ScriptBlock.Create(""), this.context);
                                                break;

                                            case CommandTypes.Cmdlet:
                                                this._current_5__14 = new CmdletInfo(this._entry_5__13.Value.Name, null, null, null, this.context);
                                                break;

                                            case CommandTypes.Workflow:
                                                this._current_5__14 = new WorkflowInfo(this._entry_5__13.Value.Name, ScriptBlock.Create(""), this.context);
                                                break;
                                            }
                                            this._current_5__14.SetModule(this._tempModuleInfo_5__11);
                                            this.__2__current = this._current_5__14;
                                            this.__1__state   = 3;
                                            return(true);

                                            this.__1__state = 2;
                                        }
                                        this.__m__Finally1e();
                                        continue;
                                    }
                                }
                                this._moduleShortName_5__15  = Path.GetFileNameWithoutExtension(this._modulePath_5__e);
                                this._exportedCommands_5__16 = AnalysisCache.GetExportedCommands(this._modulePath_5__e, false, this.context);
                                if (this._exportedCommands_5__16 != null)
                                {
                                    this._tempModuleInfo_5__11 = new PSModuleInfo(this._moduleShortName_5__15, this._modulePath_5__e, null, null);
                                    if (InitialSessionState.IsEngineModule(this._moduleShortName_5__15))
                                    {
                                        this._tempModuleInfo_5__11.SetModuleBase(Utils.GetApplicationBase(Utils.DefaultPowerShellShellID));
                                    }
                                    this.__7__wrap1f = this._exportedCommands_5__16.Keys.GetEnumerator();
                                    this.__1__state  = 4;
                                    while (this.__7__wrap1f.MoveNext())
                                    {
                                        this._exportedCommand_5__17 = this.__7__wrap1f.Current;
                                        if (this._commandPattern_5__b.IsMatch(this._exportedCommand_5__17))
                                        {
                                            this.__7__wrap21 = this._exportedCommands_5__16[this._exportedCommand_5__17].GetEnumerator();
                                            this.__1__state  = 5;
                                            while (this.__7__wrap21.MoveNext())
                                            {
                                                this._commandType_5__18         = this.__7__wrap21.Current;
                                                this._shouldExportCommand_5__19 = true;
                                                if ((this.context.InitialSessionState != null) && (this.commandOrigin == CommandOrigin.Runspace))
                                                {
                                                    foreach (SessionStateCommandEntry entry in this.context.InitialSessionState.Commands[this._exportedCommand_5__17])
                                                    {
                                                        string b = null;
                                                        if (entry.Module != null)
                                                        {
                                                            b = entry.Module.Name;
                                                        }
                                                        else if (entry.PSSnapIn != null)
                                                        {
                                                            b = entry.PSSnapIn.Name;
                                                        }
                                                        if (string.Equals(this._moduleShortName_5__15, b, StringComparison.OrdinalIgnoreCase) && (entry.Visibility == SessionStateEntryVisibility.Private))
                                                        {
                                                            this._shouldExportCommand_5__19 = false;
                                                        }
                                                    }
                                                }
                                                if (!this._shouldExportCommand_5__19)
                                                {
                                                    continue;
                                                }
                                                this._current_5__1a = null;
                                                switch (this._commandType_5__18)
                                                {
                                                case CommandTypes.Alias:
                                                    this._current_5__1a = new AliasInfo(this._exportedCommand_5__17, null, this.context);
                                                    break;

                                                case CommandTypes.Function:
                                                    this._current_5__1a = new FunctionInfo(this._exportedCommand_5__17, ScriptBlock.Create(""), this.context);
                                                    break;

                                                case CommandTypes.Cmdlet:
                                                    this._current_5__1a = new CmdletInfo(this._exportedCommand_5__17, null, null, null, this.context);
                                                    break;

                                                case CommandTypes.Workflow:
                                                    this._current_5__1a = new WorkflowInfo(this._exportedCommand_5__17, ScriptBlock.Create(""), this.context);
                                                    break;
                                                }
                                                if (this._current_5__1a != null)
                                                {
                                                    this._current_5__1a.SetModule(this._tempModuleInfo_5__11);
                                                }
                                                this.__2__current = this._current_5__1a;
                                                this.__1__state   = 7;
                                                return(true);

Label_060F:
                                                this.__1__state = 5;
                                            }
                                            this.__m__Finally22();
                                        }
                                    }
                                    this.__m__Finally20();
                                }
                            }
                            this.__m__Finally1c();
                        }
                    }
                    return(false);
                }
                finally
                {
                    (this as IDisposable).Dispose();
                }
            }
Пример #9
0
        internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, string culture)
        {
            if (((InitialSessionState.IsEngineModule(module.ModuleName) || InitialSessionState.IsNestedEngineModule(module.ModuleName)) || module.ModuleName.Equals(InitialSessionState.CoreSnapin, StringComparison.OrdinalIgnoreCase)) && !UpdatableHelpSystem.IsAdministrator())
            {
                string message = StringUtil.Format(HelpErrors.UpdatableHelpRequiresElevation, new object[0]);
                base.ProcessException(module.ModuleName, null, new UpdatableHelpSystemException("UpdatableHelpSystemRequiresElevation", message, ErrorCategory.InvalidOperation, null, null));
                return(false);
            }
            UpdatableHelpInfo currentHelpInfo = null;
            UpdatableHelpInfo newHelpInfo     = null;
            string            str2            = null;
            string            xml             = UpdatableHelpSystem.LoadStringFromPath(this, base.SessionState.Path.Combine(module.ModuleBase, module.GetHelpInfoName()), null);

            if (xml != null)
            {
                currentHelpInfo = base._helpSystem.CreateHelpInfo(xml, module.ModuleName, module.ModuleGuid, null, null, false);
            }
            if (!this.alreadyCheckedOncePerDayPerModule && !base.CheckOncePerDayPerModule(module.ModuleName, module.ModuleBase, module.GetHelpInfoName(), DateTime.UtcNow, base._force))
            {
                return(true);
            }
            this.alreadyCheckedOncePerDayPerModule = true;
            if (this._path != null)
            {
                //using (null)
                {
                    try
                    {
                        Collection <string> collection = new Collection <string>();
                        foreach (string str4 in this._path)
                        {
                            if (string.IsNullOrEmpty(str4))
                            {
                                PSArgumentException exception = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.PathNullOrEmpty, new object[0]));
                                base.WriteError(exception.ErrorRecord);
                                return(false);
                            }
                            try
                            {
                                string path = str4;
                                if (base._credential != null)
                                {
                                    UpdatableHelpSystemDrive drive2 = new UpdatableHelpSystemDrive(this, str4, base._credential);
                                    path = drive2.DriveName;
                                }
                                foreach (string str6 in base.ResolvePath(path, this._recurse, this.isLiteralPath))
                                {
                                    collection.Add(str6);
                                }
                            }
                            catch (System.Management.Automation.DriveNotFoundException exception2)
                            {
                                this.ThrowPathMustBeValidContainersException(str4, exception2);
                            }
                            catch (ItemNotFoundException exception3)
                            {
                                this.ThrowPathMustBeValidContainersException(str4, exception3);
                            }
                        }
                        if (collection.Count == 0)
                        {
                            return(true);
                        }
                        foreach (string str7 in collection)
                        {
                            string str8 = base.SessionState.Path.Combine(str7, module.GetHelpInfoName());
                            xml = UpdatableHelpSystem.LoadStringFromPath(this, str8, base._credential);
                            if (xml != null)
                            {
                                newHelpInfo = base._helpSystem.CreateHelpInfo(xml, module.ModuleName, module.ModuleGuid, culture, str7, false);
                                str2        = str7;
                                goto Label_02DD;
                            }
                        }
                    }
                    catch (Exception exception4)
                    {
                        CommandProcessorBase.CheckForSevereException(exception4);
                        throw new UpdatableHelpSystemException("UnableToRetrieveHelpInfoXml", StringUtil.Format(HelpDisplayStrings.UnableToRetrieveHelpInfoXml, culture), ErrorCategory.ResourceUnavailable, null, exception4);
                    }
                    goto Label_02DD;
                }
            }
            string str9 = base._helpSystem.GetHelpInfoUri(module, null).ResolvedUri + module.GetHelpInfoName();

            newHelpInfo = base._helpSystem.GetHelpInfo(UpdatableHelpCommandType.UpdateHelpCommand, str9, module.ModuleName, module.ModuleGuid, culture);
Label_02DD:
            if (newHelpInfo == null)
            {
                throw new UpdatableHelpSystemException("UnableToRetrieveHelpInfoXml", StringUtil.Format(HelpDisplayStrings.UnableToRetrieveHelpInfoXml, culture), ErrorCategory.ResourceUnavailable, null, null);
            }
            bool flag = false;

            foreach (UpdatableHelpUri uri in newHelpInfo.HelpContentUriCollection)
            {
                if (!base.IsUpdateNecessary(module, currentHelpInfo, newHelpInfo, uri.Culture, base._force))
                {
                    base.WriteVerbose(StringUtil.Format(HelpDisplayStrings.SuccessfullyUpdatedHelpContent, new object[] { module.ModuleName, HelpDisplayStrings.NewestContentAlreadyInstalled, uri.Culture.Name, newHelpInfo.GetCultureVersion(uri.Culture) }));
                    flag = true;
                }
                else
                {
                    try
                    {
                        Collection <string> collection3;
                        string resolvedUri            = uri.ResolvedUri;
                        string xsdPath                = base.SessionState.Path.Combine(Utils.GetApplicationBase(base.Context.ShellID), @"Schemas\PSMaml\maml.xsd");
                        Collection <string> destPaths = new Collection <string> {
                            module.ModuleBase
                        };
                        if (UpdatableHelpCommandBase.IsSystemModule(module.ModuleName) && Environment.Is64BitOperatingSystem)
                        {
                            string item = Utils.GetApplicationBase(Utils.DefaultPowerShellShellID).Replace("System32", "SysWOW64");
                            destPaths.Add(item);
                        }
                        if (Directory.Exists(resolvedUri))
                        {
                            if (base._credential != null)
                            {
                                string helpContentName = module.GetHelpContentName(uri.Culture);
                                string str14           = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName()));
                                try
                                {
                                    using (UpdatableHelpSystemDrive drive3 = new UpdatableHelpSystemDrive(this, resolvedUri, base._credential))
                                    {
                                        if (!Directory.Exists(str14))
                                        {
                                            Directory.CreateDirectory(str14);
                                        }
                                        base.InvokeProvider.Item.Copy(new string[] { Path.Combine(drive3.DriveName, helpContentName) }, Path.Combine(str14, helpContentName), false, CopyContainers.CopyTargetContainer, true, true);
                                        base._helpSystem.InstallHelpContent(UpdatableHelpCommandType.UpdateHelpCommand, base.Context, str14, destPaths, module.GetHelpContentName(uri.Culture), Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName())), uri.Culture, xsdPath, out collection3);
                                    }
                                    goto Label_0593;
                                }
                                catch (Exception exception5)
                                {
                                    CommandProcessorBase.CheckForSevereException(exception5);
                                    throw new UpdatableHelpSystemException("HelpContentNotFound", StringUtil.Format(HelpDisplayStrings.HelpContentNotFound, new object[0]), ErrorCategory.ResourceUnavailable, null, exception5);
                                }
                            }
                            base._helpSystem.InstallHelpContent(UpdatableHelpCommandType.UpdateHelpCommand, base.Context, resolvedUri, destPaths, module.GetHelpContentName(uri.Culture), Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName())), uri.Culture, xsdPath, out collection3);
                        }
                        else if (!base._helpSystem.DownloadAndInstallHelpContent(UpdatableHelpCommandType.UpdateHelpCommand, base.Context, destPaths, module.GetHelpContentName(uri.Culture), uri.Culture, resolvedUri, xsdPath, out collection3))
                        {
                            flag = false;
                            goto Label_069B;
                        }
Label_0593:
                        base._helpSystem.GenerateHelpInfo(module.ModuleName, module.ModuleGuid, newHelpInfo.UnresolvedUri, uri.Culture.Name, newHelpInfo.GetCultureVersion(uri.Culture), module.ModuleBase, module.GetHelpInfoName(), base._force);
                        foreach (string str15 in collection3)
                        {
                            base.WriteVerbose(StringUtil.Format(HelpDisplayStrings.SuccessfullyUpdatedHelpContent, new object[] { module.ModuleName, StringUtil.Format(HelpDisplayStrings.UpdatedHelpContent, str15), uri.Culture.Name, newHelpInfo.GetCultureVersion(uri.Culture) }));
                        }
                        base.LogMessage(StringUtil.Format(HelpDisplayStrings.UpdateHelpCompleted, new object[0]));
                        flag = true;
                    }
                    catch (Exception exception6)
                    {
                        CommandProcessorBase.CheckForSevereException(exception6);
                        base.ProcessException(module.ModuleName, uri.Culture.Name, exception6);
                    }
                    Label_069B :;
                }
            }
            return(flag);
        }
Пример #10
0
        protected override void ProcessRecord()
        {
            Dictionary <PSModuleInfo, List <PSModuleInfo> > dictionary = new Dictionary <PSModuleInfo, List <PSModuleInfo> >();

            foreach (PSModuleInfo info in base.Context.Modules.GetModules(this._name, false))
            {
                dictionary.Add(info, new List <PSModuleInfo> {
                    info
                });
            }
            foreach (PSModuleInfo info2 in this._moduleInfo)
            {
                dictionary.Add(info2, new List <PSModuleInfo> {
                    info2
                });
            }
            Dictionary <PSModuleInfo, List <PSModuleInfo> > dictionary2 = new Dictionary <PSModuleInfo, List <PSModuleInfo> >();

            foreach (KeyValuePair <PSModuleInfo, List <PSModuleInfo> > pair in dictionary)
            {
                PSModuleInfo key = pair.Key;
                if ((key.NestedModules != null) && (key.NestedModules.Count > 0))
                {
                    List <PSModuleInfo> nestedModulesWithNoCircularReference = new List <PSModuleInfo>();
                    this.GetAllNestedModules(key, ref nestedModulesWithNoCircularReference);
                    dictionary2.Add(key, nestedModulesWithNoCircularReference);
                }
            }
            HashSet <PSModuleInfo> set = new HashSet <PSModuleInfo>(new PSModuleInfoComparer());

            if (dictionary2.Count > 0)
            {
                foreach (KeyValuePair <PSModuleInfo, List <PSModuleInfo> > pair2 in dictionary2)
                {
                    List <PSModuleInfo> list4 = null;
                    if (dictionary.TryGetValue(pair2.Key, out list4))
                    {
                        foreach (PSModuleInfo info4 in pair2.Value)
                        {
                            if (!set.Contains(info4))
                            {
                                list4.Add(info4);
                                set.Add(info4);
                            }
                        }
                    }
                }
            }
            Dictionary <PSModuleInfo, List <PSModuleInfo> > dictionary3 = new Dictionary <PSModuleInfo, List <PSModuleInfo> >();

            foreach (KeyValuePair <PSModuleInfo, List <PSModuleInfo> > pair3 in dictionary)
            {
                List <PSModuleInfo> list5 = new List <PSModuleInfo>();
                for (int i = pair3.Value.Count - 1; i >= 0; i--)
                {
                    PSModuleInfo targetObject = pair3.Value[i];
                    if (targetObject.AccessMode == ModuleAccessMode.Constant)
                    {
                        InvalidOperationException exception = new InvalidOperationException(StringUtil.Format(Modules.ModuleIsConstant, targetObject.Name));
                        ErrorRecord errorRecord             = new ErrorRecord(exception, "Modules_ModuleIsConstant", ErrorCategory.PermissionDenied, targetObject);
                        base.WriteError(errorRecord);
                    }
                    else if ((targetObject.AccessMode == ModuleAccessMode.ReadOnly) && !base.BaseForce)
                    {
                        string text = StringUtil.Format(Modules.ModuleIsReadOnly, targetObject.Name);
                        if (InitialSessionState.IsConstantEngineModule(targetObject.Name))
                        {
                            base.WriteWarning(text);
                        }
                        else
                        {
                            InvalidOperationException exception2 = new InvalidOperationException(text);
                            ErrorRecord record2 = new ErrorRecord(exception2, "Modules_ModuleIsReadOnly", ErrorCategory.PermissionDenied, targetObject);
                            base.WriteError(record2);
                        }
                    }
                    else if (base.ShouldProcess(StringUtil.Format(Modules.ConfirmRemoveModule, targetObject.Name, targetObject.Path)))
                    {
                        if (this.ModuleProvidesCurrentSessionDrive(targetObject))
                        {
                            if (!InitialSessionState.IsEngineModule(targetObject.Name))
                            {
                                string str4 = (this._name.Length == 1) ? this._name[0] : targetObject.Name;
                                throw PSTraceSource.NewInvalidOperationException("Modules", "ModuleDriveInUse", new object[] { str4 });
                            }
                            if (!base.BaseForce)
                            {
                                string str3 = StringUtil.Format(Modules.CoreModuleCannotBeRemoved, targetObject.Name);
                                base.WriteWarning(str3);
                            }
                        }
                        else
                        {
                            list5.Add(targetObject);
                        }
                    }
                }
                dictionary3[pair3.Key] = list5;
            }
            Dictionary <PSModuleInfo, List <PSModuleInfo> > requiredDependencies = this.GetRequiredDependencies();

            foreach (KeyValuePair <PSModuleInfo, List <PSModuleInfo> > pair4 in dictionary3)
            {
                foreach (PSModuleInfo info6 in pair4.Value)
                {
                    if (!base.BaseForce)
                    {
                        List <PSModuleInfo> list6 = null;
                        if (requiredDependencies.TryGetValue(info6, out list6))
                        {
                            for (int j = list6.Count - 1; j >= 0; j--)
                            {
                                if (dictionary3.ContainsKey(list6[j]))
                                {
                                    list6.RemoveAt(j);
                                }
                            }
                            if (list6.Count > 0)
                            {
                                InvalidOperationException exception4 = new InvalidOperationException(StringUtil.Format(Modules.ModuleIsRequired, info6.Name, list6[0].Name));
                                ErrorRecord record3 = new ErrorRecord(exception4, "Modules_ModuleIsRequired", ErrorCategory.PermissionDenied, info6);
                                base.WriteError(record3);
                                continue;
                            }
                        }
                    }
                    this._numberRemoved++;
                    base.RemoveModule(info6, pair4.Key.Name);
                }
            }
        }
Пример #11
0
        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);
        }
        /// <summary>
        /// Adds one or more snapins
        /// </summary>
        /// <param name="snapInList">List of snapin IDs</param>
        /// <remarks>
        /// This is a helper method and should not throw any
        /// exceptions. All exceptions are caught and displayed
        /// to the user using write* methods
        /// </remarks>
        private void AddPSSnapIns(Collection <string> snapInList)
        {
            if (snapInList == null)
            {
                // nothing to add
                return;
            }

            //BUGBUG TODO - brucepay - this is a workaround for not being able to dynamically update
            // the set of cmdlets in a runspace if there is no RunspaceConfiguration object.
            // This is a temporary fix to unblock remoting tests and need to be corrected/completed
            // before we can ship...

            // If there is no RunspaceConfig object, then
            // use an InitialSessionState object to gather and
            // bind the cmdlets from the snapins...
            if (Context.RunspaceConfiguration == null)
            {
                Collection <PSSnapInInfo> loadedSnapins = base.GetSnapIns(null);
                InitialSessionState       iss           = InitialSessionState.Create();
                bool isAtleastOneSnapinLoaded           = false;
                foreach (string snapIn in snapInList)
                {
                    if (InitialSessionState.IsEngineModule(snapIn))
                    {
                        WriteNonTerminatingError(snapIn, "LoadSystemSnapinAsModule",
                                                 PSTraceSource.NewArgumentException(snapIn,
                                                                                    MshSnapInCmdletResources.LoadSystemSnapinAsModule, snapIn),
                                                 ErrorCategory.InvalidArgument);
                    }
                    else
                    {
                        PSSnapInException warning;
                        try
                        {
                            // Read snapin data
                            PSSnapInInfo newPSSnapIn  = PSSnapInReader.Read(Utils.GetCurrentMajorVersion(), snapIn);
                            PSSnapInInfo psSnapInInfo = IsSnapInLoaded(loadedSnapins, newPSSnapIn);

                            // that means snapin is not already loaded ..so load the snapin
                            // now.
                            if (null == psSnapInInfo)
                            {
                                psSnapInInfo             = iss.ImportPSSnapIn(snapIn, out warning);
                                isAtleastOneSnapinLoaded = true;
                                Context.InitialSessionState.ImportedSnapins.Add(psSnapInInfo.Name, psSnapInInfo);
                            }
                            // Write psSnapInInfo object only if passthru is specified.
                            if (_passThru)
                            {
                                // Load the pssnapin info properties that are localizable and redirected in the registry
                                psSnapInInfo.LoadIndirectResources(ResourceReader);
                                WriteObject(psSnapInInfo);
                            }
                        }

                        catch (PSSnapInException pse)
                        {
                            WriteNonTerminatingError(snapIn, "AddPSSnapInRead", pse, ErrorCategory.InvalidData);
                        }
                    }
                }

                if (isAtleastOneSnapinLoaded)
                {
                    // Now update the session state with the new stuff...
                    iss.Bind(Context, /*updateOnly*/ true);
                }

                return;
            }

            foreach (string psSnapIn in snapInList)
            {
                Exception exception = null;

                try
                {
                    PSSnapInException warning = null;

                    PSSnapInInfo psSnapInInfo = this.Runspace.AddPSSnapIn(psSnapIn, out warning);

                    if (warning != null)
                    {
                        WriteNonTerminatingError(psSnapIn, "AddPSSnapInRead", warning, ErrorCategory.InvalidData);
                    }

                    // Write psSnapInInfo object only if passthru is specified.
                    if (_passThru)
                    {
                        // Load the pssnapin info properties that are localizable and redirected in the registry
                        psSnapInInfo.LoadIndirectResources(ResourceReader);
                        WriteObject(psSnapInInfo);
                    }
                }
                catch (PSArgumentException ae)
                {
                    exception = ae;
                }
                catch (PSSnapInException sle)
                {
                    exception = sle;
                }
                catch (System.Security.SecurityException se)
                {
                    exception = se;
                }

                if (exception != null)
                {
                    WriteNonTerminatingError(psSnapIn,
                                             "AddPSSnapInRead",
                                             exception,
                                             ErrorCategory.InvalidArgument);
                }
            }
        }
Пример #13
0
 private void AddPSSnapIns(Collection <string> snapInList)
 {
     if (snapInList != null)
     {
         if (base.Context.RunspaceConfiguration == null)
         {
             Collection <PSSnapInInfo> snapIns = base.GetSnapIns(null);
             InitialSessionState       state   = InitialSessionState.Create();
             bool flag = false;
             foreach (string str in snapInList)
             {
                 if (InitialSessionState.IsEngineModule(str))
                 {
                     base.WriteNonTerminatingError(str, "LoadSystemSnapinAsModule", PSTraceSource.NewArgumentException(str, "MshSnapInCmdletResources", "LoadSystemSnapinAsModule", new object[] { str }), ErrorCategory.InvalidArgument);
                 }
                 else
                 {
                     try
                     {
                         PSSnapInInfo psSnapInInfo = PSSnapInReader.Read(Utils.GetCurrentMajorVersion(), str);
                         PSSnapInInfo info2        = PSSnapInCommandBase.IsSnapInLoaded(snapIns, psSnapInInfo);
                         if (info2 == null)
                         {
                             PSSnapInException exception;
                             info2 = state.ImportPSSnapIn(str, out exception);
                             flag  = true;
                             base.Context.InitialSessionState.ImportedSnapins.Add(info2.Name, info2);
                         }
                         if (this._passThru)
                         {
                             info2.LoadIndirectResources(base.ResourceReader);
                             base.WriteObject(info2);
                         }
                     }
                     catch (PSSnapInException exception2)
                     {
                         base.WriteNonTerminatingError(str, "AddPSSnapInRead", exception2, ErrorCategory.InvalidData);
                     }
                 }
             }
             if (flag)
             {
                 state.Bind(base.Context, true);
             }
         }
         else
         {
             foreach (string str2 in snapInList)
             {
                 Exception innerException = null;
                 try
                 {
                     PSSnapInException warning        = null;
                     PSSnapInInfo      sendToPipeline = base.Runspace.AddPSSnapIn(str2, out warning);
                     if (warning != null)
                     {
                         base.WriteNonTerminatingError(str2, "AddPSSnapInRead", warning, ErrorCategory.InvalidData);
                     }
                     if (this._passThru)
                     {
                         sendToPipeline.LoadIndirectResources(base.ResourceReader);
                         base.WriteObject(sendToPipeline);
                     }
                 }
                 catch (PSArgumentException exception5)
                 {
                     innerException = exception5;
                 }
                 catch (PSSnapInException exception6)
                 {
                     innerException = exception6;
                 }
                 catch (SecurityException exception7)
                 {
                     innerException = exception7;
                 }
                 if (innerException != null)
                 {
                     base.WriteNonTerminatingError(str2, "AddPSSnapInRead", innerException, ErrorCategory.InvalidArgument);
                 }
             }
         }
     }
 }