internal Collection<ProviderInfo> Get(PSModuleInfo moduleInfo)
 {
     var providers = from p in GetAll()
                     where p.Module != null && p.Module.Equals(moduleInfo)
                     select p;
     return new Collection<ProviderInfo>(providers.ToList());
 }
Пример #2
0
        /// <summary>
        /// Creates an instance of the ShowCommandModuleInfo class based on a CommandInfo object
        /// </summary>
        /// 
        /// <param name="other">
        /// The object to wrap.
        /// </param>
        public ShowCommandModuleInfo(PSModuleInfo other)
        {
            if (null == other)
            {
                throw new ArgumentNullException("other");
            }

            this.Name = other.Name;
        }
Пример #3
0
 public WorkflowInfo(
     string name,
     string definition,
     ScriptBlock workflow,
     string xamlDefinition,
     WorkflowInfo[] workflowsCalled,
     PSModuleInfo module)
     : base (name, workflow, null)
 {
 }
Пример #4
0
 internal ModuleSpecification(PSModuleInfo moduleInfo)
 {
     if (moduleInfo == null)
     {
         throw new ArgumentNullException("moduleInfo");
     }
     this.Name = moduleInfo.Name;
     this.Version = moduleInfo.Version;
     this.Guid = new System.Guid?(moduleInfo.Guid);
 }
Пример #5
0
 protected override void BeginProcessing()
 {
     _affectedModule = ExecutionContext.SessionState.Module;
     if (_affectedModule == null)
     {
         throw new PSInvalidOperationException("You can execute Export-ModuleMember only inside a module",
                                               "Modules_CanOnlyExecuteExportModuleMemberInsideAModule",
                                               ErrorCategory.PermissionDenied);
     }
 }
Пример #6
0
        private PSModuleInfo LoadModuleByPath(Path path)
        {
            // ALWAYS derive from global scope: the Scope parameter only defines where stuff is imported to
            var sessionState = new SessionState(_executionContext.SessionStateGlobal.RootSessionState);
            sessionState.IsScriptScope = true;
            sessionState.PSVariable.Set("PSScriptRoot", path.GetDirectory());
            var moduleInfo = new PSModuleInfo(path, path.GetFileNameWithoutExtension(), sessionState);
            sessionState.SetModule(moduleInfo);

            LoadFileIntoModule(moduleInfo, path);
            return moduleInfo;
        }
Пример #7
0
 private void RegisterModuleCleanUp(PSModuleInfo moduleInfo)
 {
     if (moduleInfo == null)
     {
         throw PSTraceSource.NewArgumentNullException("moduleInfo");
     }
     string sourceIdentifier = StringUtil.Format(ImplicitRemotingStrings.EventSourceIdentifier, base.Session.InstanceId, base.ModuleGuid);
     PSEventSubscriber subscriber = base.Context.Events.SubscribeEvent(base.Session.Runspace, "StateChanged", sourceIdentifier, PSObject.AsPSObject(moduleInfo), base.Context.Engine.ParseScriptBlock("& {\r\n            if ('Closed' -eq $eventArgs.RunspaceStateInfo.State)\r\n            {\r\n                $sourceIdentifier = [system.management.automation.wildcardpattern]::Escape($eventSubscriber.SourceIdentifier)\r\n                Unregister-Event -SourceIdentifier $sourceIdentifier -Force -ErrorAction SilentlyContinue\r\n\r\n                $moduleInfo = $event.MessageData\r\n                Remove-Module -ModuleInfo $moduleInfo -Force -ErrorAction SilentlyContinue\r\n\r\n                Remove-Item -LiteralPath $moduleInfo.ModuleBase -Recurse -Force -ErrorAction SilentlyContinue\r\n                $moduleInfo = $null\r\n            }\r\n}\r\n            ", false), true, false);
     ScriptBlock newClosure = base.Context.Engine.ParseScriptBlock("\r\n            $sourceIdentifier = [system.management.automation.wildcardpattern]::Escape($eventSubscriber.SourceIdentifier)\r\n            Unregister-Event -SourceIdentifier $sourceIdentifier -Force -ErrorAction SilentlyContinue\r\n\r\n            if ($previousScript -ne $null)\r\n            {\r\n                & $previousScript $args\r\n            }\r\n            ", false).GetNewClosure();
     newClosure.Module.SessionState.PSVariable.Set("eventSubscriber", subscriber);
     newClosure.Module.SessionState.PSVariable.Set("previousScript", moduleInfo.OnRemove);
     moduleInfo.OnRemove = newClosure;
 }
Пример #8
0
        // for all fields
        internal ProviderInfo(SessionState sessionState, Type implementingType, string name, string description, string home,
                              string helpFile, PSSnapInInfo psSnapIn, PSModuleInfo module)

        {
            _sessionState = sessionState;
            Module = module;
            PSSnapIn = psSnapIn;
            Name = name;
            Description = description;
            Home = home;
            ImplementingType = implementingType;
            Capabilities = GetCapabilities(implementingType);
            HelpFile = helpFile;
        }
Пример #9
0
 internal CommandInfo(CommandInfo other)
 {
     this._name = string.Empty;
     this._type = CommandTypes.Application;
     this._prefix = "";
     this._module = other._module;
     this._visibility = other._visibility;
     this._arguments = other._arguments;
     this.Context = other.Context;
     this._name = other._name;
     this._type = other._type;
     this._copiedCommand = other;
     this.DefiningLanguageMode = other.DefiningLanguageMode;
 }
Пример #10
0
        protected virtual void Dispose(bool disposing) {
            if (disposing) {
                if (_powershell != null) {
                    _powershell.Dispose();
                    _powershell = null;
                }

                if (_reentrancyLock != null) {
                    _reentrancyLock.Dispose();
                    _reentrancyLock = null;
                }

                _module = null;
            }
        }
