Exemplo n.º 1
0
        private MamlCommandHelpInfo GetFromCommandCacheByRemovingPrefix(string helpIdentifier, CommandInfo cmdInfo)
        {
            MamlCommandHelpInfo info  = null;
            MamlCommandHelpInfo info2 = this.GetFromCommandCache(helpIdentifier, ModuleCmdletBase.RemovePrefixFromCommandName(cmdInfo.Name, cmdInfo.Prefix), cmdInfo.HelpCategory) as MamlCommandHelpInfo;

            if (info2 != null)
            {
                info = info2.Copy();
                if (info.FullHelp.Properties["Name"] != null)
                {
                    info.FullHelp.Properties.Remove("Name");
                }
                info.FullHelp.Properties.Add(new PSNoteProperty("Name", cmdInfo.Name));
                if ((info.FullHelp.Properties["Details"] == null) || (info.FullHelp.Properties["Details"].Value == null))
                {
                    return(info);
                }
                PSObject obj2 = PSObject.AsPSObject(info.FullHelp.Properties["Details"].Value).Copy();
                if (obj2.Properties["Name"] != null)
                {
                    obj2.Properties.Remove("Name");
                }
                obj2.Properties.Add(new PSNoteProperty("Name", cmdInfo.Name));
                info.FullHelp.Properties["Details"].Value = obj2;
            }
            return(info);
        }
Exemplo n.º 2
0
        private bool IsShadowingExistingCommands(string commandName)
        {
            commandName = ModuleCmdletBase.AddPrefixToCommandName(commandName, this.Prefix);
            CommandSearcher searcher = new CommandSearcher(commandName, SearchResolutionOptions.None, CommandTypes.All, base.Context);

            foreach (string str in searcher.ConstructSearchPatternsFromName(commandName))
            {
                if (this.ExistingCommands.ContainsKey(str))
                {
                    return(true);
                }
            }
            return(false);
        }
Exemplo n.º 3
0
 internal PSModuleInfo(
     string name,
     string path,
     ExecutionContext context,
     SessionState sessionState)
 {
     this._context = context;
     if (path != null)
     {
         string resolvedPath = ModuleCmdletBase.GetResolvedPath(path, this._context);
         this._path = resolvedPath == null ? path : resolvedPath;
     }
     this._name         = name != null || this._path == null ? name : ModuleIntrinsics.GetModuleName(this._path);
     this._sessionState = sessionState;
     if (sessionState == null)
     {
         return;
     }
     sessionState.Internal.Module = this;
 }
Exemplo n.º 4
0
 internal PSModuleInfo(string name, string path, ExecutionContext context, System.Management.Automation.SessionState sessionState)
 {
     this._name                         = string.Empty;
     this._path                         = string.Empty;
     this._description                  = string.Empty;
     this._version                      = new System.Version(0, 0);
     this._detectedFunctionExports      = new List <string>();
     this._detectedWorkflowExports      = new List <string>();
     this._detectedCmdletExports        = new List <string>();
     this._compiledExports              = new List <CmdletInfo>();
     this._fileList                     = new List <string>();
     this._moduleList                   = new Collection <object>();
     this._nestedModules                = new List <PSModuleInfo>();
     this._scripts                      = new List <string>();
     this._requiredAssemblies           = new Collection <string>();
     this._requiredModules              = new List <PSModuleInfo>();
     this._requiredModulesSpecification = new List <ModuleSpecification>();
     this._detectedAliasExports         = new Dictionary <string, string>();
     this._exportedFormatFiles          = new ReadOnlyCollection <string>(new List <string>());
     this._exportedTypeFiles            = new ReadOnlyCollection <string>(new List <string>());
     if (path != null)
     {
         string resolvedPath = ModuleCmdletBase.GetResolvedPath(path, context);
         this._path = resolvedPath ?? path;
     }
     this._sessionState = sessionState;
     if (sessionState != null)
     {
         sessionState.Internal.Module = this;
     }
     if (name == null)
     {
         this._name = ModuleIntrinsics.GetModuleName(this._path);
     }
     else
     {
         this._name = name;
     }
 }
Exemplo n.º 5
0
 private void ProcessImportModule(IEnumerable moduleList, bool startLifeCycleEventWritten)
 {
     foreach (object obj2 in moduleList)
     {
         string name = obj2 as string;
         if (name != null)
         {
             this.ProcessImportModule(name, null, startLifeCycleEventWritten);
         }
         else
         {
             ModuleSpecification requiredModule = obj2 as ModuleSpecification;
             if (requiredModule != null)
             {
                 if ((requiredModule.Version == null) && !requiredModule.Guid.HasValue)
                 {
                     this.ProcessImportModule(requiredModule.Name, null, startLifeCycleEventWritten);
                 }
                 else
                 {
                     Collection <PSModuleInfo> moduleIfAvailable = ModuleCmdletBase.GetModuleIfAvailable(requiredModule, this);
                     if ((moduleIfAvailable != null) && (moduleIfAvailable.Count > 0))
                     {
                         foreach (PSModuleInfo info in moduleIfAvailable)
                         {
                             this.ProcessImportModule(requiredModule.Name, info, startLifeCycleEventWritten);
                         }
                     }
                     else
                     {
                         RunspaceOpenModuleLoadException exception = new RunspaceOpenModuleLoadException(StringUtil.Format(Modules.RequiredModuleNotFoundWrongGuidVersion, new object[] { requiredModule.Name, requiredModule.Guid, (requiredModule.Version == null) ? "0.0.0.0" : requiredModule.Version.ToString() }));
                         this.ValidateAndThrowRunspaceOpenModuleLoadException(null, null, startLifeCycleEventWritten, requiredModule.Name, exception);
                     }
                 }
             }
         }
     }
 }
Exemplo n.º 6
0
        internal static DirectoryInfo CreateModuleDirectory(PSCmdlet cmdlet, string moduleNameOrPath, bool force)
        {
            DirectoryInfo targetObject = null;

            try
            {
                string str = ModuleCmdletBase.ResolveRootedFilePath(moduleNameOrPath, cmdlet.Context);
                if (string.IsNullOrEmpty(str) && moduleNameOrPath.StartsWith(".", StringComparison.OrdinalIgnoreCase))
                {
                    str = Path.Combine(cmdlet.CurrentProviderLocation(cmdlet.Context.ProviderNames.FileSystem).ProviderPath, moduleNameOrPath);
                }
                if (string.IsNullOrEmpty(str))
                {
                    str = Path.Combine(ModuleIntrinsics.GetPersonalModulePath(), moduleNameOrPath);
                }
                targetObject = new DirectoryInfo(str);
                if (targetObject.Exists)
                {
                    if (!force)
                    {
                        ErrorDetails details     = new ErrorDetails(string.Format(CultureInfo.InvariantCulture, PathUtilsStrings.ExportPSSession_ErrorDirectoryExists, new object[] { targetObject.FullName }));
                        ErrorRecord  errorRecord = new ErrorRecord(new ArgumentException(details.Message), "ExportProxyCommand_OutputDirectoryExists", ErrorCategory.ResourceExists, targetObject);
                        cmdlet.ThrowTerminatingError(errorRecord);
                    }
                    return(targetObject);
                }
                targetObject.Create();
            }
            catch (Exception exception)
            {
                CommandProcessorBase.CheckForSevereException(exception);
                ErrorDetails details2 = new ErrorDetails(string.Format(CultureInfo.InvariantCulture, PathUtilsStrings.ExportPSSession_CannotCreateOutputDirectory, new object[] { moduleNameOrPath, exception.Message }));
                ErrorRecord  record2  = new ErrorRecord(new ArgumentException(details2.Message, exception), "ExportProxyCommand_CannotCreateOutputDirectory", ErrorCategory.ResourceExists, moduleNameOrPath);
                cmdlet.ThrowTerminatingError(record2);
            }
            return(targetObject);
        }
