Beispiel #1
0
 /// <summary>
 /// Resets <see cref="GraphSession"/> instance when a user removes the module from the session via Remove-Module.
 /// </summary>
 /// <param name="psModuleInfo">A <see cref="PSModuleInfo"/> object.</param>
 public void OnRemove(PSModuleInfo psModuleInfo)
 {
     GraphSession.Reset();
 }
Beispiel #2
0
        /// <summary>
        /// Take module info of module that can be already loaded or not and loads it.
        /// </summary>
        /// <param name="originalModuleInfo"></param>
        /// <returns>module info of the same module, but loaded</returns>
        private static PSModuleInfo LoadModule(PSModuleInfo originalModuleInfo)
        {
            // originalModuleInfo is created during parse time and may not contain [System.Type] types exported from the module.
            // At this moment, we need to actually load the module and create types.
            // We want to load **exactly the same module** as we used at parse time.
            // And avoid the module resolution logic that can lead to another module (if something changed on the file system).
            // So, we load the module by the file path, not by module specification (ModuleName, RequiredVersion).
            var modulePath = originalModuleInfo.Path;
            var commandInfo = new CmdletInfo("Import-Module", typeof(ImportModuleCommand));
            var ps = PowerShell.Create(RunspaceMode.CurrentRunspace)
                .AddCommand(commandInfo)
                .AddParameter("Name", modulePath)
                .AddParameter("PassThru");
            var moduleInfo = ps.Invoke<PSModuleInfo>();
            if (ps.HadErrors)
            {
                var errorRecord = ps.Streams.Error[0];
                throw InterpreterError.NewInterpreterException(modulePath, typeof(RuntimeException), null,
                    errorRecord.FullyQualifiedErrorId, errorRecord.ToString());
            }

            if (moduleInfo.Count == 1)
            {
                return moduleInfo[0];
            }
            else
            {
                Diagnostics.Assert(false, "We should load exactly one module from the provided original module");
                return null;
            }
        }
Beispiel #3
0
 /// <summary>
 /// Add Type from the different module to the symbol Table.
 /// </summary>
 /// <param name="typeDefinitionAst"></param>
 /// <param name="moduleInfo"></param>
 public void AddTypeFromUsingModule(TypeDefinitionAst typeDefinitionAst, PSModuleInfo moduleInfo)
 {
     _scopes[_scopes.Count - 1].AddTypeFromUsingModule(_parser, typeDefinitionAst, moduleInfo);
 }
 /// <summary>
 /// Resets <see cref="GraphSession"/> instance when a user removes the module from the session via Remove-Module.
 /// </summary>
 /// <param name="psModuleInfo">A <see cref="PSModuleInfo"/> object.</param>
 public void OnRemove(PSModuleInfo psModuleInfo)
 {
     GraphSession.Reset();
     DependencyAssemblyResolver.Reset();
 }
 public PowerShellModule(PSModuleInfo module)
 {
     Name = module.Name ?? string.Empty;
 }