Пример #11
0
 internal CmdletInfo(string name, Type implementingType, string helpFile, PSSnapInInfo snapin, PSModuleInfo module)
     : base(name, CommandTypes.Cmdlet)
 {
     int i = name.IndexOf('-');
     if (i == -1)
     {
         throw new Exception("InvalidCmdletNameFormat " + name);
     }
     ParameterInfoLookupTable = new Dictionary<string, CommandParameterInfo>(StringComparer.CurrentCultureIgnoreCase);
     Verb = name.Substring(0, i);
     Noun = name.Substring(i + 1);
     ImplementingType = implementingType;
     HelpFile = helpFile;
     _validationException = null;
     PSSnapIn = snapin;
     Module = module;
     GetParameterSetInfo(implementingType);
     GetOutputTypes(implementingType);
 }
Пример #12
0
 private void GetAllNestedModules(PSModuleInfo module, ref List<PSModuleInfo> nestedModulesWithNoCircularReference)
 {
     List<PSModuleInfo> list = new List<PSModuleInfo>();
     if ((module.NestedModules != null) && (module.NestedModules.Count > 0))
     {
         foreach (PSModuleInfo info in module.NestedModules)
         {
             if (!nestedModulesWithNoCircularReference.Contains(info))
             {
                 nestedModulesWithNoCircularReference.Add(info);
                 list.Add(info);
             }
         }
         foreach (PSModuleInfo info2 in list)
         {
             this.GetAllNestedModules(info2, ref nestedModulesWithNoCircularReference);
         }
     }
 }
Пример #13
0
        public PowerShellProviderBase(PowerShell ps, PSModuleInfo module) {
            if (module == null) {
                throw new ArgumentNullException("module");
            }

            _powershell = ps;
            _module = module;

            // combine all the cmdinfos we care about
            // but normalize the keys as we go (remove any '-' '_' chars)
            foreach (var k in _module.ExportedAliases.Keys) {
                _allCommands.AddOrSet(k.Replace("-", "").Replace("_", ""), _module.ExportedAliases[k]);
            }
            foreach (var k in _module.ExportedCmdlets.Keys) {
                _allCommands.AddOrSet(k.Replace("-", "").Replace("_", ""), _module.ExportedCmdlets[k]);
            }
            foreach (var k in _module.ExportedFunctions.Keys) {
                _allCommands.AddOrSet(k.Replace("-", "").Replace("_", ""), _module.ExportedFunctions[k]);
            }
        }
Пример #14
0
        private void LoadFileIntoModule(PSModuleInfo moduleInfo, Path path)
        {
            // prevents accidental loops while loading a module
            moduleInfo.NestingDepth++;
            if (moduleInfo.NestingDepth > 10)
            {
                var msg = "The module is too deeply nested. A module can be only nested 10 times. Make sure to check" +
                    " the loading order of your module";
                throw new PSInvalidOperationException(msg, "Modules_ModuleTooDeeplyNested",
                    ErrorCategory.InvalidOperation);
            }

            moduleInfo.Path = path; // update path for nested modules
            var stringComparer = StringComparer.InvariantCultureIgnoreCase;
            var ext = path.GetExtension();
            if (_scriptExtensions.Contains(ext, stringComparer))
            {
                moduleInfo.ModuleType = ModuleType.Script;
                LoadScriptModule(moduleInfo, path); // actually load the script
            }
            else if (_binaryExtensions.Contains(ext, stringComparer))
            {
                moduleInfo.ModuleType = ModuleType.Binary;
                LoadBinaryModule(moduleInfo, path);
            }
            else if (_manifestExtensions.Contains(ext, stringComparer))
            {
                moduleInfo.ModuleType = ModuleType.Manifest;
                LoadManifestModule(moduleInfo, path);
            }
            else
            {
                var msg = "The extension '" + ext + "' is currently not supported";
                throw new PSInvalidOperationException(msg, "Modules_InvalidFileExtension",
                                                      ErrorCategory.InvalidOperation, null, false);
            }
            moduleInfo.ValidateExportedMembers();
        }
Пример #15
0
 private bool ModuleProvidesCurrentSessionDrive(PSModuleInfo module)
 {
     if (module.ModuleType == ModuleType.Binary)
     {
         foreach (KeyValuePair<string, List<ProviderInfo>> pair in base.Context.TopLevelSessionState.Providers)
         {
             foreach (ProviderInfo info in pair.Value)
             {
                 if (info.ImplementingType.Assembly.Location.Equals(module.Path, StringComparison.OrdinalIgnoreCase))
                 {
                     foreach (PSDriveInfo info2 in base.Context.TopLevelSessionState.GetDrivesForProvider(info.FullName))
                     {
                         if (info2 == base.SessionState.Drive.Current)
                         {
                             return true;
                         }
                     }
                 }
             }
         }
     }
     return false;
 }
Пример #16
0
 internal void SetModule(PSModuleInfo module)
 {
     Module = module;
 }
Пример #17
0
 internal void AddRequiredModule(PSModuleInfo requiredModule)
 {
     AddModuleToList(requiredModule, this._requiredModules);
 }
Пример #18
0
 private static void AddModuleToList(PSModuleInfo module, List<PSModuleInfo> moduleList)
 {
     foreach (PSModuleInfo info in moduleList)
     {
         if (info.Path.Equals(module.Path, StringComparison.OrdinalIgnoreCase))
         {
             return;
         }
     }
     moduleList.Add(module);
 }