Exemplo n.º 7
0
 private void ImportModule_ViaAssembly(ModuleCmdletBase.ImportModuleOptions importModuleOptions, System.Reflection.Assembly suppliedAssembly)
 {
     bool flag = false;
     if ((suppliedAssembly != null) && (base.Context.Modules.ModuleTable != null))
     {
         foreach (KeyValuePair<string, PSModuleInfo> pair in base.Context.Modules.ModuleTable)
         {
             if (pair.Value.Path.Equals(suppliedAssembly.Location, StringComparison.OrdinalIgnoreCase))
             {
                 flag = true;
                 break;
             }
         }
     }
     if (!flag)
     {
         bool flag2;
         PSModuleInfo module = base.LoadBinaryModule(false, null, null, suppliedAssembly, null, null, importModuleOptions, ModuleCmdletBase.ManifestProcessingFlags.LoadElements | ModuleCmdletBase.ManifestProcessingFlags.NullOnFirstError | ModuleCmdletBase.ManifestProcessingFlags.WriteErrors, base.BasePrefix, false, false, out flag2);
         if (flag2 && (module != null))
         {
             ModuleCmdletBase.AddModuleToModuleTables(base.Context, base.TargetSessionState.Internal, module);
         }
     }
 }
Exemplo n.º 8
0
 private PSModuleInfo ImportModule_RemotelyViaPsrpSession_SinglePreimportedModule(ModuleCmdletBase.ImportModuleOptions importModuleOptions, string remoteModuleName, Version remoteModuleVersion, System.Management.Automation.Runspaces.PSSession psSession)
 {
     PSModuleInfo info3;
     string pattern = RemoteDiscoveryHelper.GetModulePath(remoteModuleName, remoteModuleVersion, psSession.ComputerName, base.Context.CurrentRunspace);
     string str2 = WildcardPattern.Escape(pattern);
     try
     {
         PSModuleInfo info2;
         string modulePath = Path.Combine(pattern, Path.GetFileName(pattern) + ".psm1");
         PSModuleInfo info = base.IsModuleImportUnnecessaryBecauseModuleIsAlreadyLoaded(modulePath, base.BasePrefix, importModuleOptions);
         if (info != null)
         {
             return info;
         }
         using (PowerShell shell = PowerShell.Create(RunspaceMode.CurrentRunspace))
         {
             shell.AddCommand("Export-PSSession");
             shell.AddParameter("OutputModule", str2);
             shell.AddParameter("AllowClobber", true);
             shell.AddParameter("Module", remoteModuleName);
             shell.AddParameter("Force", true);
             shell.AddParameter("FormatTypeName", "*");
             shell.AddParameter("Session", psSession);
             string errorMessageTemplate = string.Format(CultureInfo.InvariantCulture, Modules.RemoteDiscoveryFailedToGenerateProxyForRemoteModule, new object[] { remoteModuleName });
             if (RemoteDiscoveryHelper.InvokePowerShell(shell, this.CancellationToken, this, errorMessageTemplate).Count<PSObject>() == 0)
             {
                 return null;
             }
         }
         string destFileName = Path.Combine(pattern, remoteModuleName + ".psd1");
         File.Move(Path.Combine(pattern, Path.GetFileName(pattern) + ".psd1"), destFileName);
         string name = WildcardPattern.Escape(destFileName);
         object[] argumentList = this.ArgumentList;
         try
         {
             this.ArgumentList = new object[] { psSession };
             this.ImportModule_LocallyViaName(importModuleOptions, name);
         }
         finally
         {
             this.ArgumentList = argumentList;
         }
         Path.GetFileName(pattern);
         string key = Path.Combine(pattern, Path.GetFileName(pattern) + ".psm1");
         if (!base.Context.Modules.ModuleTable.TryGetValue(key, out info2))
         {
             if (Directory.Exists(pattern))
             {
                 Directory.Delete(pattern, true);
             }
             return null;
         }
         ScriptBlock newClosure = base.Context.Engine.ParseScriptBlock("\r\n                    Microsoft.PowerShell.Management\\Remove-Item `\r\n                        -LiteralPath $temporaryModulePath `\r\n                        -Force `\r\n                        -Recurse `\r\n                        -ErrorAction SilentlyContinue\r\n\r\n                    if ($previousOnRemoveScript -ne $null)\r\n                    {\r\n                        & $previousOnRemoveScript $args\r\n                    }\r\n                    ", false).GetNewClosure();
         newClosure.Module.SessionState.PSVariable.Set("temporaryModulePath", pattern);
         newClosure.Module.SessionState.PSVariable.Set("previousOnRemoveScript", info2.OnRemove);
         info2.OnRemove = newClosure;
         info3 = info2;
     }
     catch
     {
         if (Directory.Exists(pattern))
         {
             Directory.Delete(pattern, true);
         }
         throw;
     }
     return info3;
 }
Exemplo n.º 9
0
 private static void SetSnapInLoggingInformation(PSSnapInInfo psSnapInInfo)
 {
     foreach (ExecutionPolicyScope scope in SecuritySupport.ExecutionPolicyScopePreferences)
     {
         IEnumerable <string> enumerable;
         ModuleCmdletBase.ModuleLoggingGroupPolicyStatus moduleLoggingInformation = ModuleCmdletBase.GetModuleLoggingInformation(scope, out enumerable);
         if (moduleLoggingInformation != ModuleCmdletBase.ModuleLoggingGroupPolicyStatus.Undefined)
         {
             SetSnapInLoggingInformation(psSnapInInfo, moduleLoggingInformation, enumerable);
             return;
         }
     }
 }