Beispiel #6
0
 internal static void AnalyzePSSnapInAssembly(Assembly assembly, string name, PSSnapInInfo psSnapInInfo, PSModuleInfo moduleInfo, bool isModuleLoad, out Dictionary <string, SessionStateCmdletEntry> cmdlets, out Dictionary <string, SessionStateProviderEntry> providers, out string helpFile)
 {
     Type[] assemblyTypes;
     helpFile = null;
     if (assembly == null)
     {
         throw new ArgumentNullException("assembly");
     }
     cmdlets   = null;
     providers = null;
     if (_cmdletCache.Value.ContainsKey(assembly))
     {
         cmdlets = new Dictionary <string, SessionStateCmdletEntry>(_cmdletCache.Value.Count, StringComparer.OrdinalIgnoreCase);
         Dictionary <string, SessionStateCmdletEntry> dictionary = _cmdletCache.Value[assembly];
         foreach (string str in dictionary.Keys)
         {
             SessionStateCmdletEntry entry = dictionary[str];
             if ((entry.PSSnapIn == null) && (psSnapInInfo != null))
             {
                 entry.SetPSSnapIn(psSnapInInfo);
             }
             SessionStateCmdletEntry entry2 = (SessionStateCmdletEntry)entry.Clone();
             cmdlets[str] = entry2;
         }
     }
     if (_providerCache.Value.ContainsKey(assembly))
     {
         providers = new Dictionary <string, SessionStateProviderEntry>(_providerCache.Value.Count, StringComparer.OrdinalIgnoreCase);
         Dictionary <string, SessionStateProviderEntry> dictionary2 = _providerCache.Value[assembly];
         foreach (string str2 in dictionary2.Keys)
         {
             SessionStateProviderEntry entry3 = dictionary2[str2];
             if ((entry3.PSSnapIn == null) && (psSnapInInfo != null))
             {
                 entry3.SetPSSnapIn(psSnapInInfo);
             }
             SessionStateProviderEntry entry4 = (SessionStateProviderEntry)entry3.Clone();
             providers[str2] = entry4;
         }
     }
     if ((cmdlets != null) || (providers != null))
     {
         if (!_assembliesWithModuleInitializerCache.Value.ContainsKey(assembly))
         {
             _PSSnapInTracer.WriteLine("Returning cached cmdlet and provider entries for {0}", new object[] { assembly.Location });
         }
         else
         {
             _PSSnapInTracer.WriteLine("Executing IModuleAssemblyInitializer.Import for {0}", new object[] { assembly.Location });
             assemblyTypes = GetAssemblyTypes(assembly, name);
             ExecuteModuleInitializer(assembly, assemblyTypes, isModuleLoad);
         }
     }
     else
     {
         _PSSnapInTracer.WriteLine("Analyzing assembly {0} for cmdlet and providers", new object[] { assembly.Location });
         helpFile      = GetHelpFile(assembly.Location);
         assemblyTypes = GetAssemblyTypes(assembly, name);
         ExecuteModuleInitializer(assembly, assemblyTypes, isModuleLoad);
         Type type  = null;
         Type type2 = null;
         foreach (Type type3 in assemblyTypes)
         {
             if ((type3.IsPublic || type3.IsNestedPublic) && !type3.IsAbstract)
             {
                 if (IsCmdletClass(type3) && HasDefaultConstructor(type3))
                 {
                     type = type3;
                     CmdletAttribute customAttribute = GetCustomAttribute <CmdletAttribute>(type3);
                     if (customAttribute != null)
                     {
                         string cmdletName = GetCmdletName(customAttribute);
                         if (!string.IsNullOrEmpty(cmdletName))
                         {
                             if ((cmdlets != null) && cmdlets.ContainsKey(cmdletName))
                             {
                                 string errorMessageFormat = StringUtil.Format(ConsoleInfoErrorStrings.PSSnapInDuplicateCmdlets, cmdletName, name);
                                 _PSSnapInTracer.TraceError(errorMessageFormat, new object[0]);
                                 throw new PSSnapInException(name, errorMessageFormat);
                             }
                             SessionStateCmdletEntry entry5 = new SessionStateCmdletEntry(cmdletName, type3, helpFile);
                             if (psSnapInInfo != null)
                             {
                                 entry5.SetPSSnapIn(psSnapInInfo);
                             }
                             if (cmdlets == null)
                             {
                                 cmdlets = new Dictionary <string, SessionStateCmdletEntry>(StringComparer.OrdinalIgnoreCase);
                             }
                             cmdlets.Add(cmdletName, entry5);
                             _PSSnapInTracer.WriteLine("{0} from type {1} is added as a cmdlet. ", new object[] { cmdletName, type3.FullName });
                         }
                     }
                 }
                 else if (IsProviderClass(type3) && HasDefaultConstructor(type3))
                 {
                     type2 = type3;
                     CmdletProviderAttribute providerAttribute = GetCustomAttribute <CmdletProviderAttribute>(type3);
                     if (providerAttribute != null)
                     {
                         string providerName = GetProviderName(providerAttribute);
                         if (!string.IsNullOrEmpty(providerName))
                         {
                             if ((providers != null) && providers.ContainsKey(providerName))
                             {
                                 string str6 = StringUtil.Format(ConsoleInfoErrorStrings.PSSnapInDuplicateProviders, providerName, psSnapInInfo.Name);
                                 _PSSnapInTracer.TraceError(str6, new object[0]);
                                 throw new PSSnapInException(psSnapInInfo.Name, str6);
                             }
                             SessionStateProviderEntry entry6 = new SessionStateProviderEntry(providerName, type3, helpFile);
                             entry6.SetPSSnapIn(psSnapInInfo);
                             if (moduleInfo != null)
                             {
                                 entry6.SetModule(moduleInfo);
                             }
                             if (providers == null)
                             {
                                 providers = new Dictionary <string, SessionStateProviderEntry>(StringComparer.OrdinalIgnoreCase);
                             }
                             providers.Add(providerName, entry6);
                             _PSSnapInTracer.WriteLine("{0} from type {1} is added as a provider. ", new object[] { providerName, type3.FullName });
                         }
                     }
                 }
             }
         }
         if (((providers == null) || (providers.Count == 0)) && ((cmdlets == null) || (cmdlets.Count == 0)))
         {
             try
             {
                 if (type != null)
                 {
                     ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes);
                     if (constructor != null)
                     {
                         constructor.Invoke(null);
                     }
                 }
                 if (type2 != null)
                 {
                     ConstructorInfo info2 = type2.GetConstructor(Type.EmptyTypes);
                     if (info2 != null)
                     {
                         info2.Invoke(null);
                     }
                 }
             }
             catch (TargetInvocationException exception)
             {
                 throw exception.InnerException;
             }
         }
         if (cmdlets != null)
         {
             Dictionary <string, SessionStateCmdletEntry> dictionary3 = new Dictionary <string, SessionStateCmdletEntry>(cmdlets.Count, StringComparer.OrdinalIgnoreCase);
             foreach (KeyValuePair <string, SessionStateCmdletEntry> pair in cmdlets)
             {
                 dictionary3[pair.Key] = (SessionStateCmdletEntry)pair.Value.Clone();
             }
             _cmdletCache.Value[assembly] = dictionary3;
         }
         if (providers != null)
         {
             Dictionary <string, SessionStateProviderEntry> dictionary4 = new Dictionary <string, SessionStateProviderEntry>(providers.Count, StringComparer.OrdinalIgnoreCase);
             foreach (KeyValuePair <string, SessionStateProviderEntry> pair2 in providers)
             {
                 dictionary4[pair2.Key] = (SessionStateProviderEntry)pair2.Value.Clone();
             }
             _providerCache.Value[assembly] = providers;
         }
     }
 }
 public void OnRemove(PSModuleInfo psModuleInfo)
 {
     AppDomain.CurrentDomain.AssemblyResolve -= HandleAssemblyResolve;
 }