Пример #19
0
        private void GetAllNestedModules(PSModuleInfo module, ref List<PSModuleInfo> nestedModulesWithNoCircularReference)
        {
            List<PSModuleInfo> nestedModules = new List<PSModuleInfo>();
            if (module.NestedModules != null && module.NestedModules.Count > 0)
            {
                foreach (var nestedModule in module.NestedModules)
                {
                    if (!nestedModulesWithNoCircularReference.Contains(nestedModule))
                    {
                        nestedModulesWithNoCircularReference.Add(nestedModule);
                        nestedModules.Add(nestedModule);
                    }
                }

                foreach (PSModuleInfo child in nestedModules)
                {
                    GetAllNestedModules(child, ref nestedModulesWithNoCircularReference);
                }
            }
        }
Пример #20
0
 public WorkflowInfo(string name, string definition, ScriptBlock workflow, string xamlDefinition, WorkflowInfo[] workflowsCalled, PSModuleInfo module) : this(name, definition, workflow, xamlDefinition, workflowsCalled)
 {
     base.SetModule(module);
 }
Пример #21
0
 internal CmdletInfo(string name, Type implementingType, string helpFile, PSModuleInfo module)
     : this(name, implementingType, helpFile, null, module)
 {
 }
Пример #22
0
 /// <summary>
 /// Creates an instance of the workflowInfo class with the specified name and ScriptBlock
 /// </summary>
 /// <param name="name">
 /// The name of the workflow.
 /// </param>
 /// <param name="definition">
 /// The script body defining the workflow.
 /// </param>
 /// <param name="workflow">
 /// The ScriptBlock for the workflow
 /// </param>
 /// <param name="xamlDefinition">
 /// The XAML used to define the workflow
 /// </param>
 /// <param name="workflowsCalled">
 /// The workflows referenced within <paramref name="xamlDefinition"/>.
 /// </param>
 /// <param name="module">module.</param>
 /// <exception cref="ArgumentNullException">
 /// If <paramref name="workflow"/> is null.
 /// </exception>
 internal WorkflowInfo(string name, string definition, ScriptBlock workflow, string xamlDefinition, WorkflowInfo[] workflowsCalled, PSModuleInfo module)
     : this(name, definition, workflow, xamlDefinition, workflowsCalled)
 {
     this.Module = module;
 }
Пример #23
0
        internal static void CacheModuleExports(PSModuleInfo module, ExecutionContext context)
        {
            ModuleIntrinsics.Tracer.WriteLine("Requested caching for {0}", module.Name);

            // Don't cache incompatible modules on the system32 module path even if loaded with
            // -SkipEditionCheck, since it will break subsequent sessions.
            if (!module.IsConsideredEditionCompatible)
            {
                ModuleIntrinsics.Tracer.WriteLine($"Module '{module.Name}' not edition compatible and not cached.");
                return;
            }

            DateTime         lastWriteTime;
            ModuleCacheEntry moduleCacheEntry;

            GetModuleEntryFromCache(module.Path, out lastWriteTime, out moduleCacheEntry);

            var realExportedCommands = module.ExportedCommands;
            var realExportedClasses  = module.GetExportedTypeDefinitions();
            ConcurrentDictionary <string, CommandTypes>   exportedCommands;
            ConcurrentDictionary <string, TypeAttributes> exportedClasses;

            // First see if the existing module info is sufficient. GetModuleEntryFromCache does LastWriteTime
            // verification, so this will also return nothing if the cache is out of date or corrupt.
            if (moduleCacheEntry != null)
            {
                bool needToUpdate = false;

                // We need to iterate and check as exportedCommands will have more item as it can have aliases as well.
                exportedCommands = moduleCacheEntry.Commands;
                foreach (var pair in realExportedCommands)
                {
                    var          commandName     = pair.Key;
                    var          realCommandType = pair.Value.CommandType;
                    CommandTypes commandType;
                    if (!exportedCommands.TryGetValue(commandName, out commandType) || commandType != realCommandType)
                    {
                        needToUpdate = true;
                        break;
                    }
                }

                exportedClasses = moduleCacheEntry.Types;
                foreach (var pair in realExportedClasses)
                {
                    var            className          = pair.Key;
                    var            realTypeAttributes = pair.Value.TypeAttributes;
                    TypeAttributes typeAttributes;
                    if (!exportedClasses.TryGetValue(className, out typeAttributes) ||
                        typeAttributes != realTypeAttributes)
                    {
                        needToUpdate = true;
                        break;
                    }
                }

                // Update or not, we've analyzed commands and types now.
                moduleCacheEntry.TypesAnalyzed = true;

                if (!needToUpdate)
                {
                    ModuleIntrinsics.Tracer.WriteLine("Existing cached info up-to-date. Skipping.");
                    return;
                }

                exportedCommands.Clear();
                exportedClasses.Clear();
            }
            else
            {
                exportedCommands = new ConcurrentDictionary <string, CommandTypes>(3, realExportedCommands.Count, StringComparer.OrdinalIgnoreCase);
                exportedClasses  = new ConcurrentDictionary <string, TypeAttributes>(1, realExportedClasses.Count, StringComparer.OrdinalIgnoreCase);
                moduleCacheEntry = new ModuleCacheEntry
                {
                    ModulePath    = module.Path,
                    LastWriteTime = lastWriteTime,
                    Commands      = exportedCommands,
                    TypesAnalyzed = true,
                    Types         = exportedClasses
                };
                moduleCacheEntry = s_cacheData.Entries.GetOrAdd(module.Path, moduleCacheEntry);
            }

            // We need to update the cache
            foreach (var exportedCommand in realExportedCommands.Values)
            {
                ModuleIntrinsics.Tracer.WriteLine("Caching command: {0}", exportedCommand.Name);
                exportedCommands.GetOrAdd(exportedCommand.Name, exportedCommand.CommandType);
            }

            foreach (var pair in realExportedClasses)
            {
                var className = pair.Key;
                ModuleIntrinsics.Tracer.WriteLine("Caching command: {0}", className);
                moduleCacheEntry.Types.AddOrUpdate(className, pair.Value.TypeAttributes, (k, t) => t);
            }

            s_cacheData.QueueSerialization();
        }