Exemplo n.º 10
0
        /// <summary>
        /// Initialize moduleSpecification from hashtable. Return exception object, if hashtable cannot be converted.
        /// Return null, in the success case.
        /// </summary>
        /// <param name="moduleSpecification">Object to initialize.</param>
        /// <param name="hashtable">Contains info about object to initialize.</param>
        /// <returns></returns>
        internal static Exception ModuleSpecificationInitHelper(ModuleSpecification moduleSpecification, Hashtable hashtable)
        {
            StringBuilder badKeys = new StringBuilder();

            try
            {
                foreach (DictionaryEntry entry in hashtable)
                {
                    string field = entry.Key.ToString();

                    if (field.Equals("ModuleName", StringComparison.OrdinalIgnoreCase))
                    {
                        moduleSpecification.Name = LanguagePrimitives.ConvertTo <string>(entry.Value);
                    }
                    else if (field.Equals("ModuleVersion", StringComparison.OrdinalIgnoreCase))
                    {
                        moduleSpecification.Version = LanguagePrimitives.ConvertTo <Version>(entry.Value);
                    }
                    else if (field.Equals("RequiredVersion", StringComparison.OrdinalIgnoreCase))
                    {
                        moduleSpecification.RequiredVersion = LanguagePrimitives.ConvertTo <Version>(entry.Value);
                    }
                    else if (field.Equals("MaximumVersion", StringComparison.OrdinalIgnoreCase))
                    {
                        moduleSpecification.MaximumVersion = LanguagePrimitives.ConvertTo <string>(entry.Value);
                        ModuleCmdletBase.GetMaximumVersion(moduleSpecification.MaximumVersion);
                    }
                    else if (field.Equals("GUID", StringComparison.OrdinalIgnoreCase))
                    {
                        moduleSpecification.Guid = LanguagePrimitives.ConvertTo <Guid?>(entry.Value);
                    }
                    else
                    {
                        if (badKeys.Length > 0)
                        {
                            badKeys.Append(", ");
                        }

                        badKeys.Append("'");
                        badKeys.Append(entry.Key.ToString());
                        badKeys.Append("'");
                    }
                }
            }
            // catch all exceptions here, we are going to report them via return value.
            // Example of catched exception: one of conversions to Version failed.
            catch (Exception e)
            {
                return(e);
            }

            string message;

            if (badKeys.Length != 0)
            {
                message = StringUtil.Format(Modules.InvalidModuleSpecificationMember, "ModuleName, ModuleVersion, RequiredVersion, GUID", badKeys);
                return(new ArgumentException(message));
            }

            if (string.IsNullOrEmpty(moduleSpecification.Name))
            {
                message = StringUtil.Format(Modules.RequiredModuleMissingModuleName);
                return(new MissingMemberException(message));
            }

            if (moduleSpecification.RequiredVersion == null && moduleSpecification.Version == null && moduleSpecification.MaximumVersion == null)
            {
                message = StringUtil.Format(Modules.RequiredModuleMissingModuleVersion);
                return(new MissingMemberException(message));
            }

            if (moduleSpecification.RequiredVersion != null && moduleSpecification.Version != null)
            {
                message = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "ModuleVersion", "RequiredVersion");
                return(new ArgumentException(message));
            }

            if (moduleSpecification.RequiredVersion != null && moduleSpecification.MaximumVersion != null)
            {
                message = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "MaximumVersion", "RequiredVersion");
                return(new ArgumentException(message));
            }

            return(null);
        }
Exemplo n.º 11
0
 /// <summary>
 /// Enable Snapin logging based on group policy
 /// </summary>
 private static void SetSnapInLoggingInformation(PSSnapInInfo psSnapInInfo, ModuleCmdletBase.ModuleLoggingGroupPolicyStatus status, IEnumerable<string> moduleOrSnapinNames)
 {
     if (((status & ModuleCmdletBase.ModuleLoggingGroupPolicyStatus.Enabled) != 0) && moduleOrSnapinNames != null)
     {
         foreach (string currentGPModuleOrSnapinName in moduleOrSnapinNames)
         {
             if (string.Equals(psSnapInInfo.Name, currentGPModuleOrSnapinName, StringComparison.OrdinalIgnoreCase))
             {
                 psSnapInInfo.LogPipelineExecutionDetails = true;
             }
             else if (WildcardPattern.ContainsWildcardCharacters(currentGPModuleOrSnapinName))
             {
                 WildcardPattern wildcard = WildcardPattern.Get(currentGPModuleOrSnapinName, WildcardOptions.IgnoreCase);
                 if (wildcard.IsMatch(psSnapInInfo.Name))
                 {
                     psSnapInInfo.LogPipelineExecutionDetails = true;
                 }
             }
         }
     }
 }
Exemplo n.º 12
0
        private bool IsCommandInResult(CommandInfo command)
        {
            bool flag2 = command.Module != null;

            foreach (CommandInfo info in this.accumulatedResults)
            {
                if ((((command.CommandType == info.CommandType) && ((string.Compare(command.Name, info.Name, StringComparison.CurrentCultureIgnoreCase) == 0) || (string.Compare(ModuleCmdletBase.RemovePrefixFromCommandName(info.Name, info.Prefix), command.Name, StringComparison.CurrentCultureIgnoreCase) == 0))) && ((info.Module != null) && flag2)) && (((info.IsImported && command.IsImported) && info.Module.Equals(command.Module)) || ((!info.IsImported || !command.IsImported) && info.Module.Path.Equals(command.Module.Path, StringComparison.OrdinalIgnoreCase))))
                {
                    return(true);
                }
            }
            return(false);
        }
Exemplo n.º 13
0
        private void ProcessTypeFiles()
        {
            Collection <string> collection  = UpdateData.Glob(base.PrependPath, "TypesPrependPathException", this);
            Collection <string> collection2 = UpdateData.Glob(base.AppendPath, "TypesAppendPathException", this);

            if (((base.PrependPath.Length <= 0) && (base.AppendPath.Length <= 0)) || ((collection.Count != 0) || (collection2.Count != 0)))
            {
                string updateTypeDataAction = UpdateDataStrings.UpdateTypeDataAction;
                string updateTarget         = UpdateDataStrings.UpdateTarget;
                if (base.Context.RunspaceConfiguration != null)
                {
                    for (int i = collection.Count - 1; i >= 0; i--)
                    {
                        string target = string.Format(CultureInfo.InvariantCulture, updateTarget, new object[] { collection[i] });
                        if (base.ShouldProcess(target, updateTypeDataAction))
                        {
                            base.Context.RunspaceConfiguration.Types.Prepend(new TypeConfigurationEntry(collection[i]));
                        }
                    }
                    foreach (string str4 in collection2)
                    {
                        string str5 = string.Format(CultureInfo.InvariantCulture, updateTarget, new object[] { str4 });
                        if (base.ShouldProcess(str5, updateTypeDataAction))
                        {
                            base.Context.RunspaceConfiguration.Types.Append(new TypeConfigurationEntry(str4));
                        }
                    }
                    try
                    {
                        base.Context.CurrentRunspace.RunspaceConfiguration.Types.Update(true);
                        return;
                    }
                    catch (RuntimeException exception)
                    {
                        base.WriteError(new ErrorRecord(exception, "TypesXmlUpdateException", ErrorCategory.InvalidOperation, null));
                        return;
                    }
                }
                if (base.Context.InitialSessionState != null)
                {
                    HashSet <string> set = new HashSet <string>(StringComparer.CurrentCultureIgnoreCase);
                    Collection <SessionStateTypeEntry> collection3 = new Collection <SessionStateTypeEntry>();
                    for (int j = collection.Count - 1; j >= 0; j--)
                    {
                        string str6 = string.Format(CultureInfo.InvariantCulture, updateTarget, new object[] { collection[j] });
                        string item = ModuleCmdletBase.ResolveRootedFilePath(collection[j], base.Context) ?? collection[j];
                        if (base.ShouldProcess(str6, updateTypeDataAction) && !set.Contains(item))
                        {
                            set.Add(item);
                            collection3.Add(new SessionStateTypeEntry(collection[j]));
                        }
                    }
                    foreach (SessionStateTypeEntry entry in base.Context.InitialSessionState.Types)
                    {
                        if (entry.FileName != null)
                        {
                            string str8 = ModuleCmdletBase.ResolveRootedFilePath(entry.FileName, base.Context) ?? entry.FileName;
                            if (!set.Contains(str8))
                            {
                                set.Add(str8);
                                collection3.Add(entry);
                            }
                        }
                        else
                        {
                            collection3.Add(entry);
                        }
                    }
                    foreach (string str9 in collection2)
                    {
                        string str10 = string.Format(CultureInfo.InvariantCulture, updateTarget, new object[] { str9 });
                        string str11 = ModuleCmdletBase.ResolveRootedFilePath(str9, base.Context) ?? str9;
                        if (base.ShouldProcess(str10, updateTypeDataAction) && !set.Contains(str11))
                        {
                            set.Add(str11);
                            collection3.Add(new SessionStateTypeEntry(str9));
                        }
                    }
                    base.Context.InitialSessionState.Types.Clear();
                    Collection <string> errors = new Collection <string>();
                    bool clearTable            = true;
                    foreach (SessionStateTypeEntry entry2 in collection3)
                    {
                        try
                        {
                            if (entry2.TypeTable != null)
                            {
                                PSInvalidOperationException exception2 = new PSInvalidOperationException(UpdateDataStrings.CannotUpdateTypeWithTypeTable);
                                base.WriteError(new ErrorRecord(exception2, "CannotUpdateTypeWithTypeTable", ErrorCategory.InvalidOperation, null));
                                continue;
                            }
                            if (entry2.FileName != null)
                            {
                                bool flag2;
                                base.Context.TypeTable.Update(entry2.FileName, errors, clearTable, base.Context.AuthorizationManager, base.Context.InitialSessionState.Host, out flag2);
                            }
                            else
                            {
                                base.Context.TypeTable.Update(entry2.TypeData, errors, entry2.IsRemove, clearTable);
                            }
                        }
                        catch (RuntimeException exception3)
                        {
                            base.WriteError(new ErrorRecord(exception3, "TypesXmlUpdateException", ErrorCategory.InvalidOperation, null));
                        }
                        base.Context.InitialSessionState.Types.Add(entry2);
                        if (errors.Count > 0)
                        {
                            foreach (string str12 in errors)
                            {
                                RuntimeException exception4 = new RuntimeException(str12);
                                base.WriteError(new ErrorRecord(exception4, "TypesXmlUpdateException", ErrorCategory.InvalidOperation, null));
                            }
                            errors.Clear();
                        }
                        clearTable = false;
                    }
                }
            }
        }