Beispiel #8
0
        /// <summary>
        /// Generates a complete activity source file from a module.
        /// </summary>
        /// <param name="moduleToProcess"></param>
        /// <param name="activityNamespace">The namespace to use for the target classes</param>
        /// <returns>An array of code elements to compile into an assembly</returns>
        static public string[] GenerateFromModuleInfo(PSModuleInfo moduleToProcess, string activityNamespace)
        {
            if (moduleToProcess == null)
            {
                throw new ArgumentNullException("moduleToProcess");
            }

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

            // Cmdlets and function need to exist in separate namespaces...
            if (moduleToProcess.ExportedCmdlets != null)
            {
                string namespaceToUse = !string.IsNullOrEmpty(activityNamespace) ? activityNamespace : moduleToProcess.Name + "_Cmdlet_Activities";
                foreach (CmdletInfo ci in moduleToProcess.ExportedCmdlets.Values)
                {
                    string code = Microsoft.PowerShell.Activities.ActivityGenerator.GenerateFromCommandInfo(ci, namespaceToUse, "PSRemotingActivity", null, null, "");
                    codeToCompile.Add(code);
                }
            }

            Dictionary <string, string> modules = new Dictionary <string, string>();
            PSModuleInfo cimModule = moduleToProcess;

            if (moduleToProcess.ExportedFunctions != null)
            {
                string namespaceToUse = !string.IsNullOrEmpty(activityNamespace) ? activityNamespace : moduleToProcess.Name + "_Function_Activities";
                foreach (FunctionInfo fi in moduleToProcess.ExportedFunctions.Values)
                {
                    string moduleName       = null;
                    string moduleDefinition = null;

                    // Save the module defining this function - we may need to extract
                    // embedded types further on
                    if (fi.ScriptBlock.Module != null && !string.IsNullOrEmpty(fi.ScriptBlock.Module.Definition))
                    {
                        moduleName       = fi.ScriptBlock.Module.Name;
                        moduleDefinition = fi.ScriptBlock.Module.Definition;
                    }

                    string code;
                    if (fi.ScriptBlock.Module.ModuleType == ModuleType.Cim)
                    {
                        // Special-case CIM activities
                        string embeddedDefinition = "";

                        // Embed the module definition in the activity...
                        if (moduleDefinition != null)
                        {
                            // Remove all of the calls to Export-ModuleMember and getcommand
                            string editedDefinition = System.Text.RegularExpressions.Regex.Replace(moduleDefinition, @"Microsoft.PowerShell.Core\\Export-ModuleMember[^\n]*\n", "");
                            editedDefinition = System.Text.RegularExpressions.Regex.Replace(editedDefinition,
                                                                                            @"if \(\$\(Microsoft.PowerShell.Core\\Get-Command Set-StrictMode[^\n]*\n", "");

                            embeddedDefinition = "protected override string ModuleDefinition { get { return _moduleDefinition; } }\r\n        const string _moduleDefinition = @\""
                                                 + editedDefinition.Replace("\"", "\"\"") + "\";";
                        }
                        code = Microsoft.PowerShell.Activities.ActivityGenerator.GenerateFromCommandInfo(
                            fi, namespaceToUse, "PSGeneratedCIMActivity", new string[] { "Computer", "AsJob", "CimSession" }, null, embeddedDefinition);

                        cimModule = fi.ScriptBlock.Module;
                    }
                    else
                    {
                        code = Microsoft.PowerShell.Activities.ActivityGenerator.GenerateFromCommandInfo(
                            fi, namespaceToUse, "PSRemotingActivity", new string[] { "Computer", "AsJob" }, moduleToProcess.Name, "");
                    }
                    codeToCompile.Add(code);

                    if (moduleName != null && !modules.ContainsKey(fi.ScriptBlock.Module.Name))
                    {
                        modules.Add(moduleName, moduleDefinition);
                    }
                }
            }

            string fileName = cimModule.Path;

            // See if there are any embedded types to extract
            if (Path.GetExtension(fileName).Equals(".cdxml", StringComparison.OrdinalIgnoreCase))
            {
                // generate cmdletization proxies
                using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    XmlReader xmlReader = XmlReader.Create(file, xmlReaderSettings.Value);

                    PowerShellMetadata cmdletizationMetadata = (PowerShellMetadata)xmlSerializer.Value.Deserialize(xmlReader);

                    if (cmdletizationMetadata != null && cmdletizationMetadata.Enums != null)
                    {
                        foreach (EnumMetadataEnum enumMetadata in cmdletizationMetadata.Enums)
                        {
                            codeToCompile.Add(GetCSharpCode(enumMetadata));
                        }
                    }
                }
            }

            return(codeToCompile.ToArray <string>());
        }
        /// <summary>
        /// Loads and retrieves information about a given module.
        /// </summary>
        /// <param name="module">The module to load, given as a PSModuleInfo.</param>
        /// <param name="error">Any error encountered, if any.</param>
        /// <returns>The name, version and data object for the module, or null if data collection did not succeed.</returns>
        public Tuple <string, Version, ModuleData> LoadAndGetModuleData(PSModuleInfo module, out Exception error)
        {
            try
            {
                PSModuleInfo importedModule = _pwsh.AddCommand(s_ipmoInfo)
                                              .AddParameter("ModuleInfo", module)
                                              .AddParameter("PassThru")
                                              .AddParameter("ErrorAction", "Stop")
                                              .InvokeAndClear <PSModuleInfo>()
                                              .FirstOrDefault();

                if (importedModule == null)
                {
                    error = null;
                    return(null);
                }

                Tuple <string, Version, ModuleData> moduleData = GetSingleModuleData(importedModule);

                _pwsh.AddCommand(s_rmoInfo)
                .AddParameter("ModuleInfo", importedModule)
                .InvokeAndClear();

                error = null;
                return(moduleData);
            }
            catch (RuntimeException e)
            {
                // A common problem is TypeData being hit with other modules, this overrides that
                if (e.ErrorRecord.FullyQualifiedErrorId.Equals("FormatXmlUpdateException,Microsoft.PowerShell.Commands.ImportModuleCommand") ||
                    e.ErrorRecord.FullyQualifiedErrorId.Equals("ErrorsUpdatingTypes"))
                {
                    foreach (string typeDataName in GetTypeDataNamesFromErrorMessage(e.Message))
                    {
                        _pwsh.AddCommand("Remove-TypeData")
                        .AddParameter("TypeName", typeDataName)
                        .InvokeAndClear();
                    }
                }

                // Attempt to load the module in a new runspace instead
                try
                {
                    using (SMA.PowerShell fallbackPwsh = SMA.PowerShell.Create(RunspaceMode.NewRunspace))
                    {
                        PSModuleInfo importedModule = fallbackPwsh.AddCommand(s_ipmoInfo)
                                                      .AddParameter("Name", module.Path)
                                                      .AddParameter("PassThru")
                                                      .AddParameter("Force")
                                                      .AddParameter("ErrorAction", "Stop")
                                                      .InvokeAndClear <PSModuleInfo>()
                                                      .FirstOrDefault();

                        error = null;
                        return(GetSingleModuleData(importedModule));
                    }
                }
                catch (Exception fallbackException)
                {
                    error = fallbackException;
                    return(null);
                }
            }
        }