Пример #24
0
        /// <summary>
        /// Get suggestion text from suggestion scriptblock with arguments.
        /// </summary>
        private static string GetSuggestionText(object suggestion, object[] suggestionArgs, PSModuleInfo invocationModule)
        {
            if (suggestion is ScriptBlock)
            {
                ScriptBlock suggestionScript = (ScriptBlock)suggestion;

                object result = null;
                try
                {
                    result = invocationModule.Invoke(suggestionScript, suggestionArgs);
                }
                catch (Exception)
                {
                    // Catch-all OK. This is a third-party call-out.
                    return(string.Empty);
                }

                return((string)LanguagePrimitives.ConvertTo(result, typeof(string), CultureInfo.CurrentCulture));
            }
            else
            {
                return((string)LanguagePrimitives.ConvertTo(suggestion, typeof(string), CultureInfo.CurrentCulture));
            }
        }
Пример #25
0
 private static string GetSuggestionText(object suggestion, PSModuleInfo invocationModule)
 {
     return(GetSuggestionText(suggestion, null, invocationModule));
 }
Пример #26
0
        internal static List <string> GetSuggestion(HistoryInfo lastHistory, object lastError, ArrayList errorList)
        {
            var returnSuggestions = new List <string>();

            PSModuleInfo invocationModule = new PSModuleInfo(true);

            invocationModule.SessionState.PSVariable.Set("lastHistory", lastHistory);
            invocationModule.SessionState.PSVariable.Set("lastError", lastError);

            int initialErrorCount = 0;

            // Go through all of the suggestions
            foreach (Hashtable suggestion in s_suggestions)
            {
                initialErrorCount = errorList.Count;

                // Make sure the rule is enabled
                if (!LanguagePrimitives.IsTrue(suggestion["Enabled"]))
                {
                    continue;
                }

                SuggestionMatchType matchType = (SuggestionMatchType)LanguagePrimitives.ConvertTo(
                    suggestion["MatchType"],
                    typeof(SuggestionMatchType),
                    CultureInfo.InvariantCulture);

                // If this is a dynamic match, evaluate the ScriptBlock
                if (matchType == SuggestionMatchType.Dynamic)
                {
                    object result = null;

                    ScriptBlock evaluator = suggestion["Rule"] as ScriptBlock;
                    if (evaluator == null)
                    {
                        suggestion["Enabled"] = false;

                        throw new ArgumentException(
                                  SuggestionStrings.RuleMustBeScriptBlock, "Rule");
                    }

                    try
                    {
                        result = invocationModule.Invoke(evaluator, null);
                    }
                    catch (Exception)
                    {
                        // Catch-all OK. This is a third-party call-out.
                        suggestion["Enabled"] = false;
                        continue;
                    }

                    // If it returned results, evaluate its suggestion
                    if (LanguagePrimitives.IsTrue(result))
                    {
                        string suggestionText = GetSuggestionText(suggestion["Suggestion"], (object[])suggestion["SuggestionArgs"], invocationModule);

                        if (!string.IsNullOrEmpty(suggestionText))
                        {
                            string returnString = string.Format(
                                CultureInfo.CurrentCulture,
                                "Suggestion [{0},{1}]: {2}",
                                (int)suggestion["Id"],
                                (string)suggestion["Category"],
                                suggestionText);

                            returnSuggestions.Add(returnString);
                        }
                    }
                }
                else
                {
                    string matchText = string.Empty;

                    // Otherwise, this is a Regex match against the
                    // command or error
                    if (matchType == SuggestionMatchType.Command)
                    {
                        matchText = lastHistory.CommandLine;
                    }
                    else if (matchType == SuggestionMatchType.Error)
                    {
                        if (lastError != null)
                        {
                            Exception lastException = lastError as Exception;
                            if (lastException != null)
                            {
                                matchText = lastException.Message;
                            }
                            else
                            {
                                matchText = lastError.ToString();
                            }
                        }
                    }
                    else if (matchType == SuggestionMatchType.ErrorId)
                    {
                        if (lastError != null && lastError is ErrorRecord errorRecord)
                        {
                            matchText = errorRecord.FullyQualifiedErrorId;
                        }
                    }
                    else
                    {
                        suggestion["Enabled"] = false;

                        throw new ArgumentException(
                                  SuggestionStrings.InvalidMatchType,
                                  "MatchType");
                    }

                    // If the text matches, evaluate the suggestion
                    if (Regex.IsMatch(matchText, (string)suggestion["Rule"], RegexOptions.IgnoreCase))
                    {
                        string suggestionText = GetSuggestionText(suggestion["Suggestion"], (object[])suggestion["SuggestionArgs"], invocationModule);

                        if (!string.IsNullOrEmpty(suggestionText))
                        {
                            string returnString = string.Format(
                                CultureInfo.CurrentCulture,
                                "Suggestion [{0},{1}]: {2}",
                                (int)suggestion["Id"],
                                (string)suggestion["Category"],
                                suggestionText);

                            returnSuggestions.Add(returnString);
                        }
                    }
                }

                // If the rule generated an error, disable it
                if (errorList.Count != initialErrorCount)
                {
                    suggestion["Enabled"] = false;
                }
            }

            return(returnSuggestions);
        }
Пример #27
0
 internal void SetModule(PSModuleInfo module)
 {
     Module = module;
 }