Exemplo n.º 14
0
 protected override void ProcessRecord()
 {
     if (base.ParameterSetName == "RemoveFileSet")
     {
         string removeTypeFileAction    = UpdateDataStrings.RemoveTypeFileAction;
         string updateTarget            = UpdateDataStrings.UpdateTarget;
         Collection <string> collection = UpdateData.Glob(this.typeFiles, "TypePathException", this);
         if (collection.Count != 0)
         {
             Dictionary <string, List <int> > fileNameToIndexMap = new Dictionary <string, List <int> >(StringComparer.OrdinalIgnoreCase);
             List <int> list = new List <int>();
             if (base.Context.RunspaceConfiguration != null)
             {
                 for (int i = 0; i < base.Context.RunspaceConfiguration.Types.Count; i++)
                 {
                     string fileName = base.Context.RunspaceConfiguration.Types[i].FileName;
                     if (fileName != null)
                     {
                         ConstructFileToIndexMap(fileName, i, fileNameToIndexMap);
                     }
                 }
             }
             else if (base.Context.InitialSessionState != null)
             {
                 for (int j = 0; j < base.Context.InitialSessionState.Types.Count; j++)
                 {
                     string filePath = base.Context.InitialSessionState.Types[j].FileName;
                     if (filePath != null)
                     {
                         filePath = ModuleCmdletBase.ResolveRootedFilePath(filePath, base.Context) ?? filePath;
                         ConstructFileToIndexMap(filePath, j, fileNameToIndexMap);
                     }
                 }
             }
             foreach (string str5 in collection)
             {
                 string target = string.Format(CultureInfo.InvariantCulture, updateTarget, new object[] { str5 });
                 if (base.ShouldProcess(target, removeTypeFileAction))
                 {
                     List <int> list2;
                     if (fileNameToIndexMap.TryGetValue(str5, out list2))
                     {
                         list.AddRange(list2);
                     }
                     else
                     {
                         base.WriteError(this.NewError("TypeFileNotExistsInCurrentSession", "TypeFileNotExistsInCurrentSession", null, new object[] { str5 }));
                     }
                 }
             }
             if (list.Count > 0)
             {
                 list.Sort();
                 for (int k = list.Count - 1; k >= 0; k--)
                 {
                     if (base.Context.RunspaceConfiguration != null)
                     {
                         base.Context.RunspaceConfiguration.Types.RemoveItem(list[k]);
                     }
                     else if (base.Context.InitialSessionState != null)
                     {
                         base.Context.InitialSessionState.Types.RemoveItem(list[k]);
                     }
                 }
                 try
                 {
                     if (base.Context.RunspaceConfiguration != null)
                     {
                         base.Context.RunspaceConfiguration.Types.Update();
                     }
                     else if (base.Context.InitialSessionState != null)
                     {
                         bool refreshTypeAndFormatSetting = base.Context.InitialSessionState.RefreshTypeAndFormatSetting;
                         try
                         {
                             base.Context.InitialSessionState.RefreshTypeAndFormatSetting = true;
                             base.Context.InitialSessionState.UpdateTypes(base.Context, false, false);
                         }
                         finally
                         {
                             base.Context.InitialSessionState.RefreshTypeAndFormatSetting = refreshTypeAndFormatSetting;
                         }
                     }
                 }
                 catch (RuntimeException exception)
                 {
                     base.WriteError(new ErrorRecord(exception, "TypesFileRemoveException", ErrorCategory.InvalidOperation, null));
                 }
             }
         }
     }
     else
     {
         string removeTypeDataAction = UpdateDataStrings.RemoveTypeDataAction;
         string removeTypeDataTarget = UpdateDataStrings.RemoveTypeDataTarget;
         string typeName             = null;
         if (base.ParameterSetName == "RemoveTypeDataSet")
         {
             typeName = this.typeData.TypeName;
         }
         else
         {
             if (string.IsNullOrWhiteSpace(this.typeName))
             {
                 base.ThrowTerminatingError(this.NewError("TargetTypeNameEmpty", "TargetTypeNameEmpty", this.typeName, new object[0]));
             }
             typeName = this.typeName;
         }
         System.Management.Automation.Runspaces.TypeData type = new System.Management.Automation.Runspaces.TypeData(typeName);
         string str10 = string.Format(CultureInfo.InvariantCulture, removeTypeDataTarget, new object[] { typeName });
         if (base.ShouldProcess(str10, removeTypeDataAction))
         {
             try
             {
                 Collection <string> errors = new Collection <string>();
                 base.Context.TypeTable.Update(type, errors, true, false);
                 if (errors.Count > 0)
                 {
                     foreach (string str11 in errors)
                     {
                         RuntimeException exception2 = new RuntimeException(str11);
                         base.WriteError(new ErrorRecord(exception2, "TypesDynamicRemoveException", ErrorCategory.InvalidOperation, null));
                     }
                 }
                 else if (base.Context.RunspaceConfiguration != null)
                 {
                     base.Context.RunspaceConfiguration.Types.Append(new TypeConfigurationEntry(type, true));
                 }
                 else if (base.Context.InitialSessionState != null)
                 {
                     base.Context.InitialSessionState.Types.Add(new SessionStateTypeEntry(type, true));
                 }
             }
             catch (RuntimeException exception3)
             {
                 base.WriteError(new ErrorRecord(exception3, "TypesDynamicRemoveException", ErrorCategory.InvalidOperation, null));
             }
         }
     }
 }