Beispiel #10
0
 private IEnumerable <KeyValuePair <string, string> > GetPackageManagementModules(PSModuleInfo module)
 {
     // skip modules that we know don't contain any PM modules
     if (!_exclusionList.Contains(module.Name))
     {
         var privateData = module.PrivateData as Hashtable;
         if (privateData != null)
         {
             return(ScanPrivateDataForProviders(Path.GetDirectoryName(module.Path), privateData, module.Version));
         }
     }
     return(Enumerable.Empty <KeyValuePair <string, string> >());
 }
Beispiel #11
0
 public PowerShellPackageProvider(DynamicPowershell ps, PSModuleInfo module) : base(ps, module)
 {
 }
Beispiel #12
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)
            {
                // TODO:
                // Paths in the module name may fail here because
                // they the wrong directory separator or are relative.
                // Fix with the code below:
                // FullyQualifiedName = FullyQualifiedName.Select(ms => ms.WithNormalizedName(Context, SessionState.Path.CurrentLocation.Path)).ToArray();
                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);
                }
            }
        }
        private List <CorrectionExtent> GetCorrectionExtent(string field, IScriptExtent extent, PSModuleInfo psModuleInfo)
        {
            Debug.Assert(field != null);
            Debug.Assert(psModuleInfo != null);
            Debug.Assert(extent != null);
            var    corrections    = new List <CorrectionExtent>();
            string correctionText = null;

            switch (field)
            {
            case functionsToExport:
                correctionText = GetListLiteral(psModuleInfo.ExportedFunctions);
                break;

            case cmdletsToExport:
                correctionText = GetListLiteral(psModuleInfo.ExportedCmdlets);
                break;

            case aliasesToExport:
                correctionText = GetListLiteral(psModuleInfo.ExportedAliases);
                break;

            default:
                throw new NotImplementedException(string.Format("{0} not implemented", field));
            }
            string description = string.Format(
                Strings.UseToExportFieldsInManifestCorrectionDescription,
                extent.Text,
                correctionText);

            corrections.Add(new CorrectionExtent(
                                extent.StartLineNumber,
                                extent.EndLineNumber,
                                extent.StartColumnNumber,
                                extent.EndColumnNumber,
                                correctionText,
                                extent.File,
                                description));
            return(corrections);
        }
Beispiel #14
0
 public ModuleInfo(PSModuleInfo info)
 {
     Path = info.ModuleBase;
     Name = info.Name;
 }
Beispiel #15
0
        /// <summary>
        /// Gets a list of matching commands
        /// </summary>
        /// <param name="pattern">command pattern</param>
        /// <param name="commandOrigin"></param>
        /// <param name="context"></param>
        /// <param name="rediscoverImportedModules"></param>
        /// <param name="moduleVersionRequired"></param>
        /// <returns></returns>
        internal static IEnumerable<CommandInfo> GetMatchingCommands(string pattern, ExecutionContext context, CommandOrigin commandOrigin, bool rediscoverImportedModules = false, bool moduleVersionRequired = 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(true, false, context))
                {
                    // Skip modules that have already been loaded so that we don't expose private commands.
                    string moduleName = Path.GetFileNameWithoutExtension(modulePath);
                    var 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, null, null);
                            tempModuleInfo.SetModuleBase(psModule.ModuleBase);

                            foreach (var entry in psModule.ExportedCommands)
                            {
                                if (commandPattern.IsMatch(entry.Value.Name))
                                {
                                    CommandInfo current = null;
                                    switch (entry.Value.CommandType)
                                    {
                                        case CommandTypes.Alias:
                                            current = new AliasInfo(entry.Value.Name, null, context);
                                            break;
                                        case CommandTypes.Workflow:
                                            current = new WorkflowInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, 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, null, null, null, context);
                                            break;
                                        default:
                                            Dbg.Assert(false, "cannot be hit");
                                            break;
                                    }

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

                            continue;
                        }
                    }

                    string moduleShortName = System.IO.Path.GetFileNameWithoutExtension(modulePath);
                    var exportedCommands = AnalysisCache.GetExportedCommands(modulePath, false, context);

                    if (exportedCommands == null) { continue; }

                    tempModuleInfo = new PSModuleInfo(moduleShortName, modulePath, null, null);
                    if (InitialSessionState.IsEngineModule(moduleShortName))
                    {
                        tempModuleInfo.SetModuleBase(Utils.GetApplicationBase(Utils.DefaultPowerShellShellID));
                    }

                    //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 (var pair in exportedCommands)
                    {
                        var commandName = pair.Key;
                        var commandTypes = pair.Value;

                        if (commandPattern.IsMatch(commandName))
                        {
                            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
                                    };
                                }
                                if ((commandTypes & CommandTypes.Workflow) == CommandTypes.Workflow)
                                {
                                    yield return new WorkflowInfo(commandName, ScriptBlock.EmptyScriptBlock, context)
                                    {
                                        Module = tempModuleInfo
                                    };
                                }
                            }
                        }
                    }
                }
            }
        }