Пример #28
0
        private PSModuleInfo CreateModuleImplementation(
            string name,
            string path,
            object moduleCode,
            Token callerToken,
            SessionState ss,
            out ArrayList result,
            params object[] arguments)
        {
            if (ss == null)
            {
                ss = new SessionState(this._context.EngineSessionState, true, true);
            }
            SessionStateInternal engineSessionState = this._context.EngineSessionState;
            PSModuleInfo         psModuleInfo       = new PSModuleInfo(name, path, this._context, ss);

            ss.Internal.Module = psModuleInfo;
            bool flag = false;
            int  num  = 0;

            try
            {
                ArrayList resultList = (ArrayList)null;
                this._context.EngineSessionState = ss.Internal;
                this._context.EngineSessionState.SetVariableValue("PSScriptRoot", (object)Path.GetDirectoryName(path), CommandOrigin.Internal);
                switch (moduleCode)
                {
                case ExternalScriptInfo externalScriptInfo:
                    this._context.EngineSessionState.SetVariableValue("MyInvocation", (object)new InvocationInfo((CommandInfo)externalScriptInfo, callerToken), CommandOrigin.Internal);
                    scriptBlock = externalScriptInfo.ScriptBlock;
                    break;

                case ScriptBlock scriptBlock:
                    scriptBlock = scriptBlock.Clone(true);
                    scriptBlock.SessionState = ss;
                    break;

                case string _:
                    scriptBlock = ScriptBlock.Create(this._context, (string)moduleCode);
                    break;
                }
                if (scriptBlock == null)
                {
                    throw ModuleIntrinsics.tracer.NewInvalidOperationException();
                }
                scriptBlock.SessionStateInternal = ss.Internal;
                try
                {
                    if (arguments == null)
                    {
                        scriptBlock.InvokeWithPipe(false, true, (object)AutomationNull.Value, (object)AutomationNull.Value, (object)AutomationNull.Value, (Pipe)null, ref resultList);
                    }
                    else
                    {
                        scriptBlock.InvokeWithPipe(false, true, (object)AutomationNull.Value, (object)AutomationNull.Value, (object)AutomationNull.Value, (Pipe)null, ref resultList, arguments);
                    }
                }
                catch (ExitException ex)
                {
                    num  = (int)ex.Argument;
                    flag = true;
                }
                result = resultList;
            }
            finally
            {
                this._context.EngineSessionState = engineSessionState;
            }
            if (flag)
            {
                this._context.SetVariable("global:LASTEXITCODE", (object)num);
            }
            return(psModuleInfo);
        }
Пример #29
0
        /// <summary>
        /// Check if the given path is valid.
        /// </summary>
        /// <param name="path"></param>
        /// <param name="module"></param>
        /// <param name="verifyPathScope"></param>
        /// <returns></returns>
        private bool IsValidFilePath(string path, PSModuleInfo module, bool verifyPathScope)
        {
            try
            {
                if (!System.IO.Path.IsPathRooted(path))
                {
                    // we assume the relative path is under module scope, otherwise we will throw error anyway.
                    path = System.IO.Path.GetFullPath(module.ModuleBase + "\\" + path);
                }

                // First, we validate if the path  does exist.
                if (!File.Exists(path) && !Directory.Exists(path))
                {
                    return false;
                }

                //Then, we validate if the path is under module scope
                if (verifyPathScope && !System.IO.Path.GetFullPath(path).StartsWith(System.IO.Path.GetFullPath(module.ModuleBase), StringComparison.OrdinalIgnoreCase))
                {
                    return false;
                }
            }
            catch (Exception exception)
            {
                if (exception is ArgumentException || exception is ArgumentNullException || exception is NotSupportedException || exception is PathTooLongException)
                {
                    return false;
                }
            }

            return true;
        }
Пример #30
0
 internal void ReportExportedCommands(PSModuleInfo moduleInfo)
 {
     if (moduleInfo.ExportedCommands.Count == 0)
     {
         moduleInfo.DeclaredAliasExports = new Collection<string>();
         moduleInfo.DeclaredFunctionExports = new Collection<string>();
         IEnumerable<CommonCmdletMetadata> collection = Enumerable.Empty<CommonCmdletMetadata>();
         if (this.cmdletizationMetadata.Class.InstanceCmdlets != null)
         {
             collection = collection.Append<CommonCmdletMetadata>(this.GetGetCmdletMetadata());
             if (this.cmdletizationMetadata.Class.InstanceCmdlets.Cmdlet != null)
             {
                 collection = collection.Concat<CommonCmdletMetadata>(from c in this.cmdletizationMetadata.Class.InstanceCmdlets.Cmdlet select c.CmdletMetadata);
             }
         }
         if (this.cmdletizationMetadata.Class.StaticCmdlets != null)
         {
             collection = collection.Concat<CommonCmdletMetadata>((IEnumerable<CommonCmdletMetadata>) (from c in this.cmdletizationMetadata.Class.StaticCmdlets select c.CmdletMetadata));
         }
         foreach (CommonCmdletMetadata metadata in collection)
         {
             if (metadata.Aliases != null)
             {
                 foreach (string str in metadata.Aliases)
                 {
                     moduleInfo.DeclaredAliasExports.Add(str);
                 }
             }
             CommandMetadata commandMetadata = this.GetCommandMetadata(metadata);
             moduleInfo.DeclaredFunctionExports.Add(commandMetadata.Name);
         }
     }
 }
 internal static void AssociatePSModuleInfoWithSession(PSModuleInfo moduleInfo, CimSession cimSession, Uri resourceUri, string cimNamespace)
 {
     AssociatePSModuleInfoWithSession(moduleInfo, (object)new Tuple <CimSession, Uri, string>(cimSession, resourceUri, cimNamespace));
 }