Exemplo n.º 15
0
 private void ImportModule_ViaLocalModuleInfo(ModuleCmdletBase.ImportModuleOptions importModuleOptions, PSModuleInfo module)
 {
     try
     {
         PSModuleInfo info = null;
         base.Context.Modules.ModuleTable.TryGetValue(module.Path, out info);
         if (!base.BaseForce && base.IsModuleAlreadyLoaded(info))
         {
             ModuleCmdletBase.AddModuleToModuleTables(base.Context, base.TargetSessionState.Internal, info);
             base.ImportModuleMembers(info, base.BasePrefix, importModuleOptions);
             if (base.BaseAsCustomObject)
             {
                 if (info.ModuleType != ModuleType.Script)
                 {
                     InvalidOperationException exception = new InvalidOperationException(StringUtil.Format(Modules.CantUseAsCustomObjectWithBinaryModule, info.Path));
                     ErrorRecord errorRecord = new ErrorRecord(exception, "Modules_CantUseAsCustomObjectWithBinaryModule", ErrorCategory.PermissionDenied, null);
                     base.WriteError(errorRecord);
                 }
                 else
                 {
                     base.WriteObject(info.AsCustomObject());
                 }
             }
             else if (base.BasePassThru)
             {
                 base.WriteObject(info);
             }
         }
         else
         {
             PSModuleInfo info2;
             if (base.Context.Modules.ModuleTable.TryGetValue(module.Path, out info2))
             {
                 base.RemoveModule(info2);
             }
             PSModuleInfo info3 = module;
             try
             {
                 if (module.SessionState == null)
                 {
                     if (File.Exists(module.Path))
                     {
                         bool flag;
                         info3 = base.LoadModule(module.Path, null, base.BasePrefix, null, ref importModuleOptions, ModuleCmdletBase.ManifestProcessingFlags.LoadElements | ModuleCmdletBase.ManifestProcessingFlags.NullOnFirstError | ModuleCmdletBase.ManifestProcessingFlags.WriteErrors, out flag);
                     }
                 }
                 else if (!string.IsNullOrEmpty(module.Name))
                 {
                     ModuleCmdletBase.AddModuleToModuleTables(base.Context, base.TargetSessionState.Internal, info3);
                     if (info3.SessionState != null)
                     {
                         base.ImportModuleMembers(info3, base.BasePrefix, importModuleOptions);
                     }
                     if (base.BaseAsCustomObject && (info3.SessionState != null))
                     {
                         base.WriteObject(module.AsCustomObject());
                     }
                     else if (base.BasePassThru)
                     {
                         base.WriteObject(info3);
                     }
                 }
             }
             catch (IOException)
             {
             }
         }
     }
     catch (PSInvalidOperationException exception2)
     {
         ErrorRecord record2 = new ErrorRecord(exception2.ErrorRecord, exception2);
         base.WriteError(record2);
     }
 }
Exemplo n.º 16
0
        internal static DirectoryInfo CreateModuleDirectory(PSCmdlet cmdlet, string moduleNameOrPath, bool force)
        {
            Dbg.Assert(cmdlet != null, "Caller should verify cmdlet != null");
            Dbg.Assert(!string.IsNullOrEmpty(moduleNameOrPath), "Caller should verify !string.IsNullOrEmpty(moduleNameOrPath)");

            DirectoryInfo directoryInfo = null;

            try
            {
                // Even if 'moduleNameOrPath' is a rooted path, 'ResolveRootedFilePath' may return null when the path doesn't exist yet,
                // or when it contains wildcards but cannot be resolved to a single path.
                string rootedPath = ModuleCmdletBase.ResolveRootedFilePath(moduleNameOrPath, cmdlet.Context);
                if (string.IsNullOrEmpty(rootedPath) && moduleNameOrPath.StartsWith('.'))
                {
                    PathInfo currentPath = cmdlet.CurrentProviderLocation(cmdlet.Context.ProviderNames.FileSystem);
                    rootedPath = Path.Combine(currentPath.ProviderPath, moduleNameOrPath);
                }

                if (string.IsNullOrEmpty(rootedPath))
                {
                    if (Path.IsPathRooted(moduleNameOrPath))
                    {
                        rootedPath = moduleNameOrPath;
                    }
                    else
                    {
                        string personalModuleRoot = ModuleIntrinsics.GetPersonalModulePath();
                        if (string.IsNullOrEmpty(personalModuleRoot))
                        {
                            cmdlet.ThrowTerminatingError(
                                new ErrorRecord(
                                    new ArgumentException(StringUtil.Format(PathUtilsStrings.ExportPSSession_ErrorModuleNameOrPath, moduleNameOrPath)),
                                    "ExportPSSession_ErrorModuleNameOrPath",
                                    ErrorCategory.InvalidArgument,
                                    cmdlet));
                        }

                        rootedPath = Path.Combine(personalModuleRoot, moduleNameOrPath);
                    }
                }

                directoryInfo = new DirectoryInfo(rootedPath);
                if (directoryInfo.Exists)
                {
                    if (!force)
                    {
                        string errorMessage = string.Format(
                            CultureInfo.InvariantCulture, // directory name should be treated as culture-invariant
                            PathUtilsStrings.ExportPSSession_ErrorDirectoryExists,
                            directoryInfo.FullName);
                        ErrorDetails details     = new ErrorDetails(errorMessage);
                        ErrorRecord  errorRecord = new ErrorRecord(
                            new ArgumentException(details.Message),
                            "ExportProxyCommand_OutputDirectoryExists",
                            ErrorCategory.ResourceExists,
                            directoryInfo);
                        cmdlet.ThrowTerminatingError(errorRecord);
                    }
                }
                else
                {
                    directoryInfo.Create();
                }
            }
            catch (Exception e)
            {
                string errorMessage = string.Format(
                    CultureInfo.InvariantCulture, // directory name should be treated as culture-invariant
                    PathUtilsStrings.ExportPSSession_CannotCreateOutputDirectory,
                    moduleNameOrPath,
                    e.Message);
                ErrorDetails details     = new ErrorDetails(errorMessage);
                ErrorRecord  errorRecord = new ErrorRecord(
                    new ArgumentException(details.Message, e),
                    "ExportProxyCommand_CannotCreateOutputDirectory",
                    ErrorCategory.ResourceExists,
                    moduleNameOrPath);
                cmdlet.ThrowTerminatingError(errorRecord);
            }

            return(directoryInfo);
        }