Beispiel #16
0
 public ModulePageMetadataOutput(PSModuleInfo moduleInfo)
 {
     ModuleInfo = moduleInfo;
 }
Beispiel #17
0
        internal void AddTypeFromUsingModule(Parser parser, TypeDefinitionAst typeDefinitionAst, PSModuleInfo moduleInfo)
        {
            TypeLookupResult result;
            if (_typeTable.TryGetValue(typeDefinitionAst.Name, out result))
            {
                if (result.ExternalNamespaces != null)
                {
                    // override external type by the type defined in the current namespace
                    result.ExternalNamespaces.Add(moduleInfo.Name);
                }
            }
            else
            {
                var newLookupEntry = new TypeLookupResult(typeDefinitionAst)
                {
                    ExternalNamespaces = new List<string>()
                };
                newLookupEntry.ExternalNamespaces.Add(moduleInfo.Name);
                _typeTable.Add(typeDefinitionAst.Name, newLookupEntry);
            }

            string fullName = SymbolResolver.GetModuleQualifiedName(moduleInfo.Name, typeDefinitionAst.Name);
            if (_typeTable.TryGetValue(fullName, out result))
            {
                parser.ReportError(typeDefinitionAst.Extent, () => ParserStrings.MemberAlreadyDefined, fullName);
            }
            else
            {
                _typeTable.Add(fullName, new TypeLookupResult(typeDefinitionAst));
            }
        }
Beispiel #18
0
 public static ModulePageMetadataOutput ToModulePageMetadataOutput(this PSModuleInfo moduleInfo) => new ModulePageMetadataOutput(moduleInfo);
Beispiel #19
0
        /// <summary>
        /// If we cannot use psget to get swidtag information, we will try to fill in some of the information
        /// </summary>
        /// <param name="packageProvider"></param>
        /// <param name="psModuleInfo"></param>
        private void ProvideSwidTagInformation(PackageProvider packageProvider, PSModuleInfo psModuleInfo)
        {
            if (packageProvider == null || psModuleInfo == null)
            {
                return;
            }

            packageProvider.VersionScheme = "MultiPartNumeric";

            Microsoft.PackageManagement.Internal.Packaging.SoftwareMetadata softwareMetadata = new Microsoft.PackageManagement.Internal.Packaging.SoftwareMetadata();
            bool changed = false;

            var type = psModuleInfo.GetType();

            // introduced in ps 2.0
            if (!string.IsNullOrWhiteSpace(psModuleInfo.Description))
            {
                softwareMetadata.Description = psModuleInfo.Description;
                changed = true;
            }

            // introduced in ps 3.0
            if (!string.IsNullOrWhiteSpace(psModuleInfo.Copyright))
            {
                softwareMetadata.AddAttribute("copyright", psModuleInfo.Copyright);
                changed = true;
            }

            // tags is introduced in ps 5.0
            var  tagsProperty = type.GetProperty("Tags");
            bool isV5         = tagsProperty != null;

            if (isV5)
            {
                // introduced in ps 5.0
                var tags = tagsProperty.GetValue(psModuleInfo);

                // check that we have something in tags
                if (tags is IEnumerable <string> && (tags as IEnumerable <string>).Any())
                {
                    softwareMetadata.AddAttribute("tags", string.Join(" ", (tags as IEnumerable <string>).Distinct()));
                    changed = true;
                }

                var releaseNotes = type.GetProperty("ReleaseNotes").GetValue(psModuleInfo);

                // check that we have something in releasenotes
                if (releaseNotes is string && !string.IsNullOrWhiteSpace(type.GetProperty("ReleaseNotes").GetValue(psModuleInfo) as string))
                {
                    softwareMetadata.AddAttribute("tags", string.Join(" ", (tags as IEnumerable <string>).Distinct()));
                    changed = true;
                }
            }

            if (changed)
            {
                packageProvider.AddElement(softwareMetadata);
            }

            if (isV5)
            {
                var iconUri = type.GetProperty("IconUri").GetValue(psModuleInfo);

                // introduced in ps 5.0
                if (iconUri is Uri)
                {
                    packageProvider.AddLink(iconUri as Uri, "icon");
                }

                var licenseUri = type.GetProperty("LicenseUri").GetValue(psModuleInfo);

                // introduced in ps 5.0
                if (licenseUri is Uri)
                {
                    packageProvider.AddLink(licenseUri as Uri, "license");
                }

                var projectUri = type.GetProperty("ProjectUri").GetValue(psModuleInfo);

                // introduced in ps 5.0
                if (projectUri is Uri)
                {
                    packageProvider.AddLink(projectUri as Uri, "project");
                }
            }

            // introduced in ps 3.0
            if (!string.IsNullOrWhiteSpace(psModuleInfo.Author))
            {
                packageProvider.AddEntity(psModuleInfo.Author, null, "author");
            }

            // introduced in ps 3.0
            if (!string.IsNullOrWhiteSpace(psModuleInfo.CompanyName))
            {
                packageProvider.AddEntity(psModuleInfo.CompanyName, null, "owner");
            }
        }
        /// <summary>
        /// Create the new module...
        /// </summary>
        protected override void EndProcessing()
        {
            // Create a module from a scriptblock...
            if (_scriptBlock != null)
            {
                string gs = System.Guid.NewGuid().ToString();
                if (String.IsNullOrEmpty(_name))
                {
                    _name = PSModuleInfo.DynamicModulePrefixString + gs;
                }

                try
                {
                    Context.Modules.IncrementModuleNestingDepth(this, _name);

                    List <object> results     = null;
                    PSModuleInfo  localModule = null;
                    try
                    {
                        // The path for a "dynamic" module will be a GUID so it's unique.
                        localModule = Context.Modules.CreateModule(_name, gs, _scriptBlock, null, out results, _arguments);

                        // Export all functions and variables if no exports were specified...
                        if (!localModule.SessionState.Internal.UseExportList)
                        {
                            List <WildcardPattern> cmdletPatterns   = BaseCmdletPatterns ?? MatchAll;
                            List <WildcardPattern> functionPatterns = BaseFunctionPatterns ?? MatchAll;

                            ModuleIntrinsics.ExportModuleMembers(this,
                                                                 localModule.SessionState.Internal,
                                                                 functionPatterns, cmdletPatterns, BaseAliasPatterns, BaseVariablePatterns, null);
                        }
                    }
                    catch (RuntimeException e)
                    {
                        // Preserve the inner module invocation info...
                        e.ErrorRecord.PreserveInvocationInfoOnce = true;
                        WriteError(e.ErrorRecord);
                    }

                    // If the module was created successfully, then process the result...
                    if (localModule != null)
                    {
                        if (_returnResult)
                        {
                            // import the specified members...
                            ImportModuleMembers(localModule, string.Empty /* no -Prefix for New-Module cmdlet */);
                            WriteObject(results, true);
                        }
                        else if (_asCustomObject)
                        {
                            WriteObject(localModule.AsCustomObject());
                        }
                        else
                        {
                            // import the specified members...
                            ImportModuleMembers(localModule, string.Empty /* no -Prefix for New-Module cmdlet */);
                            WriteObject(localModule);
                        }
                    }
                }
                finally
                {
                    Context.Modules.DecrementModuleNestingCount();
                }
                return;
            }
        }
 public void OnRemove(PSModuleInfo psModuleInfo)
 {
     AppDomain.CurrentDomain.AssemblyResolve -= DependencyResolution.ResolveExtenionAbstraction;
 }
        /// <summary>
        /// Checks if the module contains HelpInfoUri
        /// </summary>
        /// <param name="module"></param>
        /// <param name="moduleName"></param>
        /// <returns></returns>
        private static bool HasHelpInfoUri(PSModuleInfo module, string moduleName)
        {
            // The core module is really a SnapIn, so module will be null
            if (!String.IsNullOrEmpty(moduleName) && moduleName.Equals(InitialSessionState.CoreModule, StringComparison.OrdinalIgnoreCase))
            {
                return true;
            }

            if (module == null)
            {
                return false;
            }

            return !String.IsNullOrEmpty(module.HelpInfoUri);
        }