Пример #32
0
 /// <summary>
 /// Determine whether a module info matches a given module specification table and specified PSEdition value.
 /// </summary>
 /// <param name="moduleInfo"></param>
 /// <param name="moduleSpecTable"></param>
 /// <param name="edition"></param>
 /// <returns></returns>
 private static bool ModuleMatch(PSModuleInfo moduleInfo, IDictionary<string, ModuleSpecification> moduleSpecTable, string edition)
 {
     ModuleSpecification moduleSpecification;
     return (String.IsNullOrEmpty(edition) || moduleInfo.CompatiblePSEditions.Contains(edition, StringComparer.OrdinalIgnoreCase)) &&
            (!moduleSpecTable.TryGetValue(moduleInfo.Name, out moduleSpecification) || ModuleIntrinsics.IsModuleMatchingModuleSpec(moduleInfo, moduleSpecification));
 }
 internal static void AssociatePSModuleInfoWithSession(PSModuleInfo moduleInfo, PSSession psSession)
 {
     AssociatePSModuleInfoWithSession(moduleInfo, (object)psSession);
 }
Пример #34
0
        private bool ModuleProvidesCurrentSessionDrive(PSModuleInfo module)
        {
            if (module.ModuleType == ModuleType.Binary)
            {
                Dictionary<string, List<ProviderInfo>> providers = Context.TopLevelSessionState.Providers;
                foreach (KeyValuePair<string, List<ProviderInfo>> pList in providers)
                {
                    Dbg.Assert(pList.Value != null, "There should never be a null list of entries in the provider table");
                    foreach (ProviderInfo pInfo in pList.Value)
                    {
                        string implTypeAssemblyLocation = pInfo.ImplementingType.GetTypeInfo().Assembly.Location;
                        if (implTypeAssemblyLocation.Equals(module.Path, StringComparison.OrdinalIgnoreCase))
                        {
                            foreach (PSDriveInfo dInfo in Context.TopLevelSessionState.GetDrivesForProvider(pInfo.FullName))
                            {
                                if (dInfo == SessionState.Drive.Current)
                                {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }

            return false;
        }
Пример #35
0
 internal void SetModule(PSModuleInfo module) => this._module = module;
Пример #36
0
        private void ImportModule_ViaLocalModuleInfo(ImportModuleOptions importModuleOptions, PSModuleInfo module)
        {
            try
            {
                PSModuleInfo alreadyLoadedModule = null;
                Context.Modules.ModuleTable.TryGetValue(module.Path, out alreadyLoadedModule);
                if (!BaseForce && IsModuleAlreadyLoaded(alreadyLoadedModule))
                {
                    AddModuleToModuleTables(this.Context, this.TargetSessionState.Internal, alreadyLoadedModule);

                    // Even if the module has been loaded, import the specified members...
                    ImportModuleMembers(alreadyLoadedModule, this.BasePrefix, importModuleOptions);

                    if (BaseAsCustomObject)
                    {
                        if (alreadyLoadedModule.ModuleType != ModuleType.Script)
                        {
                            string message = StringUtil.Format(Modules.CantUseAsCustomObjectWithBinaryModule, alreadyLoadedModule.Path);
                            InvalidOperationException invalidOp = new InvalidOperationException(message);
                            ErrorRecord er = new ErrorRecord(invalidOp, "Modules_CantUseAsCustomObjectWithBinaryModule",
                                                             ErrorCategory.PermissionDenied, null);
                            WriteError(er);
                        }
                        else
                        {
                            WriteObject(alreadyLoadedModule.AsCustomObject());
                        }
                    }
                    else if (BasePassThru)
                    {
                        WriteObject(alreadyLoadedModule);
                    }
                }
                else
                {
                    PSModuleInfo moduleToRemove;
                    if (Context.Modules.ModuleTable.TryGetValue(module.Path, out moduleToRemove))
                    {
                        Dbg.Assert(BaseForce, "We should only remove and reload if -Force was specified");
                        RemoveModule(moduleToRemove);
                    }

                    PSModuleInfo moduleToProcess = module;
                    try
                    {
                        // If we're passing in a dynamic module, then the session state will not be
                        // null and we want to just add the module to the module table. Otherwise, it's
                        // a module info from Get-Module -list so we need to read the actual module file.
                        if (module.SessionState == null)
                        {
                            if (File.Exists(module.Path))
                            {
                                bool found;
                                moduleToProcess = LoadModule(module.Path, null, this.BasePrefix, /*SessionState*/ null,
                                                             ref importModuleOptions,
                                                             ManifestProcessingFlags.LoadElements | ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.NullOnFirstError,
                                                             out found);
                                Dbg.Assert(found, "Module should be found when referenced by its absolute path");
                            }
                        }
                        else if (!string.IsNullOrEmpty(module.Name))
                        {
                            // It has a session state and a name but it's not in the module
                            // table so it's ok to add it

                            // Add it to the all module tables
                            AddModuleToModuleTables(this.Context, this.TargetSessionState.Internal, moduleToProcess);

                            if (moduleToProcess.SessionState != null)
                            {
                                ImportModuleMembers(moduleToProcess, this.BasePrefix, importModuleOptions);
                            }

                            if (BaseAsCustomObject && moduleToProcess.SessionState != null)
                            {
                                WriteObject(module.AsCustomObject());
                            }
                            else if (BasePassThru)
                            {
                                WriteObject(moduleToProcess);
                            }
                        }
                    }
                    catch (IOException)
                    {
                        ;
                    }
                }
            }
            catch (PSInvalidOperationException e)
            {
                ErrorRecord er = new ErrorRecord(e.ErrorRecord, e);
                WriteError(er);
            }
        }
Пример #37
0
        internal ScriptBlock CreateBoundScriptBlock(ExecutionContext context, ScriptBlock sb, bool linkToGlobal)
        {
            PSModuleInfo info = new PSModuleInfo(context, linkToGlobal);

            return(info.NewBoundScriptBlock(sb, context));
        }
Пример #38
0
 internal void AddNestedModule(PSModuleInfo nestedModule)
 {
     AddModuleToList(nestedModule, this._nestedModules);
 }
Пример #39
0
 internal void SetModule(PSModuleInfo module)
 {
     Module = module;
     _fullName = null;
 }
Пример #40
0
 internal static void SetDefaultDynamicNameAndPath(PSModuleInfo module)
 {
     string str = System.Guid.NewGuid().ToString();
     module._path = str;
     module._name = "__DynamicModule_" + str;
 }
Пример #41
0
        /// <summary>
        /// Invoke command Get-DscResource with resource name to find the resource.
        /// When found add them to the enumerator. If we have already got it, return the next resource.
        /// </summary>
        /// <returns>Next DscResource Info object or null if none are found.</returns>
        private DscResourceInfo GetNextDscResource()
        {
            var ps = PowerShell.Create(RunspaceMode.CurrentRunspace).AddCommand("Get-DscResource");

            WildcardPattern resourceMatcher = WildcardPattern.Get(_resourceName, WildcardOptions.IgnoreCase);

            if (_matchingResourceList == null)
            {
                Collection <PSObject> psObjs = ps.Invoke();

                _matchingResourceList = new Collection <DscResourceInfo>();

                bool matchFound = false;

                foreach (dynamic resource in psObjs)
                {
                    if (resource.Name != null)
                    {
                        string resourceName = resource.Name;

                        if (resourceMatcher.IsMatch(resourceName))
                        {
                            DscResourceInfo resourceInfo = new DscResourceInfo(resourceName,
                                                                               resource.ResourceType,
                                                                               resource.Path,
                                                                               resource.ParentPath,
                                                                               _context
                                                                               );


                            resourceInfo.FriendlyName = resource.FriendlyName;

                            resourceInfo.CompanyName = resource.CompanyName;

                            PSModuleInfo psMod = resource.Module as PSModuleInfo;

                            if (psMod != null)
                            {
                                resourceInfo.Module = psMod;
                            }

                            if (resource.ImplementedAs != null)
                            {
                                ImplementedAsType impType;
                                if (Enum.TryParse <ImplementedAsType>(resource.ImplementedAs.ToString(), out impType))
                                {
                                    resourceInfo.ImplementedAs = impType;
                                }
                            }

                            var properties = resource.Properties as IList;

                            if (properties != null)
                            {
                                List <DscResourcePropertyInfo> propertyList = new List <DscResourcePropertyInfo>();

                                foreach (dynamic prop in properties)
                                {
                                    DscResourcePropertyInfo propInfo = new DscResourcePropertyInfo();
                                    propInfo.Name         = prop.Name;
                                    propInfo.PropertyType = prop.PropertyType;
                                    propInfo.UpdateValues(prop.Values);

                                    propertyList.Add(propInfo);
                                }

                                resourceInfo.UpdateProperties(propertyList);
                            }

                            _matchingResourceList.Add(resourceInfo);

                            matchFound = true;
                        } //if
                    }     //if
                }         // foreach

                if (matchFound)
                {
                    _matchingResource = _matchingResourceList.GetEnumerator();
                }
                else
                {
                    return(null);
                }
            }//if

            if (!_matchingResource.MoveNext())
            {
                _matchingResource = null;
            }
            else
            {
                return(_matchingResource.Current);
            }

            return(null);
        }
Пример #42
0
        private PSModuleInfo CreateModuleImplementation(string name, string path, object moduleCode, IScriptExtent scriptPosition, SessionState ss, object privateData, out ArrayList result, params object[] arguments)
        {
            if (ss == null)
            {
                ss = new SessionState(this._context, true, true);
            }
            SessionStateInternal engineSessionState = this._context.EngineSessionState;
            PSModuleInfo         info = new PSModuleInfo(name, path, this._context, ss);

            ss.Internal.Module = info;
            info.PrivateData   = privateData;
            bool flag     = false;
            int  newValue = 0;

            try
            {
                ScriptBlock scriptBlock;
                this._context.EngineSessionState = ss.Internal;
                ExternalScriptInfo scriptCommandInfo = moduleCode as ExternalScriptInfo;
                if (scriptCommandInfo != null)
                {
                    scriptBlock = scriptCommandInfo.ScriptBlock;
                    this._context.Debugger.RegisterScriptFile(scriptCommandInfo);
                }
                else
                {
                    scriptBlock = moduleCode as ScriptBlock;
                    if (scriptBlock != null)
                    {
                        PSLanguageMode?languageMode = scriptBlock.LanguageMode;
                        scriptBlock = scriptBlock.Clone(true);
                        scriptBlock.LanguageMode = languageMode;
                        scriptBlock.SessionState = ss;
                    }
                    else if (moduleCode is string)
                    {
                        scriptBlock = ScriptBlock.Create(this._context, (string)moduleCode);
                    }
                }
                if (scriptBlock == null)
                {
                    throw PSTraceSource.NewInvalidOperationException();
                }
                scriptBlock.SessionStateInternal = ss.Internal;
                InvocationInfo invocationInfo = new InvocationInfo(scriptCommandInfo, scriptPosition);
                info._definitionExtent = scriptBlock.Ast.Extent;
                ArrayList resultList = new ArrayList();
                try
                {
                    Pipe outputPipe = new Pipe(resultList);
                    scriptBlock.InvokeWithPipe(false, ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, AutomationNull.Value, AutomationNull.Value, AutomationNull.Value, outputPipe, invocationInfo, arguments ?? new object[0]);
                }
                catch (ExitException exception)
                {
                    newValue = (int)exception.Argument;
                    flag     = true;
                }
                result = resultList;
            }
            finally
            {
                this._context.EngineSessionState = engineSessionState;
            }
            if (flag)
            {
                this._context.SetVariable(SpecialVariables.LastExitCodeVarPath, newValue);
            }
            return(info);
        }
Пример #43
0
 internal void AddRequiredModule(PSModuleInfo requiredModule)
 {
     AddModuleToList(requiredModule, this._requiredModules);
 }
Пример #44
0
 internal void SetModule(PSModuleInfo module)
 {
     this._module = module;
 }
Пример #45
0
 internal void AddNestedModule(PSModuleInfo nestedModule)
 {
     AddModuleToList(nestedModule, this._nestedModules);
 }
Пример #46
0
 internal void PopulatePSModuleInfo(PSModuleInfo moduleInfo)
 {
     moduleInfo.SetModuleType(ModuleType.Cim);
     moduleInfo.SetVersion(new Version(this.cmdletizationMetadata.Class.Version));
     Hashtable hashtable = new Hashtable(StringComparer.OrdinalIgnoreCase);
     hashtable.Add("ClassName", this.cmdletizationMetadata.Class.ClassName);
     hashtable.Add("CmdletAdapter", this.objectModelWrapper);
     Hashtable hashtable2 = new Hashtable(StringComparer.OrdinalIgnoreCase);
     hashtable2.Add("CmdletsOverObjects", hashtable);
     moduleInfo.PrivateData = hashtable2;
 }
Пример #47
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");
            }        
        }
 private static void AssociatePSModuleInfoWithSession(PSModuleInfo moduleInfo, object weaklyTypedSession)
 {
     s_moduleInfoToSession.Add(moduleInfo, weaklyTypedSession);
 }
Пример #49
0
        internal CmdletInfo(string name, Type implementingType, string helpFile, PSSnapInInfo snapin, PSModuleInfo module)
            : base(name, CommandTypes.Cmdlet)
        {
            int i = name.IndexOf('-');

            if (i == -1)
            {
                throw new Exception("InvalidCmdletNameFormat " + name);
            }
            ParameterInfoLookupTable = new Dictionary <string, CommandParameterInfo>(StringComparer.CurrentCultureIgnoreCase);
            Verb                 = name.Substring(0, i);
            Noun                 = name.Substring(i + 1);
            ImplementingType     = implementingType;
            HelpFile             = helpFile;
            _validationException = null;
            PSSnapIn             = snapin;
            Module               = module;
            GetParameterSetInfo(implementingType);
            GetOutputTypes(implementingType);
        }
        private ScriptFile[] GetBuiltinCommandScriptFiles(
            PSModuleInfo moduleInfo,
            Workspace workspace)
        {
            // if there is module info for this command
            if (moduleInfo != null)
            {
                string modPath = moduleInfo.Path;
                List<ScriptFile> scriptFiles = new List<ScriptFile>();
                ScriptFile newFile;

                // find any files where the moduleInfo's path ends with ps1 or psm1
                // and add it to allowed script files
                if (modPath.EndsWith(@".ps1") || modPath.EndsWith(@".psm1"))
                {
                    newFile = workspace.GetFile(modPath);
                    newFile.IsAnalysisEnabled = false;
                    scriptFiles.Add(newFile);
                }
                if (moduleInfo.NestedModules.Count > 0)
                {
                    foreach (PSModuleInfo nestedInfo in moduleInfo.NestedModules)
                    {
                        string nestedModPath = nestedInfo.Path;
                        if (nestedModPath.EndsWith(@".ps1") || nestedModPath.EndsWith(@".psm1"))
                        {
                            newFile = workspace.GetFile(nestedModPath);
                            newFile.IsAnalysisEnabled = false;
                            scriptFiles.Add(newFile);
                        }
                    }
                }

                return scriptFiles.ToArray();
            }

            return new List<ScriptFile>().ToArray();
        }
Пример #51
0
        private List <PSModuleInfo> GetModuleCore(string[] patterns, bool all, bool exactMatch)
        {
            string str = null;
            List <WildcardPattern> list = new List <WildcardPattern>();

            if (exactMatch)
            {
                str = patterns[0];
            }
            else
            {
                if (patterns == null)
                {
                    patterns = new string[] { "*" };
                }
                foreach (string str2 in patterns)
                {
                    list.Add(new WildcardPattern(str2, WildcardOptions.IgnoreCase));
                }
            }
            List <PSModuleInfo> list2 = new List <PSModuleInfo>();

            if (all)
            {
                foreach (string str3 in this.ModuleTable.Keys)
                {
                    PSModuleInfo item = this.ModuleTable[str3];
                    if ((exactMatch && item.Name.Equals(str, StringComparison.OrdinalIgnoreCase)) || (!exactMatch && SessionStateUtilities.MatchesAnyWildcardPattern(item.Name, list, false)))
                    {
                        list2.Add(item);
                    }
                }
            }
            else
            {
                Dictionary <string, bool> dictionary = new Dictionary <string, bool>(StringComparer.OrdinalIgnoreCase);
                foreach (string str4 in this._context.EngineSessionState.ModuleTable.Keys)
                {
                    PSModuleInfo info2 = this._context.EngineSessionState.ModuleTable[str4];
                    if ((exactMatch && info2.Name.Equals(str, StringComparison.OrdinalIgnoreCase)) || (!exactMatch && SessionStateUtilities.MatchesAnyWildcardPattern(info2.Name, list, false)))
                    {
                        list2.Add(info2);
                        dictionary[str4] = true;
                    }
                }
                if (this._context.EngineSessionState != this._context.TopLevelSessionState)
                {
                    foreach (string str5 in this._context.TopLevelSessionState.ModuleTable.Keys)
                    {
                        if (!dictionary.ContainsKey(str5))
                        {
                            PSModuleInfo info3 = this.ModuleTable[str5];
                            if ((exactMatch && info3.Name.Equals(str, StringComparison.OrdinalIgnoreCase)) || (!exactMatch && SessionStateUtilities.MatchesAnyWildcardPattern(info3.Name, list, false)))
                            {
                                list2.Add(info3);
                            }
                        }
                    }
                }
            }
            return((from m in list2
                    orderby m.Name
                    select m).ToList <PSModuleInfo>());
        }