Exemplo n.º 17
0
 private PSModuleInfo ImportModule_LocallyViaName(ModuleCmdletBase.ImportModuleOptions importModuleOptions, string name)
 {
     try
     {
         if (name.Equals("PSWorkflow", StringComparison.OrdinalIgnoreCase) && Utils.IsRunningFromSysWOW64())
         {
             throw new NotSupportedException(AutomationExceptions.WorkflowDoesNotSupportWOW64);
         }
         bool found = false;
         PSModuleInfo module = null;
         string str = null;
         string str2 = null;
         if (((this.MinimumVersion == null) && (this.RequiredVersion == null)) && (PSModuleInfo.UseAppDomainLevelModuleCache && !base.BaseForce))
         {
             str = PSModuleInfo.ResolveUsingAppDomainLevelModuleCache(name);
         }
         if (!string.IsNullOrEmpty(str))
         {
             if (File.Exists(str))
             {
                 str2 = str;
             }
             else
             {
                 PSModuleInfo.RemoveFromAppDomainLevelCache(name);
             }
         }
         if (str2 == null)
         {
             str2 = ModuleCmdletBase.ResolveRootedFilePath(name, base.Context);
         }
         bool flag2 = false;
         if (!string.IsNullOrEmpty(str2))
         {
             if (!base.BaseForce && base.Context.Modules.ModuleTable.ContainsKey(str2))
             {
                 PSModuleInfo info2 = base.Context.Modules.ModuleTable[str2];
                 if (((this.RequiredVersion == null) || info2.Version.Equals(this.RequiredVersion)) || (((base.BaseMinimumVersion == null) || (info2.ModuleType != ModuleType.Manifest)) || (info2.Version >= base.BaseMinimumVersion)))
                 {
                     flag2 = true;
                     ModuleCmdletBase.AddModuleToModuleTables(base.Context, base.TargetSessionState.Internal, info2);
                     base.ImportModuleMembers(info2, base.BasePrefix, importModuleOptions);
                     if (base.BaseAsCustomObject)
                     {
                         if (info2.ModuleType != ModuleType.Script)
                         {
                             InvalidOperationException exception = new InvalidOperationException(StringUtil.Format(Modules.CantUseAsCustomObjectWithBinaryModule, info2.Path));
                             ErrorRecord errorRecord = new ErrorRecord(exception, "Modules_CantUseAsCustomObjectWithBinaryModule", ErrorCategory.PermissionDenied, null);
                             base.WriteError(errorRecord);
                         }
                         else
                         {
                             base.WriteObject(info2.AsCustomObject());
                         }
                     }
                     else if (base.BasePassThru)
                     {
                         base.WriteObject(info2);
                     }
                     found = true;
                     module = info2;
                 }
             }
             if (!flag2)
             {
                 if (File.Exists(str2))
                 {
                     PSModuleInfo info3;
                     if (base.Context.Modules.ModuleTable.TryGetValue(str2, out info3))
                     {
                         base.RemoveModule(info3);
                     }
                     module = base.LoadModule(str2, null, base.BasePrefix, null, ref importModuleOptions, ModuleCmdletBase.ManifestProcessingFlags.LoadElements | ModuleCmdletBase.ManifestProcessingFlags.NullOnFirstError | ModuleCmdletBase.ManifestProcessingFlags.WriteErrors, out found);
                 }
                 else if (Directory.Exists(str2))
                 {
                     str2 = Path.Combine(str2, Path.GetFileName(str2));
                     module = base.LoadUsingExtensions(null, str2, str2, null, null, base.BasePrefix, null, importModuleOptions, ModuleCmdletBase.ManifestProcessingFlags.LoadElements | ModuleCmdletBase.ManifestProcessingFlags.NullOnFirstError | ModuleCmdletBase.ManifestProcessingFlags.WriteErrors, out found);
                 }
             }
         }
         else
         {
             if (InitialSessionState.IsEngineModule(name))
             {
                 CmdletInfo cmdlet = base.Context.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Get-PSSnapIn");
                 if ((cmdlet != null) && (cmdlet.Visibility == SessionStateEntryVisibility.Public))
                 {
                     CommandInfo commandInfo = new CmdletInfo("Get-PSSnapIn", typeof(GetPSSnapinCommand), null, null, base.Context);
                     Command command = new Command(commandInfo);
                     Collection<PSSnapInInfo> collection = null;
                     try
                     {
                         using (PowerShell shell = PowerShell.Create(RunspaceMode.CurrentRunspace))
                         {
                             shell.AddCommand(command).AddParameter("Name", name).AddParameter("ErrorAction", ActionPreference.Ignore);
                             collection = shell.Invoke<PSSnapInInfo>();
                         }
                     }
                     catch (Exception exception2)
                     {
                         CommandProcessorBase.CheckForSevereException(exception2);
                     }
                     if ((collection != null) && (collection.Count == 1))
                     {
                         string text = string.Format(CultureInfo.InvariantCulture, Modules.ModuleLoadedAsASnapin, new object[] { collection[0].Name });
                         base.WriteWarning(text);
                         found = true;
                         return module;
                     }
                 }
             }
             if (ModuleCmdletBase.IsRooted(name))
             {
                 if (!string.IsNullOrEmpty(Path.GetExtension(name)))
                 {
                     module = base.LoadModule(name, null, base.BasePrefix, null, ref importModuleOptions, ModuleCmdletBase.ManifestProcessingFlags.LoadElements | ModuleCmdletBase.ManifestProcessingFlags.NullOnFirstError | ModuleCmdletBase.ManifestProcessingFlags.WriteErrors, out found);
                 }
                 else
                 {
                     module = base.LoadUsingExtensions(null, name, name, null, null, base.BasePrefix, null, importModuleOptions, ModuleCmdletBase.ManifestProcessingFlags.LoadElements | ModuleCmdletBase.ManifestProcessingFlags.NullOnFirstError | ModuleCmdletBase.ManifestProcessingFlags.WriteErrors, out found);
                 }
             }
             else
             {
                 IEnumerable<string> modulePath = ModuleIntrinsics.GetModulePath(false, base.Context);
                 if ((this.MinimumVersion == null) && (this.RequiredVersion == null))
                 {
                     base.AddToAppDomainLevelCache = true;
                 }
                 found = base.LoadUsingModulePath(found, modulePath, name, null, importModuleOptions, ModuleCmdletBase.ManifestProcessingFlags.LoadElements | ModuleCmdletBase.ManifestProcessingFlags.NullOnFirstError | ModuleCmdletBase.ManifestProcessingFlags.WriteErrors, out module);
             }
         }
         if (!found)
         {
             ErrorRecord record2 = null;
             string message = null;
             if (base.BaseRequiredVersion != null)
             {
                 message = StringUtil.Format(Modules.ModuleWithVersionNotFound, name, base.BaseRequiredVersion);
             }
             else if (base.BaseMinimumVersion != null)
             {
                 message = StringUtil.Format(Modules.ModuleWithVersionNotFound, name, base.BaseMinimumVersion);
             }
             if ((base.BaseRequiredVersion != null) || (base.BaseMinimumVersion != null))
             {
                 FileNotFoundException exception3 = new FileNotFoundException(message);
                 record2 = new ErrorRecord(exception3, "Modules_ModuleWithVersionNotFound", ErrorCategory.ResourceUnavailable, name);
             }
             else
             {
                 FileNotFoundException exception4 = new FileNotFoundException(StringUtil.Format(Modules.ModuleNotFound, name));
                 record2 = new ErrorRecord(exception4, "Modules_ModuleNotFound", ErrorCategory.ResourceUnavailable, name);
             }
             base.WriteError(record2);
         }
         return module;
     }
     catch (PSInvalidOperationException exception5)
     {
         ErrorRecord record3 = new ErrorRecord(exception5.ErrorRecord, exception5);
         base.WriteError(record3);
     }
     return null;
 }