Beispiel #23
0
 /// <inheritdoc/>
 public void OnRemove(PSModuleInfo psModuleInfo)
 {
     SubsystemManager.UnregisterSubsystem <ICommandPredictor>(AzPredictor.Identifier);
 }
Beispiel #24
0
 public void OnRemove(PSModuleInfo module)
 {
     AppDomain.CurrentDomain.AssemblyResolve -= ResolveAssembly;
 }
Beispiel #25
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 is 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
                                    });
                                }
                            }
                        }
                    }
                }
            }
        }
        private PSModuleInfo ConvertCimModuleInfoToPSModuleInfo(RemoteDiscoveryHelper.CimModule cimModule,
                                                                string computerName)
        {
            try
            {
                bool containedErrors = false;

                if (cimModule.MainManifest is null)
                {
                    return(GetModuleInfoForRemoteModuleWithoutManifest(cimModule));
                }

                string temporaryModuleManifestPath = Path.Combine(
                    RemoteDiscoveryHelper.GetModulePath(cimModule.ModuleName, null, computerName,
                                                        this.Context.CurrentRunspace),
                    Path.GetFileName(cimModule.ModuleName));

                Hashtable mainData = null;
                if (!containedErrors)
                {
                    mainData = RemoteDiscoveryHelper.ConvertCimModuleFileToManifestHashtable(
                        cimModule.MainManifest,
                        temporaryModuleManifestPath,
                        this,
                        ref containedErrors);
                    if (mainData is null)
                    {
                        return(GetModuleInfoForRemoteModuleWithoutManifest(cimModule));
                    }
                }

                if (!containedErrors)
                {
                    mainData = RemoteDiscoveryHelper.RewriteManifest(mainData);
                }

                Hashtable localizedData = mainData; // TODO/FIXME - this needs full path support from the provider

                PSModuleInfo moduleInfo = null;
                if (!containedErrors)
                {
                    ImportModuleOptions throwAwayOptions = new ImportModuleOptions();
                    moduleInfo = LoadModuleManifest(
                        temporaryModuleManifestPath,
                        null, // scriptInfo
                        mainData,
                        localizedData,
                        0 /* - don't write errors, don't load elements, don't return null on first error */,
                        this.BaseMinimumVersion,
                        this.BaseMaximumVersion,
                        this.BaseRequiredVersion,
                        this.BaseGuid,
                        ref throwAwayOptions,
                        ref containedErrors);
                }

                if ((moduleInfo is null) || containedErrors)
                {
                    moduleInfo = GetModuleInfoForRemoteModuleWithoutManifest(cimModule);
                }

                return(moduleInfo);
            }
            catch (Exception e)
            {
                ErrorRecord errorRecord = RemoteDiscoveryHelper.GetErrorRecordForProcessingOfCimModule(e, cimModule.ModuleName);
                this.WriteError(errorRecord);
                return(null);
            }
        }