Exemplo n.º 18
0
 private PSModuleInfo ImportModule_RemotelyViaCimModuleData(ModuleCmdletBase.ImportModuleOptions importModuleOptions, RemoteDiscoveryHelper.CimModule remoteCimModule, Microsoft.Management.Infrastructure.CimSession cimSession)
 {
     PSModuleInfo info5;
     try
     {
         Token[] tokenArray;
         ParseError[] errorArray;
         Version version;
         Func<RemoteDiscoveryHelper.CimModuleFile, bool> filesFilter = null;
         Func<RemoteDiscoveryHelper.CimModuleFile, bool> func2 = null;
         if (remoteCimModule.MainManifest == null)
         {
             ArgumentException exception = new ArgumentException(string.Format(CultureInfo.InvariantCulture, Modules.EmptyModuleManifest, new object[] { remoteCimModule.ModuleName + ".psd1" }));
             throw exception;
         }
         bool containedErrors = false;
         PSModuleInfo module = null;
         string fileName = Path.Combine(RemoteDiscoveryHelper.GetModulePath(remoteCimModule.ModuleName, null, cimSession.ComputerName, base.Context.CurrentRunspace), remoteCimModule.ModuleName + ".psd1");
         Hashtable data = null;
         Hashtable originalManifest = null;
         ScriptBlockAst ast = null;
         ast = Parser.ParseInput(remoteCimModule.MainManifest.FileData, fileName, out tokenArray, out errorArray);
         if ((ast == null) || ((errorArray != null) && (errorArray.Length > 0)))
         {
             throw new ParseException(errorArray);
         }
         ScriptBlock scriptBlock = new ScriptBlock(ast, false);
         data = base.LoadModuleManifestData(fileName, scriptBlock, ModuleCmdletBase.ModuleManifestMembers, ModuleCmdletBase.ManifestProcessingFlags.NullOnFirstError | ModuleCmdletBase.ManifestProcessingFlags.WriteErrors, ref containedErrors);
         if ((data == null) || containedErrors)
         {
             return null;
         }
         originalManifest = data;
         if (!base.GetScalarFromData<Version>(data, null, "ModuleVersion", 0, out version))
         {
             version = null;
         }
         string str2 = RemoteDiscoveryHelper.GetModulePath(remoteCimModule.ModuleName, version, cimSession.ComputerName, base.Context.CurrentRunspace);
         fileName = Path.Combine(str2, remoteCimModule.ModuleName + ".psd1");
         PSModuleInfo info2 = base.IsModuleImportUnnecessaryBecauseModuleIsAlreadyLoaded(fileName, base.BasePrefix, importModuleOptions);
         if (info2 != null)
         {
             info5 = info2;
         }
         else
         {
             try
             {
                 Directory.CreateDirectory(str2);
                 if (filesFilter == null)
                 {
                     filesFilter = cimModuleFile => this.IsTypesPs1XmlFile(cimModuleFile, data);
                 }
                 IEnumerable<string> typesToProcess = this.CreateCimModuleFiles(remoteCimModule, RemoteDiscoveryHelper.CimFileCode.TypesV1, filesFilter, str2);
                 if (func2 == null)
                 {
                     func2 = cimModuleFile => this.IsFormatPs1XmlFile(cimModuleFile, data);
                 }
                 IEnumerable<string> formatsToProcess = this.CreateCimModuleFiles(remoteCimModule, RemoteDiscoveryHelper.CimFileCode.FormatV1, func2, str2);
                 IEnumerable<string> nestedModules = this.CreateCimModuleFiles(remoteCimModule, RemoteDiscoveryHelper.CimFileCode.CmdletizationV1, new Func<RemoteDiscoveryHelper.CimModuleFile, bool>(ImportModuleCommand.IsCmdletizationFile), str2);
                 data = RemoteDiscoveryHelper.RewriteManifest(data, nestedModules, typesToProcess, formatsToProcess);
                 originalManifest = RemoteDiscoveryHelper.RewriteManifest(originalManifest);
                 module = base.LoadModuleManifest(fileName, null, data, originalManifest, ModuleCmdletBase.ManifestProcessingFlags.LoadElements | ModuleCmdletBase.ManifestProcessingFlags.NullOnFirstError | ModuleCmdletBase.ManifestProcessingFlags.WriteErrors, base.BaseMinimumVersion, base.BaseRequiredVersion, ref importModuleOptions, ref containedErrors);
                 if (module == null)
                 {
                     return null;
                 }
                 foreach (PSModuleInfo info3 in module.NestedModules)
                 {
                     Type type;
                     PSPrimitiveDictionary.TryPathGet<Type>(info3.PrivateData as IDictionary, out type, new string[] { "CmdletsOverObjects", "CmdletAdapter" });
                     if (!type.AssemblyQualifiedName.Equals("Microsoft.PowerShell.Cmdletization.Cim.CimCmdletAdapter, Microsoft.PowerShell.Commands.Management, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", StringComparison.OrdinalIgnoreCase))
                     {
                         ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, CmdletizationCoreResources.ImportModule_UnsupportedCmdletAdapter, new object[] { type.FullName })), "UnsupportedCmdletAdapter", ErrorCategory.InvalidData, type);
                         base.ThrowTerminatingError(errorRecord);
                     }
                 }
                 if (this.IsMixedModePsCimModule(remoteCimModule))
                 {
                     string text = string.Format(CultureInfo.InvariantCulture, Modules.MixedModuleOverCimSessionWarning, new object[] { remoteCimModule.ModuleName });
                     base.WriteWarning(text);
                 }
                 foreach (PSModuleInfo info4 in module.NestedModules)
                 {
                     IDictionary dictionary;
                     PSPrimitiveDictionary.TryPathGet<IDictionary>(info4.PrivateData as IDictionary, out dictionary, new string[] { "CmdletsOverObjects" });
                     dictionary["DefaultSession"] = cimSession;
                 }
                 ScriptBlock newClosure = base.Context.Engine.ParseScriptBlock("\r\n                        Microsoft.PowerShell.Management\\Remove-Item `\r\n                            -LiteralPath $temporaryModulePath `\r\n                            -Force `\r\n                            -Recurse `\r\n                            -ErrorAction SilentlyContinue\r\n\r\n                        if ($previousOnRemoveScript -ne $null)\r\n                        {\r\n                            & $previousOnRemoveScript $args\r\n                        }\r\n                        ", false).GetNewClosure();
                 newClosure.Module.SessionState.PSVariable.Set("temporaryModulePath", str2);
                 newClosure.Module.SessionState.PSVariable.Set("previousOnRemoveScript", module.OnRemove);
                 module.OnRemove = newClosure;
                 ModuleCmdletBase.AddModuleToModuleTables(base.Context, base.TargetSessionState.Internal, module);
                 if (base.BasePassThru)
                 {
                     base.WriteObject(module);
                 }
                 info5 = module;
             }
             catch
             {
                 if (Directory.Exists(str2))
                 {
                     Directory.Delete(str2, true);
                 }
                 throw;
             }
             finally
             {
                 if ((module == null) && Directory.Exists(str2))
                 {
                     Directory.Delete(str2, true);
                 }
             }
         }
     }
     catch (Exception exception2)
     {
         ErrorRecord errorRecordForProcessingOfCimModule = RemoteDiscoveryHelper.GetErrorRecordForProcessingOfCimModule(exception2, remoteCimModule.ModuleName);
         base.WriteError(errorRecordForProcessingOfCimModule);
         info5 = null;
     }
     return info5;
 }
Exemplo n.º 19
0
 private void ImportModule_RemotelyViaCimSession(ModuleCmdletBase.ImportModuleOptions importModuleOptions, string[] moduleNames, Microsoft.Management.Infrastructure.CimSession cimSession, Uri resourceUri, string cimNamespace)
 {
     IEnumerable<RemoteDiscoveryHelper.CimModule> enumerable = RemoteDiscoveryHelper.GetCimModules(cimSession, resourceUri, cimNamespace, moduleNames, false, this, this.CancellationToken).ToList<RemoteDiscoveryHelper.CimModule>();
     IEnumerable<RemoteDiscoveryHelper.CimModule> enumerable2 = from cimModule in enumerable
         where cimModule.IsPsCimModule
         select cimModule;
     foreach (string str in from cimModule in enumerable
         where !cimModule.IsPsCimModule
         select cimModule.ModuleName)
     {
         ErrorRecord errorRecord = new ErrorRecord(new ArgumentException(string.Format(CultureInfo.InvariantCulture, Modules.PsModuleOverCimSessionError, new object[] { str })), "PsModuleOverCimSessionError", ErrorCategory.InvalidArgument, str);
         base.WriteError(errorRecord);
     }
     IEnumerable<string> source = (from cimModule in enumerable select cimModule.ModuleName).ToList<string>();
     foreach (string str3 in moduleNames)
     {
         WildcardPattern wildcardPattern = new WildcardPattern(str3, WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase);
         if (!source.Any<string>(foundModuleName => wildcardPattern.IsMatch(foundModuleName)))
         {
             FileNotFoundException exception = new FileNotFoundException(StringUtil.Format(Modules.ModuleNotFound, str3));
             ErrorRecord record2 = new ErrorRecord(exception, "Modules_ModuleNotFound", ErrorCategory.ResourceUnavailable, str3);
             base.WriteError(record2);
         }
     }
     foreach (RemoteDiscoveryHelper.CimModule module in enumerable2)
     {
         this.ImportModule_RemotelyViaCimModuleData(importModuleOptions, module, cimSession);
     }
 }
Exemplo n.º 20
0
        internal static Hashtable ConvertCimModuleFileToManifestHashtable(CimModuleFile cimModuleFile, string temporaryModuleManifestPath, ModuleCmdletBase cmdlet, ref bool containedErrors)
        {
            ScriptBlockAst ast = null;

            if (!containedErrors)
            {
                System.Management.Automation.Language.Token[] tokenArray;
                ParseError[] errorArray;
                ast = Parser.ParseInput(cimModuleFile.FileData, temporaryModuleManifestPath, out tokenArray, out errorArray);
                if ((ast == null) || ((errorArray != null) && (errorArray.Length > 0)))
                {
                    containedErrors = true;
                }
            }
            Hashtable hashtable = null;

            if (!containedErrors)
            {
                ScriptBlock scriptBlock = new ScriptBlock(ast, false);
                hashtable = cmdlet.LoadModuleManifestData(temporaryModuleManifestPath, scriptBlock, ModuleCmdletBase.ModuleManifestMembers, 0, ref containedErrors);
            }
            return(hashtable);
        }
Exemplo n.º 21
0
 private IList<PSModuleInfo> ImportModule_RemotelyViaPsrpSession(ModuleCmdletBase.ImportModuleOptions importModuleOptions, IEnumerable<string> moduleNames, System.Management.Automation.Runspaces.PSSession psSession)
 {
     List<PSModuleInfo> list = new List<PSModuleInfo>();
     if (moduleNames != null)
     {
         foreach (string str in moduleNames)
         {
             IList<PSModuleInfo> collection = this.ImportModule_RemotelyViaPsrpSession(importModuleOptions, str, psSession);
             list.AddRange(collection);
         }
     }
     return list;
 }
Exemplo n.º 22
0
        internal static Hashtable ConvertCimModuleFileToManifestHashtable(RemoteDiscoveryHelper.CimModuleFile cimModuleFile, string temporaryModuleManifestPath, ModuleCmdletBase cmdlet, ref bool containedErrors)
        {
            Dbg.Assert(cimModuleFile.FileCode == RemoteDiscoveryHelper.CimFileCode.PsdV1, "Caller should verify the file is of the right type");

            ScriptBlockAst scriptBlockAst = null;

            if (!containedErrors)
            {
                System.Management.Automation.Language.Token[] throwAwayTokens;
                ParseError[] parseErrors;
                scriptBlockAst = System.Management.Automation.Language.Parser.ParseInput(cimModuleFile.FileData, temporaryModuleManifestPath, out throwAwayTokens, out parseErrors);
                if ((scriptBlockAst == null) || (parseErrors != null && parseErrors.Length > 0))
                {
                    containedErrors = true;
                }
            }

            Hashtable data = null;

            if (!containedErrors)
            {
                ScriptBlock scriptBlock = new ScriptBlock(scriptBlockAst, isFilter: false);
                data = cmdlet.LoadModuleManifestData(
                    temporaryModuleManifestPath,
                    scriptBlock,
                    ModuleCmdletBase.ModuleManifestMembers,
                    0 /* - don't write errors, don't load elements, don't return null on first error */,
                    ref containedErrors);
            }

            return(data);
        }
Exemplo n.º 23
0
 private IList<PSModuleInfo> ImportModule_RemotelyViaPsrpSession(ModuleCmdletBase.ImportModuleOptions importModuleOptions, string moduleName, System.Management.Automation.Runspaces.PSSession psSession)
 {
     List<PSObject> list;
     using (PowerShell shell = PowerShell.Create())
     {
         shell.Runspace = psSession.Runspace;
         shell.AddCommand("Import-Module");
         shell.AddParameter("Name", moduleName);
         shell.AddParameter("DisableNameChecking", this.DisableNameChecking);
         shell.AddParameter("PassThru", true);
         if (this.MinimumVersion != null)
         {
             shell.AddParameter("Version", this.MinimumVersion);
         }
         if (this.RequiredVersion != null)
         {
             shell.AddParameter("RequiredVersion", this.RequiredVersion);
         }
         if (this.ArgumentList != null)
         {
             shell.AddParameter("ArgumentList", this.ArgumentList);
         }
         if (base.BaseForce)
         {
             shell.AddParameter("Force", true);
         }
         string errorMessageTemplate = string.Format(CultureInfo.InvariantCulture, Modules.RemoteDiscoveryRemotePsrpCommandFailed, new object[] { string.Format(CultureInfo.InvariantCulture, "Import-Module -Name '{0}'", new object[] { moduleName }) });
         list = RemoteDiscoveryHelper.InvokePowerShell(shell, this.CancellationToken, this, errorMessageTemplate).ToList<PSObject>();
     }
     List<PSModuleInfo> list2 = new List<PSModuleInfo>();
     foreach (PSObject obj2 in list)
     {
         PSPropertyInfo info = obj2.Properties["Name"];
         if (info != null)
         {
             Version version2;
             string remoteModuleName = (string) LanguagePrimitives.ConvertTo(info.Value, typeof(string), CultureInfo.InvariantCulture);
             PSPropertyInfo info2 = obj2.Properties["Version"];
             Version remoteModuleVersion = null;
             if ((info2 != null) && LanguagePrimitives.TryConvertTo<Version>(info2.Value, CultureInfo.InvariantCulture, out version2))
             {
                 remoteModuleVersion = version2;
             }
             PSModuleInfo item = this.ImportModule_RemotelyViaPsrpSession_SinglePreimportedModule(importModuleOptions, remoteModuleName, remoteModuleVersion, psSession);
             if (item != null)
             {
                 list2.Add(item);
             }
         }
     }
     return list2;
 }
Exemplo n.º 24
0
 /// <summary>
 /// for diagnostic purposes
 /// </summary>
 /// <returns></returns>
 public override string ToString()
 {
     return(ModuleCmdletBase.AddPrefixToCommandName(Name, Prefix));
 }
Exemplo n.º 25
0
 private static void SetSnapInLoggingInformation(PSSnapInInfo psSnapInInfo, ModuleCmdletBase.ModuleLoggingGroupPolicyStatus status, IEnumerable<string> moduleOrSnapinNames)
 {
     if (((status & ModuleCmdletBase.ModuleLoggingGroupPolicyStatus.Enabled) != ModuleCmdletBase.ModuleLoggingGroupPolicyStatus.Undefined) && (moduleOrSnapinNames != null))
     {
         foreach (string str in moduleOrSnapinNames)
         {
             if (string.Equals(psSnapInInfo.Name, str, StringComparison.OrdinalIgnoreCase))
             {
                 psSnapInInfo.LogPipelineExecutionDetails = true;
             }
             else if (WildcardPattern.ContainsWildcardCharacters(str))
             {
                 WildcardPattern pattern = new WildcardPattern(str, WildcardOptions.IgnoreCase);
                 if (pattern.IsMatch(psSnapInInfo.Name))
                 {
                     psSnapInInfo.LogPipelineExecutionDetails = true;
                 }
             }
         }
     }
 }