Beispiel #27
0
        internal void AddTypeFromUsingModule(Parser parser, TypeDefinitionAst typeDefinitionAst, PSModuleInfo moduleInfo)
        {
            TypeLookupResult result;

            if (_typeTable.TryGetValue(typeDefinitionAst.Name, out result))
            {
                if (result.ExternalNamespaces != null)
                {
                    // override external type by the type defined in the current namespace
                    result.ExternalNamespaces.Add(moduleInfo.Name);
                }
            }
            else
            {
                var newLookupEntry = new TypeLookupResult(typeDefinitionAst)
                {
                    ExternalNamespaces = new List <string>()
                };
                newLookupEntry.ExternalNamespaces.Add(moduleInfo.Name);
                _typeTable.Add(typeDefinitionAst.Name, newLookupEntry);
            }

            string fullName = SymbolResolver.GetModuleQualifiedName(moduleInfo.Name, typeDefinitionAst.Name);

            if (_typeTable.TryGetValue(fullName, out result))
            {
                parser.ReportError(typeDefinitionAst.Extent,
                                   nameof(ParserStrings.MemberAlreadyDefined),
                                   ParserStrings.MemberAlreadyDefined,
                                   fullName);
            }
            else
            {
                _typeTable.Add(fullName, new TypeLookupResult(typeDefinitionAst));
            }
        }
        /// <summary>
        /// Create the new module...
        /// </summary>
        protected override void EndProcessing()
        {
            // Create a module from a scriptblock...
            if (_scriptBlock != null)
            {
                // Check ScriptBlock language mode.  If it is different than the context language mode
                // then throw error since private trusted script functions may be exposed.
                if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage &&
                    _scriptBlock.LanguageMode == PSLanguageMode.FullLanguage)
                {
                    this.ThrowTerminatingError(
                        new ErrorRecord(
                            new PSSecurityException(Modules.CannotCreateModuleWithScriptBlock),
                            "Modules_CannotCreateModuleWithFullLanguageScriptBlock",
                            ErrorCategory.SecurityError,
                            null));
                }

                string gs = System.Guid.NewGuid().ToString();
                if (string.IsNullOrEmpty(_name))
                {
                    _name = PSModuleInfo.DynamicModulePrefixString + gs;
                }

                try
                {
                    Context.Modules.IncrementModuleNestingDepth(this, _name);

                    List <object> results     = null;
                    PSModuleInfo  localModule = null;
                    try
                    {
                        // The path for a "dynamic" module will be a GUID so it's unique.
                        localModule = Context.Modules.CreateModule(_name, gs, _scriptBlock, null, out results, _arguments);

                        // Export all functions and variables if no exports were specified...
                        if (!localModule.SessionState.Internal.UseExportList)
                        {
                            List <WildcardPattern> cmdletPatterns   = BaseCmdletPatterns ?? MatchAll;
                            List <WildcardPattern> functionPatterns = BaseFunctionPatterns ?? MatchAll;

                            ModuleIntrinsics.ExportModuleMembers(this,
                                                                 localModule.SessionState.Internal,
                                                                 functionPatterns, cmdletPatterns, BaseAliasPatterns, BaseVariablePatterns, null);
                        }
                    }
                    catch (RuntimeException e)
                    {
                        // Preserve the inner module invocation info...
                        e.ErrorRecord.PreserveInvocationInfoOnce = true;
                        WriteError(e.ErrorRecord);
                    }

                    // If the module was created successfully, then process the result...
                    if (localModule != null)
                    {
                        if (_returnResult)
                        {
                            // import the specified members...
                            ImportModuleMembers(localModule, string.Empty /* no -Prefix for New-Module cmdlet */);
                            WriteObject(results, true);
                        }
                        else if (_asCustomObject)
                        {
                            WriteObject(localModule.AsCustomObject());
                        }
                        else
                        {
                            // import the specified members...
                            ImportModuleMembers(localModule, string.Empty /* no -Prefix for New-Module cmdlet */);
                            WriteObject(localModule);
                        }
                    }
                }
                finally
                {
                    Context.Modules.DecrementModuleNestingCount();
                }

                return;
            }
        }
Beispiel #29
0
 public static PsModuleHelpInfo ToModuleInfo(this PSModuleInfo moduleInfo) => new PsModuleHelpInfo(moduleInfo);
Beispiel #30
0
        private IEnumerable <KeyValuePair <string, PSModuleInfo> > ScanPrivateDataForProviders(PsRequest request, string baseFolder, Hashtable privateData, PSModuleInfo moduleInfo)
        {
            var providers = privateData.GetStringCollection("PackageManagementProviders").ReEnumerable();

            if (providers.Any())
            {
                // found a module that is advertizing one or more  Providers.

                foreach (var provider in providers)
                {
                    var fullPath = provider;
                    try {
                        if (!Path.IsPathRooted(provider))
                        {
                            fullPath = Path.GetFullPath(Path.Combine(baseFolder, provider));
                        }
                    } catch {
                        // got an error from the path.
                        continue;
                    }
                    if (Directory.Exists(fullPath) || File.Exists(fullPath))
                    {
                        // looks like we have something that could definitely be a
                        // a module path.
                        var result = new KeyValuePair <string, PSModuleInfo>(fullPath, moduleInfo);
                        AddToPowerShellProviderCacheTable(result);
                        yield return(result);
                    }
                    else
                    {
                        request.Verbose(string.Format(CultureInfo.CurrentCulture, Resources.Messages.FileNotFound, fullPath));
                    }
                }
            }
            else
            {
                request.Debug(string.Format(Resources.Messages.PackageManagementProvidersNotFound, baseFolder));
            }
        }
Beispiel #31
0
 public PsModuleHelpInfo(PSModuleInfo moduleInfo)
     : this(moduleInfo?.Name ?? String.Empty, moduleInfo?.Guid ?? Guid.NewGuid(), moduleInfo?.Description ?? String.Empty)
 {
 }
Beispiel #32
0
        private IEnumerable <KeyValuePair <string, PSModuleInfo> > GetPackageManagementModules(PsRequest request, PSModuleInfo module, Version requiredVersion, Version minimumVersion, Version maximumVersion)
        {
            // skip modules that we know don't contain any PM modules
            if (!_exclusionList.Contains(module.Name))
            {
                var privateData = module.PrivateData as Hashtable;
                if (privateData != null)
                {
                    if (requiredVersion != null)
                    {
                        if ((FourPartVersion)module.Version == (FourPartVersion)requiredVersion)
                        {
                            return(ScanPrivateDataForProviders(request, Path.GetDirectoryName(module.Path), privateData, module).ToArray());
                        }
                        else
                        {
                            return(Enumerable.Empty <KeyValuePair <string, PSModuleInfo> >());
                        }
                    }

                    if ((minimumVersion != null) && ((FourPartVersion)module.Version < (FourPartVersion)minimumVersion))
                    {
                        return(Enumerable.Empty <KeyValuePair <string, PSModuleInfo> >());
                    }

                    if ((maximumVersion != null) && ((FourPartVersion)module.Version > (FourPartVersion)maximumVersion))
                    {
                        return(Enumerable.Empty <KeyValuePair <string, PSModuleInfo> >());
                    }

                    return(ScanPrivateDataForProviders(request, Path.GetDirectoryName(module.Path), privateData, module).ToArray());
                }
            }
            return(Enumerable.Empty <KeyValuePair <string, PSModuleInfo> >());
        }
Beispiel #33
0
 protected InitialSessionStateEntry(string name)
 {
     this.name = name;
     this.psSnapIn = null;
     this.module = null;
 }
Beispiel #34
0
        private PackageProvider AnalyzeModule(PsRequest request, string modulePath, Version requiredVersion, bool force, bool logWarning = true, PSModuleInfo psModuleInfo = null)
        {
            if (string.IsNullOrWhiteSpace(modulePath))
            {
                return(null);
            }

            request.Debug("Attempting to load PowerShell Provider Module [{0}]", modulePath);

            if (string.Equals(Path.GetExtension(modulePath), ".dll", StringComparison.OrdinalIgnoreCase))
            {
                if (psModuleInfo != null)
                {
                    // fake provider and returns it
                    var result = new PackageProvider(new DefaultPackageProvider(psModuleInfo.Name, psModuleInfo.Version.ToString()))
                    {
                        ProviderPath = modulePath,
                        Version      = psModuleInfo.Version,
                        IsLoaded     = false
                    };

                    AddToPackageProviderCacheTable(result);

                    return(result);
                }
                else
                {
                    // psmoduleinfo is only null when this function is called in loadavailableprovider
                    // but in that case we want to load the provider directly anyway so we can do this
                    // if the path is a .dll then we ask packagemanagement to load it for us
                    // it will also register the dll
                    PackageManagementService.LoadProviderAssembly(request, modulePath, true);

                    // now let's checked whether we can find it in the list of loaded providers
                    foreach (var loadedProvider in PackageManagementService.PackageProviders)
                    {
                        // the one loaded should have the same path
                        if (string.Equals(loadedProvider.ProviderPath, modulePath, StringComparison.OrdinalIgnoreCase))
                        {
                            return(loadedProvider);
                        }
                    }

                    // if we reached here then we have failed to load the provider :(
                    return(null);
                }
            }

            string requiredVersionString = requiredVersion.ToString();
            var    provider = Create(request, modulePath, requiredVersionString, force, logWarning);

            if (provider != null)
            {
                var providerName = provider.GetPackageProviderName();
                if (!string.IsNullOrWhiteSpace(providerName))
                {
                    request.Debug(string.Format(CultureInfo.CurrentCulture, Resources.Messages.SuccessfullyLoadedModule, modulePath));
                    // looks good to me, let's add this to the list of moduels this meta provider can create.

                    var packageProvider = new PackageProvider(provider.As <IPackageProvider>())
                    {
                        IsLoaded     = true,
                        Version      = provider.GetProviderVersion(),
                        ProviderPath = modulePath
                    };

                    // take out powershell get
                    var psgetprovider = PackageManagementService.PackageProviders.FirstOrDefault(pv => string.Equals(pv.ProviderName, PowerShellGet, StringComparison.OrdinalIgnoreCase));

                    if (psModuleInfo != null)
                    {
                        // add swidtag information using moduleinfo
                        // however, this won't give us as much information yet
                        // we may have to fill this up later
                        ProvideSwidTagInformation(packageProvider, psModuleInfo);
                    }

                    AddToPackageProviderCacheTable(packageProvider);
                    _availableProviders.AddOrSet(providerName, provider);

                    return(packageProvider);
                }
                else
                {
                    provider.Dispose();
                    provider = null;
                    request.Debug(string.Format(CultureInfo.CurrentCulture, Resources.Messages.ProviderNameIsNullOrEmpty, modulePath));
                }
            }
            return(null);
        }
Beispiel #35
0
 /// <summary>
 /// Add Type from the different module to the symbol Table.
 /// </summary>
 /// <param name="typeDefinitionAst"></param>
 /// <param name="moduleInfo"></param>
 public void AddTypeFromUsingModule(TypeDefinitionAst typeDefinitionAst, PSModuleInfo moduleInfo)
 {
     _scopes[_scopes.Count - 1].AddTypeFromUsingModule(_parser, typeDefinitionAst, moduleInfo);
 }
Beispiel #36
0
 public RequiredModuleSpecs(PSModuleInfo moduleInfo)
 {
     Name    = moduleInfo.Name;
     Version = moduleInfo.Version;
     Guid    = moduleInfo.Guid;
 }