/// <summary>
        /// Initiate an instance of runspace configuration entry. 
        /// </summary>
        /// <param name="name">Name for the runspace configuration entry</param>
        /// <param name="psSnapin">The name of the PSSnapin the entry comes from.</param>
        /// <!--
        /// This is meant to be called by derived class only. It doesn't make sense to 
        /// directly create an instance of this class. 
        /// -->
        internal RunspaceConfigurationEntry(string name, PSSnapInInfo psSnapin)
        {
            if (String.IsNullOrEmpty(name) || String.IsNullOrEmpty(name.Trim()))
            {
                throw PSTraceSource.NewArgumentNullException("name");
            }

            Name = name.Trim();

            if (psSnapin == null)
            {
                throw PSTraceSource.NewArgumentException("psSnapin");
            }

            PSSnapIn = psSnapin;
        }
        /// <summary>
        /// Adds a mshsnapin specified by <paramref name="mshSnapInID"/> to the current list of
        /// mshsnapins. If the mshsnapin is successfully added, IsDirty property is set to true.
        /// </summary>
        /// <param name="mshSnapInID">ID of the mshsnapin which needs to be added.</param>
        /// <returns>A <see cref="PSSnapInInfo"/> object corresponding to mshSnapInID.</returns>
        /// <remarks>PSSnapIn information must be present in the registry for this call to succeed.</remarks>
        /// <exception cref="PSArgumentNullException">
        /// mshSnapInID is empty or null.
        /// </exception>
        /// <exception cref="PSArgumentException">
        /// PSSnapIn is already loaded.
        /// No PSSnapIn with given id found.
        /// PSSnapIn cannot be loaded.
        /// </exception>
        /// <exception cref="System.Security.SecurityException">
        /// Caller doesn't have permission to read keys.
        /// </exception>
        internal PSSnapInInfo AddPSSnapIn(string mshSnapInID)
        {
            if (string.IsNullOrEmpty(mshSnapInID))
            {
                PSTraceSource.NewArgumentNullException("mshSnapInID");
            }

            // Check whether the mshsnapin is already present in defaultmshsnapins/externalMshSnapins
            if (IsDefaultPSSnapIn(mshSnapInID, _defaultPSSnapIns))
            {
                s_mshsnapinTracer.TraceError("MshSnapin {0} can't be added since it is a default mshsnapin", mshSnapInID);

                throw PSTraceSource.NewArgumentException("mshSnapInID", ConsoleInfoErrorStrings.CannotLoadDefault);
            }

            if (IsActiveExternalPSSnapIn(mshSnapInID))
            {
                s_mshsnapinTracer.TraceError("MshSnapin {0} is already loaded.", mshSnapInID);

                throw PSTraceSource.NewArgumentException("mshSnapInID", ConsoleInfoErrorStrings.PSSnapInAlreadyExists, mshSnapInID);
            }

            // Check whether the mshsnapin is present in the registry.
            PSSnapInInfo newPSSnapIn = PSSnapInReader.Read(this.MajorVersion, mshSnapInID);

            if (!Utils.IsPSVersionSupported(newPSSnapIn.PSVersion.ToString()))
            {
                s_mshsnapinTracer.TraceError("MshSnapin {0} and current monad engine's versions don't match.", mshSnapInID);

                throw PSTraceSource.NewArgumentException("mshSnapInID",
                                                         ConsoleInfoErrorStrings.AddPSSnapInBadMonadVersion,
                                                         newPSSnapIn.PSVersion.ToString(),
                                                         PSVersion.ToString());
            }

            // new mshsnapin will never be null
            //if this is a valid new mshsnapin,add this to external mshsnapins
            _externalPSSnapIns.Add(newPSSnapIn);
            s_mshsnapinTracer.WriteLine("MshSnapin {0} successfully added to consoleinfo list.", mshSnapInID);
            //Set IsDirty to true
            IsDirty = true;

            return(newPSSnapIn);
        }
Exemple #3
0
 private void UnloadPSSnapIn(PSSnapInInfo mshsnapinInfo, out PSSnapInException warning)
 {
     warning = null;
     if (mshsnapinInfo != null)
     {
         string str;
         this.Cmdlets.RemovePSSnapIn(mshsnapinInfo.Name);
         this.Providers.RemovePSSnapIn(mshsnapinInfo.Name);
         this.Assemblies.RemovePSSnapIn(mshsnapinInfo.Name);
         this.Types.RemovePSSnapIn(mshsnapinInfo.Name);
         this.Formats.RemovePSSnapIn(mshsnapinInfo.Name);
         this.UpdateAll(out str);
         if (!string.IsNullOrEmpty(str))
         {
             _mshsnapinTracer.TraceWarning(str, new object[0]);
             warning = new PSSnapInException(mshsnapinInfo.Name, str, true);
         }
     }
 }
        /// <summary>
        /// Removes a mshsnapin specified by <paramref name="mshSnapInID"/> from the current
        /// list.
        /// </summary>
        /// <param name="mshSnapInID">ID of the mshsnapin which needs to be removed</param>
        /// <returns>PSSnapInInfo object for the mshsnapin that is removed.</returns>
        /// <remarks>MshSnapin is removed only from the console file. Registry entry
        /// is not touched.</remarks>
        /// <exception cref="PSArgumentNullException">
        /// mshSnapInID is null.
        /// </exception>
        /// <exception cref="PSArgumentException">
        /// 1. mshSnapInID is either a default mshsnapin or not loaded.
        /// 2. mshSnapInId is not valid.
        /// </exception>
        internal PSSnapInInfo RemovePSSnapIn(string mshSnapInID)
        {
            if (string.IsNullOrEmpty(mshSnapInID))
            {
                PSTraceSource.NewArgumentNullException("mshSnapInID");
            }

            // Monad has specific restrictions on the mshsnapinid like
            // mshsnapinid should be A-Za-z0-9.-_ etc.
            PSSnapInInfo.VerifyPSSnapInFormatThrowIfError(mshSnapInID);

            PSSnapInInfo removedPSSnapIn = null;

            // Check external mshsnapins
            foreach (PSSnapInInfo mshSnapIn in _externalPSSnapIns)
            {
                if (string.Equals(mshSnapInID, mshSnapIn.Name, System.StringComparison.OrdinalIgnoreCase))
                {
                    // We found the mshsnapin..remove from the list and break
                    removedPSSnapIn = mshSnapIn;
                    _externalPSSnapIns.Remove(mshSnapIn);

                    // The state of console file is changing..so set
                    // dirty flag.
                    IsDirty = true;
                    break;
                }
            }

            if (removedPSSnapIn == null)
            {
                if (IsDefaultPSSnapIn(mshSnapInID, _defaultPSSnapIns))
                {
                    s_mshsnapinTracer.WriteLine("MshSnapin {0} can't be removed since it is a default mshsnapin.", mshSnapInID);

                    throw PSTraceSource.NewArgumentException("mshSnapInID", ConsoleInfoErrorStrings.CannotRemoveDefault, mshSnapInID);
                }

                throw PSTraceSource.NewArgumentException("mshSnapInID", ConsoleInfoErrorStrings.CannotRemovePSSnapIn, mshSnapInID);
            }

            return(removedPSSnapIn);
        }
Exemple #5
0
        /// <exception cref="PSArgumentNullException">
        /// mshSnapInID is null.
        /// </exception>
        /// <exception cref="PSArgumentException">
        /// mshSnapInID is either a default mshsnapin or not loaded.
        /// </exception>
        internal override PSSnapInInfo DoRemovePSSnapIn(string name, out PSSnapInException warning)
        {
            warning = null;

            if (_consoleInfo == null)
            {
                return(null);
            }

            s_mshsnapinTracer.WriteLine("Removing mshsnapin {0}", name);

            PSSnapInInfo mshsnapinInfo = _consoleInfo.RemovePSSnapIn(name);

            UnloadPSSnapIn(mshsnapinInfo, out warning);

            s_mshsnapinTracer.WriteLine("MshSnapin {0} removed", name);

            return(mshsnapinInfo);
        }
 internal ProviderConfigurationEntry(
     string name,
     Type implementingType,
     string helpFileName,
     PSSnapInInfo psSnapinInfo)
     : base(name, psSnapinInfo)
 {
     using (ProviderConfigurationEntry.tracer.TraceConstructor((object)this))
     {
         this._type = implementingType != null ? implementingType : throw ProviderConfigurationEntry.tracer.NewArgumentNullException(nameof(implementingType));
         if (!string.IsNullOrEmpty(helpFileName))
         {
             this._helpFileName = helpFileName.Trim();
         }
         else
         {
             this._helpFileName = helpFileName;
         }
     }
 }
        internal Collection <PSSnapInInfo> GetPSSnapIn(
            string pattern,
            bool searchRegistry)
        {
            bool flag = WildcardPattern.ContainsWildcardCharacters(pattern);

            if (!flag)
            {
                PSSnapInInfo.VerifyPSSnapInFormatThrowIfError(pattern);
            }
            Collection <PSSnapInInfo> collection1 = searchRegistry ? PSSnapInReader.ReadAll() : this.PSSnapIns;
            Collection <PSSnapInInfo> collection2 = new Collection <PSSnapInInfo>();

            if (collection1 == null)
            {
                return(collection2);
            }
            if (!flag)
            {
                foreach (PSSnapInInfo psSnapInInfo in collection1)
                {
                    if (string.Equals(psSnapInInfo.Name, pattern, StringComparison.OrdinalIgnoreCase))
                    {
                        collection2.Add(psSnapInInfo);
                    }
                }
            }
            else
            {
                WildcardPattern wildcardPattern = new WildcardPattern(pattern, WildcardOptions.IgnoreCase);
                foreach (PSSnapInInfo psSnapInInfo in collection1)
                {
                    if (wildcardPattern.IsMatch(psSnapInInfo.Name))
                    {
                        collection2.Add(psSnapInInfo);
                    }
                }
            }
            return(collection2);
        }
Exemple #8
0
 private static bool RunScript(string cmd)
 {
     // create Powershell runspace
     try {
         RunspaceConfiguration rsConfig        = RunspaceConfiguration.Create();
         PSSnapInException     snapInException = null;
         PSSnapInInfo          info            = rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out snapInException);
         Runspace myRunSpace = RunspaceFactory.CreateRunspace(rsConfig);
         myRunSpace.Open();
         Pipeline pipeLine  = myRunSpace.CreatePipeline();
         Command  myCommand = new Command(cmd, true);
         pipeLine.Commands.Add(myCommand);
         Collection <PSObject> commandResults = pipeLine.Invoke();
         foreach (PSObject obj in commandResults)
         {
             Console.WriteLine(obj.ToString());
         }
         return(true);
     } catch (Exception ex) {
         return(false);
     }
 }
Exemple #9
0
        private void UnloadPSSnapIn(PSSnapInInfo mshsnapinInfo, out PSSnapInException warning)
        {
            warning = null;

            if (mshsnapinInfo != null)
            {
                this.Cmdlets.RemovePSSnapIn(mshsnapinInfo.Name);
                this.Providers.RemovePSSnapIn(mshsnapinInfo.Name);
                this.Assemblies.RemovePSSnapIn(mshsnapinInfo.Name);
                this.Types.RemovePSSnapIn(mshsnapinInfo.Name);
                this.Formats.RemovePSSnapIn(mshsnapinInfo.Name);

                string errors;
                UpdateAll(out errors);

                if (!String.IsNullOrEmpty(errors))
                {
                    s_mshsnapinTracer.TraceWarning(errors);
                    warning = new PSSnapInException(mshsnapinInfo.Name, errors, true);
                }
            }
        }
Exemple #10
0
 private void LoadPSSnapIn(PSSnapInInfo mshsnapinInfo)
 {
     if (mshsnapinInfo != null)
     {
         if (!string.IsNullOrEmpty(mshsnapinInfo.CustomPSSnapInType))
         {
             this.LoadCustomPSSnapIn(mshsnapinInfo);
         }
         else
         {
             Assembly assembly = null;
             _mshsnapinTracer.WriteLine("Loading assembly for mshsnapin {0}", new object[] { mshsnapinInfo.Name });
             assembly = this.LoadMshSnapinAssembly(mshsnapinInfo);
             if (assembly == null)
             {
                 _mshsnapinTracer.TraceError("Loading assembly for mshsnapin {0} failed", new object[] { mshsnapinInfo.Name });
             }
             else
             {
                 _mshsnapinTracer.WriteLine("Loading assembly for mshsnapin {0} succeeded", new object[] { mshsnapinInfo.Name });
                 this.AnalyzeMshSnapinAssembly(assembly, mshsnapinInfo);
                 foreach (string str in mshsnapinInfo.Types)
                 {
                     string name = Path.Combine(mshsnapinInfo.ApplicationBase, str);
                     TypeConfigurationEntry entry = new TypeConfigurationEntry(name, name, mshsnapinInfo);
                     this.Types.AddBuiltInItem(entry);
                 }
                 foreach (string str3 in mshsnapinInfo.Formats)
                 {
                     string str4 = Path.Combine(mshsnapinInfo.ApplicationBase, str3);
                     FormatConfigurationEntry entry2 = new FormatConfigurationEntry(str4, str4, mshsnapinInfo);
                     this.Formats.AddBuiltInItem(entry2);
                 }
                 AssemblyConfigurationEntry item = new AssemblyConfigurationEntry(mshsnapinInfo.AssemblyName, mshsnapinInfo.AbsoluteModulePath, mshsnapinInfo);
                 this.Assemblies.AddBuiltInItem(item);
             }
         }
     }
 }
Exemple #11
0
 /// <summary>
 /// Removes all cmdlets of a specific PSSnapIn
 /// </summary>
 /// <param name="snapinInfo">Information about the PSSnapIn whose cmdlets should be removed</param>
 internal void RemoveCmdlets(PSSnapInInfo snapinInfo)
 {
     foreach (var pair in _cmdLets)
     {
         Collection <CmdletInfo> removables = new Collection <CmdletInfo>();
         foreach (var cmdlet in pair.Value)
         {
             if (cmdlet.PSSnapIn == null) // not loaded with a snapin. e.g. with a module
             {
                 continue;
             }
             if (cmdlet.PSSnapIn.Equals(snapinInfo))
             {
                 removables.Add(cmdlet);
             }
         }
         foreach (var rmCmdlet in removables)
         {
             pair.Value.Remove(rmCmdlet);
         }
     }
 }
        public static string ExecPowerShellCommand(string sCommand, bool bRemoveEmptyLines)
        {
            if (runspace == null)
            {
                PSSnapInInfo      info = null;
                PSSnapInException ex   = null;
                bool error             = false;

                try
                {
                    runspace = RunspaceFactory.CreateRunspace(RunspaceConfiguration.Create());
                    runspace.Open();

                    foreach (string pssnapin in ExchangePsSnapin)
                    {
                        if (Execute("$(Get-PSSnapin -Registered | Select-String " + pssnapin + ") -ne $null", true).Trim() == "True")
                        {
                            info = runspace.RunspaceConfiguration.AddPSSnapIn(pssnapin, out ex);
                        }
                    }
                }
                catch (Exception)
                {
                    error = true;
                }

                if (ex != null || info == null || error)
                {
                    if (runspace != null)
                    {
                        runspace.Dispose();
                        runspace = null;
                    }
                    throw new ExchangeServerException("Couldn't initialize PowerShell runspace.");
                }
            }

            return(Execute(sCommand, bRemoveEmptyLines));
        }
Exemple #13
0
        internal override PSSnapInInfo DoAddPSSnapIn(string name, out PSSnapInException warning)
        {
            warning = null;
            _mshsnapinTracer.WriteLine("Adding mshsnapin {0}", new object[] { name });
            if (this._consoleInfo == null)
            {
                return(null);
            }
            PSSnapInInfo mshsnapinInfo = null;

            try
            {
                mshsnapinInfo = this._consoleInfo.AddPSSnapIn(name);
            }
            catch (PSArgumentException exception)
            {
                _mshsnapinTracer.TraceError(exception.Message, new object[0]);
                _mshsnapinTracer.WriteLine("Adding mshsnapin {0} failed.", new object[] { name });
                throw;
            }
            catch (PSArgumentNullException exception2)
            {
                _mshsnapinTracer.TraceError(exception2.Message, new object[0]);
                _mshsnapinTracer.WriteLine("Adding mshsnapin {0} failed.", new object[] { name });
                throw;
            }
            if (mshsnapinInfo == null)
            {
                return(null);
            }
            this.LoadPSSnapIn(mshsnapinInfo, out warning);
            if (warning != null)
            {
                _mshsnapinTracer.TraceWarning("There was a warning when loading mshsnapin {0}: {1}", new object[] { name, warning.Message });
            }
            _mshsnapinTracer.WriteLine("MshSnapin {0} added", new object[] { name });
            return(mshsnapinInfo);
        }
Exemple #14
0
        protected Collection <PSSnapInInfo> GetSnapIns(string pattern)
        {
            Collection <PSSnapInInfo> results;

            if (WildcardPattern.ContainsWildcardCharacters(pattern))
            {
                results = ExecutionContext.SessionStateGlobal.GetPSSnapIns(new WildcardPattern(pattern));
            }
            else //usual name
            {
                results = new Collection <PSSnapInInfo>();
                PSSnapInInfo info = ExecutionContext.SessionStateGlobal.GetPSSnapIn(pattern);
                if (info != null)
                {
                    results.Add(info);
                }
            }
            if (results.Count < 1)
            {
                throw new PSArgumentException(String.Format(NoSnapinsFoundFormat, pattern));
            }
            return(results);
        }
Exemple #15
0
        private void LoadPSSnapIn(PSSnapInInfo mshsnapinInfo, out PSSnapInException warning)
        {
            string str;

            warning = null;
            try
            {
                this.LoadPSSnapIn(mshsnapinInfo);
            }
            catch (PSSnapInException)
            {
                if (!mshsnapinInfo.IsDefault)
                {
                    this._consoleInfo.RemovePSSnapIn(mshsnapinInfo.Name);
                }
                throw;
            }
            this.UpdateAll(out str);
            if (!string.IsNullOrEmpty(str))
            {
                _mshsnapinTracer.TraceWarning("There was a warning while loading mshsnapin {0}:{1}", new object[] { mshsnapinInfo.Name, str });
                warning = new PSSnapInException(mshsnapinInfo.Name, str, true);
            }
        }
Exemple #16
0
        // TODO: separate providers from cmdlets
        internal Collection <CmdletInfo> LoadCmdletsFromPSSnapin(string strType, out Collection <SnapinProviderPair> providers)
        {
            Type     snapinType = Type.GetType(strType, true);
            Assembly assembly   = snapinType.Assembly;

            PSSnapIn snapin = Activator.CreateInstance(snapinType) as PSSnapIn;

            PSSnapInInfo snapinInfo = new PSSnapInInfo(snapin.Name, false, string.Empty, assembly.GetName().Name, string.Empty, new Version(1, 0), null, null, null, snapin.Description, snapin.Vendor);

            var snapinProviderPairs = from Type type in assembly.GetTypes()
                                      where !type.IsSubclassOf(typeof(Cmdlet))
                                      where type.IsSubclassOf(typeof(CmdletProvider))
                                      from CmdletProviderAttribute providerAttr in type.GetCustomAttributes(typeof(CmdletProviderAttribute), true)
                                      select new SnapinProviderPair
            {
                snapinInfo   = snapinInfo,
                providerType = type,
                providerAttr = providerAttr
            };

            providers = snapinProviderPairs.ToCollection();

            return(LoadCmdletsFromAssembly(assembly, snapinInfo).ToCollection());
        }
        private void LoadPSSnapIn(PSSnapInInfo mshsnapinInfo, out PSSnapInException warning)
        {
            warning = null;

            try
            {
                LoadPSSnapIn(mshsnapinInfo);
            }
            catch (PSSnapInException)
            {
                if (!mshsnapinInfo.IsDefault)
                    _consoleInfo.RemovePSSnapIn(mshsnapinInfo.Name);

                // exception during load mshsnapin are fatal. 
                throw;
            }

            string errors;

            UpdateAll(out errors);

            if (!String.IsNullOrEmpty(errors))
            {
                s_mshsnapinTracer.TraceWarning("There was a warning while loading mshsnapin {0}:{1}", mshsnapinInfo.Name, errors);

                warning = new PSSnapInException(mshsnapinInfo.Name, errors, true);
            }
        }
 internal ProviderConfigurationEntry(string name, Type implementingType, string helpFileName, PSSnapInInfo psSnapinInfo)
     : base(name, psSnapinInfo)
 {
     ImplementingType = implementingType;
     HelpFileName = helpFileName;
 }
        /// <summary>
        /// Initiate an instance for assembly configuration entry.
        /// </summary>
        /// <param name="name">Strong name of the assembly</param>
        /// <param name="fileName">Name of the assembly file</param>
        /// <param name="psSnapinInfo">PSSnapin information.</param>
        /// <exception cref="ArgumentException">when <paramref name="fileName"/> is null, empty or does not end in .ps1xml</exception>
        internal AssemblyConfigurationEntry(string name, string fileName, PSSnapInInfo psSnapinInfo)
            : base(name, psSnapinInfo)
        {
            if (String.IsNullOrEmpty(fileName) || String.IsNullOrEmpty(fileName.Trim()))
            {
                throw PSTraceSource.NewArgumentNullException("fileName");
            }

            FileName = fileName.Trim();
        }
 protected InitialSessionStateEntry(string name)
 {
     this.name     = name;
     this.psSnapIn = null;
     this.module   = null;
 }
 protected InitialSessionStateEntry(string name)
 {
     this.name = name;
     this.psSnapIn = null;
     this.module = null;
 }
        /// <summary>
        /// Initiate an instance for provider configuration entry.
        /// </summary>
        /// <param name="name">Name of the provider configuration entry</param>
        /// <param name="implementingType">Class that include implementation of the provider</param>
        /// <param name="helpFileName">Name of the help file that include help information for the provider</param>
        /// <param name="psSnapinInfo">PSSnapin from which provider comes from.</param>
        internal ProviderConfigurationEntry(string name, Type implementingType, string helpFileName, PSSnapInInfo psSnapinInfo)
            : base(name, psSnapinInfo)
        {
            if (implementingType == null)
            {
                throw PSTraceSource.NewArgumentNullException("implementingType");
            }

            ImplementingType = implementingType;

            if (!String.IsNullOrEmpty(helpFileName))
            {
                HelpFileName = helpFileName.Trim();
            }
            else
            {
                HelpFileName = helpFileName;
            }
        }
Exemple #23
0
        public void TestReadCoreEngineSnapIn()
        {
            PSSnapInInfo pSSnapInInfo = PSSnapInReader.ReadCoreEngineSnapIn();

            Assert.Contains("PublicKeyToken=31bf3856ad364e35", pSSnapInInfo.AssemblyName);
        }
 protected override void ProcessRecord()
 {
     foreach (string str in this._pssnapins)
     {
         Collection <PSSnapInInfo> snapIns = base.GetSnapIns(str);
         if (snapIns.Count == 0)
         {
             base.WriteNonTerminatingError(str, "NoPSSnapInsFound", PSTraceSource.NewArgumentException(str, "MshSnapInCmdletResources", "NoPSSnapInsFound", new object[] { str }), ErrorCategory.InvalidArgument);
         }
         else
         {
             foreach (PSSnapInInfo info in snapIns)
             {
                 if (base.ShouldProcess(info.Name))
                 {
                     Exception innerException = null;
                     if ((base.Runspace == null) && (base.Context.InitialSessionState != null))
                     {
                         try
                         {
                             PSSnapInException exception2;
                             PSSnapInInfo.VerifyPSSnapInFormatThrowIfError(info.Name);
                             if (MshConsoleInfo.IsDefaultPSSnapIn(info.Name, base.Context.InitialSessionState.defaultSnapins))
                             {
                                 throw PSTraceSource.NewArgumentException(info.Name, "ConsoleInfoErrorStrings", "CannotRemoveDefault", new object[] { info.Name });
                             }
                             InitialSessionState state = InitialSessionState.Create();
                             state.ImportPSSnapIn(info, out exception2);
                             state.Unbind(base.Context);
                             base.Context.InitialSessionState.ImportedSnapins.Remove(info.Name);
                         }
                         catch (PSArgumentException exception3)
                         {
                             innerException = exception3;
                         }
                         if (innerException != null)
                         {
                             base.WriteNonTerminatingError(str, "RemovePSSnapIn", innerException, ErrorCategory.InvalidArgument);
                         }
                     }
                     else
                     {
                         try
                         {
                             PSSnapInException warning        = null;
                             PSSnapInInfo      sendToPipeline = base.Runspace.RemovePSSnapIn(info.Name, out warning);
                             if (warning != null)
                             {
                                 base.WriteNonTerminatingError(info.Name, "RemovePSSnapInRead", warning, ErrorCategory.InvalidData);
                             }
                             if (this._passThru)
                             {
                                 sendToPipeline.LoadIndirectResources(base.ResourceReader);
                                 base.WriteObject(sendToPipeline);
                             }
                         }
                         catch (PSArgumentException exception5)
                         {
                             innerException = exception5;
                         }
                         if (innerException != null)
                         {
                             base.WriteNonTerminatingError(str, "RemovePSSnapIn", innerException, ErrorCategory.InvalidArgument);
                         }
                     }
                 }
             }
         }
     }
 }
        private Assembly LoadMshSnapinAssembly(PSSnapInInfo mshsnapinInfo)
        {
            Assembly assembly = null;

            s_mshsnapinTracer.WriteLine("Loading assembly from GAC. Assembly Name: {0}", mshsnapinInfo.AssemblyName);

            try
            {
                // WARNING: DUPLICATE CODE see InitialSessionState
                assembly = Assembly.Load(new AssemblyName(mshsnapinInfo.AssemblyName));
            }
            catch (FileLoadException e)
            {
                s_mshsnapinTracer.TraceWarning("Not able to load assembly {0}: {1}", mshsnapinInfo.AssemblyName, e.Message);
            }
            catch (BadImageFormatException e)
            {
                s_mshsnapinTracer.TraceWarning("Not able to load assembly {0}: {1}", mshsnapinInfo.AssemblyName, e.Message);
            }
            catch (FileNotFoundException e)
            {
                s_mshsnapinTracer.TraceWarning("Not able to load assembly {0}: {1}", mshsnapinInfo.AssemblyName, e.Message);
            }

            if (assembly != null)
                return assembly;

            s_mshsnapinTracer.WriteLine("Loading assembly from path: {0}", mshsnapinInfo.AssemblyName);

            try
            {
                AssemblyName assemblyName = ClrFacade.GetAssemblyName(mshsnapinInfo.AbsoluteModulePath);
                if (string.Compare(assemblyName.FullName, mshsnapinInfo.AssemblyName, StringComparison.OrdinalIgnoreCase) != 0)
                {
                    string message = StringUtil.Format(ConsoleInfoErrorStrings.PSSnapInAssemblyNameMismatch, mshsnapinInfo.AbsoluteModulePath, mshsnapinInfo.AssemblyName);
                    s_mshsnapinTracer.TraceError(message);
                    throw new PSSnapInException(mshsnapinInfo.Name, message);
                }

                assembly = ClrFacade.LoadFrom(mshsnapinInfo.AbsoluteModulePath);
            }
            catch (FileLoadException e)
            {
                s_mshsnapinTracer.TraceError("Not able to load assembly {0}: {1}", mshsnapinInfo.AssemblyName, e.Message);
                throw new PSSnapInException(mshsnapinInfo.Name, e.Message);
            }
            catch (BadImageFormatException e)
            {
                s_mshsnapinTracer.TraceError("Not able to load assembly {0}: {1}", mshsnapinInfo.AssemblyName, e.Message);
                throw new PSSnapInException(mshsnapinInfo.Name, e.Message);
            }
            catch (FileNotFoundException e)
            {
                s_mshsnapinTracer.TraceError("Not able to load assembly {0}: {1}", mshsnapinInfo.AssemblyName, e.Message);
                throw new PSSnapInException(mshsnapinInfo.Name, e.Message);
            }

            return assembly;
        }
        private void MergeCustomPSSnapIn(PSSnapInInfo mshsnapinInfo, CustomPSSnapIn customPSSnapIn)
        {
            if (mshsnapinInfo == null || customPSSnapIn == null)
                return;

            s_mshsnapinTracer.WriteLine("Merging configuration from custom mshsnapin {0}", mshsnapinInfo.Name);

            if (customPSSnapIn.Cmdlets != null)
            {
                foreach (CmdletConfigurationEntry entry in customPSSnapIn.Cmdlets)
                {
                    CmdletConfigurationEntry cmdlet = new CmdletConfigurationEntry(entry.Name, entry.ImplementingType, entry.HelpFileName, mshsnapinInfo);
                    _cmdlets.AddBuiltInItem(cmdlet);
                }
            }

            if (customPSSnapIn.Providers != null)
            {
                foreach (ProviderConfigurationEntry entry in customPSSnapIn.Providers)
                {
                    ProviderConfigurationEntry provider = new ProviderConfigurationEntry(entry.Name, entry.ImplementingType, entry.HelpFileName, mshsnapinInfo);
                    _providers.AddBuiltInItem(provider);
                }
            }

            if (customPSSnapIn.Types != null)
            {
                foreach (TypeConfigurationEntry entry in customPSSnapIn.Types)
                {
                    string path = Path.Combine(mshsnapinInfo.ApplicationBase, entry.FileName);
                    TypeConfigurationEntry type = new TypeConfigurationEntry(entry.Name, path, mshsnapinInfo);
                    _types.AddBuiltInItem(type);
                }
            }

            if (customPSSnapIn.Formats != null)
            {
                foreach (FormatConfigurationEntry entry in customPSSnapIn.Formats)
                {
                    string path = Path.Combine(mshsnapinInfo.ApplicationBase, entry.FileName);
                    FormatConfigurationEntry format = new FormatConfigurationEntry(entry.Name, path, mshsnapinInfo);
                    _formats.AddBuiltInItem(format);
                }
            }

            AssemblyConfigurationEntry assemblyEntry = new AssemblyConfigurationEntry(mshsnapinInfo.AssemblyName, mshsnapinInfo.AbsoluteModulePath, mshsnapinInfo);
            this.Assemblies.AddBuiltInItem(assemblyEntry);

            s_mshsnapinTracer.WriteLine("Configuration from custom mshsnapin {0} merged", mshsnapinInfo.Name);
        }
Exemple #27
0
 private void AnalyzeMshSnapinAssembly(Assembly assembly, PSSnapInInfo mshsnapinInfo)
 {
     if (assembly != null)
     {
         _mshsnapinTracer.WriteLine("Analyzing assembly {0} for cmdlet and providers", new object[] { assembly.Location });
         string helpFile      = GetHelpFile(assembly.Location);
         Type[] exportedTypes = null;
         try
         {
             exportedTypes = assembly.GetExportedTypes();
         }
         catch (ReflectionTypeLoadException exception)
         {
             string errorMessageFormat = exception.Message + "\nLoader Exceptions: \n";
             if (exception.LoaderExceptions != null)
             {
                 foreach (Exception exception2 in exception.LoaderExceptions)
                 {
                     errorMessageFormat = errorMessageFormat + "\n" + exception2.Message;
                 }
             }
             _mshsnapinTracer.TraceError(errorMessageFormat, new object[0]);
             throw new PSSnapInException(mshsnapinInfo.Name, errorMessageFormat);
         }
         Hashtable hashtable  = new Hashtable(StringComparer.OrdinalIgnoreCase);
         Hashtable hashtable2 = new Hashtable(StringComparer.OrdinalIgnoreCase);
         foreach (Type type in exportedTypes)
         {
             string   cmdletName       = null;
             string   providerName     = null;
             object[] customAttributes = type.GetCustomAttributes(typeof(CmdletAttribute), false);
             if (customAttributes.Length > 0)
             {
                 cmdletName = GetCmdletName(customAttributes[0] as CmdletAttribute);
             }
             else
             {
                 customAttributes = type.GetCustomAttributes(typeof(CmdletProviderAttribute), false);
                 if (customAttributes.Length > 0)
                 {
                     providerName = GetProviderName(customAttributes[0] as CmdletProviderAttribute);
                 }
             }
             if (!string.IsNullOrEmpty(cmdletName))
             {
                 if (IsCmdletClass(type) && HasDefaultConstructor(type))
                 {
                     if (hashtable.ContainsKey(cmdletName))
                     {
                         string str5 = StringUtil.Format(ConsoleInfoErrorStrings.PSSnapInDuplicateCmdlets, cmdletName, mshsnapinInfo.Name);
                         _mshsnapinTracer.TraceError(str5, new object[0]);
                         throw new PSSnapInException(mshsnapinInfo.Name, str5);
                     }
                     hashtable.Add(cmdletName, null);
                     CmdletConfigurationEntry item = new CmdletConfigurationEntry(cmdletName, type, helpFile, mshsnapinInfo);
                     this._cmdlets.AddBuiltInItem(item);
                     _mshsnapinTracer.WriteLine("{0} from type {1} is added as a cmdlet. ", new object[] { cmdletName, type.FullName });
                     continue;
                 }
                 _mshsnapinTracer.TraceWarning("{0} is not valid cmdlet because it doesn't derive from the Cmdlet type or it doesn't have a default constructor.", new object[] { cmdletName });
             }
             if (!string.IsNullOrEmpty(providerName))
             {
                 if (IsProviderClass(type) && HasDefaultConstructor(type))
                 {
                     if (hashtable2.ContainsKey(providerName))
                     {
                         string str6 = StringUtil.Format(ConsoleInfoErrorStrings.PSSnapInDuplicateProviders, providerName, mshsnapinInfo.Name);
                         _mshsnapinTracer.TraceError(str6, new object[0]);
                         throw new PSSnapInException(mshsnapinInfo.Name, str6);
                     }
                     hashtable2.Add(providerName, null);
                     ProviderConfigurationEntry entry2 = new ProviderConfigurationEntry(providerName, type, helpFile, mshsnapinInfo);
                     this._providers.AddBuiltInItem(entry2);
                     _mshsnapinTracer.WriteLine("{0} from type {1} is added as a provider. ", new object[] { providerName, type.FullName });
                     continue;
                 }
                 _mshsnapinTracer.TraceWarning("{0} is not valid provider because it doesn't derive from the provider type or it doesn't have a default constructor.", new object[] { providerName });
             }
             if (typeof(IModuleAssemblyInitializer).IsAssignableFrom(type) && !type.Equals(typeof(IModuleAssemblyInitializer)))
             {
                 _mshsnapinTracer.TraceWarning("Calling module initializer defined by type {0}", new object[] { type.FullName });
                 (Activator.CreateInstance(type, true) as IModuleAssemblyInitializer).OnImport();
             }
         }
     }
 }
        /// <summary>
        /// Adds one or more snapins
        /// </summary>
        /// <param name="snapInList">List of snapin IDs</param>
        /// <remarks>
        /// This is a helper method and should not throw any
        /// exceptions. All exceptions are caught and displayed
        /// to the user using write* methods
        /// </remarks>
        private void AddPSSnapIns(Collection <string> snapInList)
        {
            if (snapInList == null)
            {
                // nothing to add
                return;
            }

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

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

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

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

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

                return;
            }

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

                try
                {
                    PSSnapInException warning = null;

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

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

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

                if (exception != null)
                {
                    WriteNonTerminatingError(psSnapIn,
                                             "AddPSSnapInRead",
                                             exception,
                                             ErrorCategory.InvalidArgument);
                }
            }
        }
Exemple #29
0
 public void LoadCmdletsFromAssembly(Assembly assembly, PSSnapInInfo snapinInfo)
 {
     LoadCmdletsFromAssembly(assembly, snapinInfo, null);
 }
        private void LoadPSSnapIn(PSSnapInInfo mshsnapinInfo)
        {
            if (mshsnapinInfo == null)
                return;

#if !CORECLR // CustomPSSnapIn Not Supported On CSS. 
            if (!String.IsNullOrEmpty(mshsnapinInfo.CustomPSSnapInType))
            {
                LoadCustomPSSnapIn(mshsnapinInfo);
                return;
            }
#endif
            Assembly assembly = null;

            s_mshsnapinTracer.WriteLine("Loading assembly for mshsnapin {0}", mshsnapinInfo.Name);

            assembly = LoadMshSnapinAssembly(mshsnapinInfo);

            if (assembly == null)
            {
                s_mshsnapinTracer.TraceError("Loading assembly for mshsnapin {0} failed", mshsnapinInfo.Name);
                return;
            }

            s_mshsnapinTracer.WriteLine("Loading assembly for mshsnapin {0} succeeded", mshsnapinInfo.Name);

            Dictionary<string, SessionStateCmdletEntry> cmdlets = null;
            Dictionary<string, List<SessionStateAliasEntry>> aliases = null;
            Dictionary<string, SessionStateProviderEntry> providers = null;
            string throwAwayHelpFile = null;
            PSSnapInHelpers.AnalyzePSSnapInAssembly(assembly, assembly.Location, mshsnapinInfo, null, false, out cmdlets, out aliases, out providers, out throwAwayHelpFile);
            if (cmdlets != null)
            {
                foreach (var c in cmdlets)
                {
                    CmdletConfigurationEntry cmdlet = new CmdletConfigurationEntry(c.Key, c.Value.ImplementingType,
                                                                                   c.Value.HelpFileName, mshsnapinInfo);
                    _cmdlets.AddBuiltInItem(cmdlet);
                }
            }
            if (providers != null)
            {
                foreach (var p in providers)
                {
                    ProviderConfigurationEntry provider = new ProviderConfigurationEntry(p.Key, p.Value.ImplementingType,
                                                                                         p.Value.HelpFileName,
                                                                                         mshsnapinInfo);
                    _providers.AddBuiltInItem(provider);
                }
            }

            foreach (string file in mshsnapinInfo.Types)
            {
                string path = Path.Combine(mshsnapinInfo.ApplicationBase, file);

                TypeConfigurationEntry typeEntry = new TypeConfigurationEntry(path, path, mshsnapinInfo);
                this.Types.AddBuiltInItem(typeEntry);
            }

            foreach (string file in mshsnapinInfo.Formats)
            {
                string path = Path.Combine(mshsnapinInfo.ApplicationBase, file);

                FormatConfigurationEntry formatEntry = new FormatConfigurationEntry(path, path, mshsnapinInfo);
                this.Formats.AddBuiltInItem(formatEntry);
            }

            AssemblyConfigurationEntry assemblyEntry = new AssemblyConfigurationEntry(mshsnapinInfo.AssemblyName, mshsnapinInfo.AbsoluteModulePath, mshsnapinInfo);
            this.Assemblies.AddBuiltInItem(assemblyEntry);

            return;
        }
Exemple #31
0
        internal static Assembly LoadPSSnapInAssembly(
            PSSnapInInfo psSnapInInfo,
            out Dictionary <string, SessionStateCmdletEntry> cmdlets,
            out Dictionary <string, SessionStateProviderEntry> providers)
        {
            Assembly assembly1 = (Assembly)null;

            cmdlets   = (Dictionary <string, SessionStateCmdletEntry>)null;
            providers = (Dictionary <string, SessionStateProviderEntry>)null;
            PSSnapInHelpers._PSSnapInTracer.WriteLine("Loading assembly from GAC. Assembly Name: {0}", (object)psSnapInInfo.AssemblyName);
            try
            {
                assembly1 = Assembly.Load(psSnapInInfo.AssemblyName);
            }
            catch (FileLoadException ex)
            {
                PSSnapInHelpers._PSSnapInTracer.TraceWarning("Not able to load assembly {0}: {1}", (object)psSnapInInfo.AssemblyName, (object)ex.Message);
            }
            catch (BadImageFormatException ex)
            {
                PSSnapInHelpers._PSSnapInTracer.TraceWarning("Not able to load assembly {0}: {1}", (object)psSnapInInfo.AssemblyName, (object)ex.Message);
            }
            catch (FileNotFoundException ex)
            {
                PSSnapInHelpers._PSSnapInTracer.TraceWarning("Not able to load assembly {0}: {1}", (object)psSnapInInfo.AssemblyName, (object)ex.Message);
            }
            if (assembly1 != null)
            {
                return(assembly1);
            }
            PSSnapInHelpers._PSSnapInTracer.WriteLine("Loading assembly from path: {0}", (object)psSnapInInfo.AssemblyName);
            try
            {
                Assembly assembly2 = Assembly.ReflectionOnlyLoadFrom(psSnapInInfo.AbsoluteModulePath);
                if (assembly2 == null)
                {
                    return((Assembly)null);
                }
                if (!string.Equals(assembly2.FullName, psSnapInInfo.AssemblyName, StringComparison.OrdinalIgnoreCase))
                {
                    string str = ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "PSSnapInAssemblyNameMismatch", (object)psSnapInInfo.AbsoluteModulePath, (object)psSnapInInfo.AssemblyName);
                    PSSnapInHelpers._PSSnapInTracer.TraceError(str);
                    throw new PSSnapInException(psSnapInInfo.Name, str);
                }
                return(Assembly.LoadFrom(psSnapInInfo.AbsoluteModulePath));
            }
            catch (FileLoadException ex)
            {
                PSSnapInHelpers._PSSnapInTracer.TraceError("Not able to load assembly {0}: {1}", (object)psSnapInInfo.AssemblyName, (object)ex.Message);
                throw new PSSnapInException(psSnapInInfo.Name, ex.Message);
            }
            catch (BadImageFormatException ex)
            {
                PSSnapInHelpers._PSSnapInTracer.TraceError("Not able to load assembly {0}: {1}", (object)psSnapInInfo.AssemblyName, (object)ex.Message);
                throw new PSSnapInException(psSnapInInfo.Name, ex.Message);
            }
            catch (FileNotFoundException ex)
            {
                PSSnapInHelpers._PSSnapInTracer.TraceError("Not able to load assembly {0}: {1}", (object)psSnapInInfo.AssemblyName, (object)ex.Message);
                throw new PSSnapInException(psSnapInInfo.Name, ex.Message);
            }
        }
        private void LoadCustomPSSnapIn(PSSnapInInfo mshsnapinInfo)
        {
            if (mshsnapinInfo == null)
                return;

            if (String.IsNullOrEmpty(mshsnapinInfo.CustomPSSnapInType))
            {
                return;
            }

            Assembly assembly = null;

            s_mshsnapinTracer.WriteLine("Loading assembly for mshsnapin {0}", mshsnapinInfo.Name);

            assembly = LoadMshSnapinAssembly(mshsnapinInfo);

            if (assembly == null)
            {
                s_mshsnapinTracer.TraceError("Loading assembly for mshsnapin {0} failed", mshsnapinInfo.Name);
                return;
            }

            CustomPSSnapIn customPSSnapIn = null;
            try
            {
                Type type = assembly.GetType(mshsnapinInfo.CustomPSSnapInType, true, false);

                if (type != null)
                {
                    customPSSnapIn = (CustomPSSnapIn)Activator.CreateInstance(type);
                }

                s_mshsnapinTracer.WriteLine("Loading assembly for mshsnapin {0} succeeded", mshsnapinInfo.Name);
            }
            catch (TypeLoadException tle)
            {
                throw new PSSnapInException(mshsnapinInfo.Name, tle.Message);
            }
            catch (ArgumentException ae)
            {
                throw new PSSnapInException(mshsnapinInfo.Name, ae.Message);
            }
            catch (MissingMethodException mme)
            {
                throw new PSSnapInException(mshsnapinInfo.Name, mme.Message);
            }
            catch (InvalidCastException ice)
            {
                throw new PSSnapInException(mshsnapinInfo.Name, ice.Message);
            }
            catch (TargetInvocationException tie)
            {
                if (tie.InnerException != null)
                {
                    throw new PSSnapInException(mshsnapinInfo.Name, tie.InnerException.Message);
                }

                throw new PSSnapInException(mshsnapinInfo.Name, tie.Message);
            }

            MergeCustomPSSnapIn(mshsnapinInfo, customPSSnapIn);
            return;
        }
Exemple #33
0
 private void ProcessSnapIn(PSSnapInInfo snapinInfo)
 {
     ProcessPath(PscxPathInfo.GetPscxPathInfo(this.SessionState, snapinInfo.ModuleName));
 }
        private void UnloadPSSnapIn(PSSnapInInfo mshsnapinInfo, out PSSnapInException warning)
        {
            warning = null;

            if (mshsnapinInfo != null)
            {
                this.Cmdlets.RemovePSSnapIn(mshsnapinInfo.Name);
                this.Providers.RemovePSSnapIn(mshsnapinInfo.Name);
                this.Assemblies.RemovePSSnapIn(mshsnapinInfo.Name);
                this.Types.RemovePSSnapIn(mshsnapinInfo.Name);
                this.Formats.RemovePSSnapIn(mshsnapinInfo.Name);

                string errors;
                UpdateAll(out errors);

                if (!String.IsNullOrEmpty(errors))
                {
                    s_mshsnapinTracer.TraceWarning(errors);
                    warning = new PSSnapInException(mshsnapinInfo.Name, errors, true);
                }
            }
        }
        /// <summary>
        /// Routine to get the list of loaded snapins...
        /// </summary>
        /// <returns></returns>
        protected internal Collection <PSSnapInInfo> GetSnapIns(string pattern)
        {
            // If RunspaceConfiguration is not null, then return the list that it has
            if (Runspace != null)
            {
                if (pattern != null)
                {
                    return(Runspace.ConsoleInfo.GetPSSnapIn(pattern, _shouldGetAll));
                }
                else
                {
                    return(Runspace.ConsoleInfo.PSSnapIns);
                }
            }

            WildcardPattern matcher = null;

            if (!String.IsNullOrEmpty(pattern))
            {
                bool doWildCardSearch = WildcardPattern.ContainsWildcardCharacters(pattern);

                if (!doWildCardSearch)
                {
                    // Verify PSSnapInID..
                    // This will throw if it not a valid name
                    PSSnapInInfo.VerifyPSSnapInFormatThrowIfError(pattern);
                }
                matcher = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);
            }

            Collection <PSSnapInInfo> snapins = new Collection <PSSnapInInfo>();

            if (_shouldGetAll)
            {
                foreach (PSSnapInInfo snapinKey in PSSnapInReader.ReadAll())
                {
                    if (matcher == null || matcher.IsMatch(snapinKey.Name))
                    {
                        snapins.Add(snapinKey);
                    }
                }
            }
            else
            {
                // Otherwise, just scan through the list of cmdlets and rebuild the table.
                List <CmdletInfo> cmdlets = InvokeCommand.GetCmdlets();
                Dictionary <PSSnapInInfo, bool> snapinTable = new Dictionary <PSSnapInInfo, bool>();
                foreach (CmdletInfo cmdlet in cmdlets)
                {
                    PSSnapInInfo snapin = cmdlet.PSSnapIn;
                    if (snapin != null && !snapinTable.ContainsKey(snapin))
                    {
                        snapinTable.Add(snapin, true);
                    }
                }

                foreach (PSSnapInInfo snapinKey in snapinTable.Keys)
                {
                    if (matcher == null || matcher.IsMatch(snapinKey.Name))
                    {
                        snapins.Add(snapinKey);
                    }
                }
            }
            return(snapins);
        }
        /// <summary>
        /// See if the snapin is already loaded..returns load snapin info if true, null otherwise.
        /// </summary>
        /// <returns></returns>
        internal static PSSnapInInfo IsSnapInLoaded(Collection <PSSnapInInfo> loadedSnapins, PSSnapInInfo psSnapInInfo)
        {
            if (null == loadedSnapins)
            {
                return(null);
            }

            foreach (PSSnapInInfo loadedPSSnapInInfo in loadedSnapins)
            {
                // See if the assembly-qualified names match and return the existing PSSnapInInfo
                // if they do.
                string loadedSnapInAssemblyName = loadedPSSnapInInfo.AssemblyName;
                if (string.Equals(loadedPSSnapInInfo.Name, psSnapInInfo.Name, StringComparison.OrdinalIgnoreCase) &&
                    !string.IsNullOrEmpty(loadedSnapInAssemblyName) &&
                    string.Equals(loadedSnapInAssemblyName, psSnapInInfo.AssemblyName, System.StringComparison.OrdinalIgnoreCase))
                {
                    return(loadedPSSnapInInfo);
                }
            }

            return(null);
        }
        /// <summary>
        /// Load help file provided.
        /// </summary>
        /// <remarks>
        /// This will load providerHelpInfo from help file into help cache.
        /// </remarks>
        /// <param name="providerInfo">ProviderInfo for which to locate help.</param>
        private void LoadHelpFile(ProviderInfo providerInfo)
        {
            if (providerInfo == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(providerInfo));
            }

            string helpFile = providerInfo.HelpFile;

            if (string.IsNullOrEmpty(helpFile) || _helpFiles.Contains(helpFile))
            {
                return;
            }

            string helpFileToLoad = helpFile;

            // Get the mshsnapinfo object for this cmdlet.
            PSSnapInInfo mshSnapInInfo = providerInfo.PSSnapIn;

            // Search fallback
            // 1. If PSSnapInInfo exists, then always look in the application base
            //    of the mshsnapin
            // Otherwise,
            //    Look in the default search path and cmdlet assembly path
            Collection <string> searchPaths = new Collection <string>();

            if (mshSnapInInfo != null)
            {
                Diagnostics.Assert(!string.IsNullOrEmpty(mshSnapInInfo.ApplicationBase),
                                   "Application Base is null or empty.");
                // not minishell case..
                // we have to search only in the application base for a mshsnapin...
                // if you create an absolute path for helpfile, then MUIFileSearcher
                // will look only in that path.
                helpFileToLoad = Path.Combine(mshSnapInInfo.ApplicationBase, helpFile);
            }
            else if ((providerInfo.Module != null) && (!string.IsNullOrEmpty(providerInfo.Module.Path)))
            {
                helpFileToLoad = Path.Combine(providerInfo.Module.ModuleBase, helpFile);
            }
            else
            {
                searchPaths.Add(GetDefaultShellSearchPath());
                searchPaths.Add(GetProviderAssemblyPath(providerInfo));
            }

            string location = MUIFileSearcher.LocateFile(helpFileToLoad, searchPaths);

            if (string.IsNullOrEmpty(location))
            {
                throw new FileNotFoundException(helpFile);
            }

            XmlDocument doc = InternalDeserializer.LoadUnsafeXmlDocument(
                new FileInfo(location),
                false, /* ignore whitespace, comments, etc. */
                null); /* default maxCharactersInDocument */

            // Add this file into _helpFiles hashtable to prevent it to be loaded again.
            _helpFiles[helpFile] = 0;

            XmlNode helpItemsNode = null;

            if (doc.HasChildNodes)
            {
                for (int i = 0; i < doc.ChildNodes.Count; i++)
                {
                    XmlNode node = doc.ChildNodes[i];
                    if (node.NodeType == XmlNodeType.Element && string.Equals(node.Name, "helpItems", StringComparison.OrdinalIgnoreCase))
                    {
                        helpItemsNode = node;
                        break;
                    }
                }
            }

            if (helpItemsNode == null)
            {
                return;
            }

            using (this.HelpSystem.Trace(location))
            {
                if (helpItemsNode.HasChildNodes)
                {
                    for (int i = 0; i < helpItemsNode.ChildNodes.Count; i++)
                    {
                        XmlNode node = helpItemsNode.ChildNodes[i];
                        if (node.NodeType == XmlNodeType.Element && string.Equals(node.Name, "providerHelp", StringComparison.OrdinalIgnoreCase))
                        {
                            HelpInfo helpInfo = ProviderHelpInfo.Load(node);

                            if (helpInfo != null)
                            {
                                this.HelpSystem.TraceErrors(helpInfo.Errors);
                                // Add snapin qualified type name for this command..
                                // this will enable customizations of the help object.
                                helpInfo.FullHelp.TypeNames.Insert(0, string.Format(CultureInfo.InvariantCulture,
                                                                                    "ProviderHelpInfo#{0}#{1}", providerInfo.PSSnapInName, helpInfo.Name));

                                if (!string.IsNullOrEmpty(providerInfo.PSSnapInName))
                                {
                                    helpInfo.FullHelp.Properties.Add(new PSNoteProperty("PSSnapIn", providerInfo.PSSnapIn));
                                    helpInfo.FullHelp.TypeNames.Insert(1, string.Format(CultureInfo.InvariantCulture,
                                                                                        "ProviderHelpInfo#{0}", providerInfo.PSSnapInName));
                                }

                                AddCache(providerInfo.PSSnapInName + "\\" + helpInfo.Name, helpInfo);
                            }
                        }
                    }
                }
            }
        }
Exemple #38
0
        /// <summary>
        /// Initiate an instance for provider configuration entry.
        /// </summary>
        /// <param name="name">Name of the provider configuration entry</param>
        /// <param name="implementingType">Class that include implementation of the provider</param>
        /// <param name="helpFileName">Name of the help file that include help information for the provider</param>
        /// <param name="psSnapinInfo">PSSnapin from which provider comes from.</param>
        internal ProviderConfigurationEntry(string name, Type implementingType, string helpFileName, PSSnapInInfo psSnapinInfo)
            : base(name, psSnapinInfo)
        {
            if (implementingType == null)
            {
                throw PSTraceSource.NewArgumentNullException("implementingType");
            }

            ImplementingType = implementingType;

            if (!String.IsNullOrEmpty(helpFileName))
            {
                HelpFileName = helpFileName.Trim();
            }
            else
            {
                HelpFileName = helpFileName;
            }
        }
Exemple #39
0
 internal ProviderConfigurationEntry(string name, Type implementingType, string helpFileName, PSSnapInInfo psSnapinInfo)
     : base(name, psSnapinInfo)
 {
     ImplementingType = implementingType;
     HelpFileName     = helpFileName;
 }
Exemple #40
0
 internal static void AnalyzePSSnapInAssembly(
     Assembly assembly,
     string name,
     PSSnapInInfo psSnapInInfo,
     out Dictionary <string, SessionStateCmdletEntry> cmdlets,
     out Dictionary <string, SessionStateProviderEntry> providers)
 {
     if (assembly == null)
     {
         throw new ArgumentNullException(nameof(assembly));
     }
     if (PSSnapInHelpers._cmdletCache != null && PSSnapInHelpers._providerCache != null && (PSSnapInHelpers._cmdletCache.ContainsKey(assembly) && PSSnapInHelpers._providerCache.ContainsKey(assembly)))
     {
         cmdlets   = PSSnapInHelpers._cmdletCache[assembly];
         providers = PSSnapInHelpers._providerCache[assembly];
     }
     else
     {
         cmdlets   = (Dictionary <string, SessionStateCmdletEntry>)null;
         providers = (Dictionary <string, SessionStateProviderEntry>)null;
         PSSnapInHelpers._PSSnapInTracer.WriteLine("Analyzing assembly {0} for cmdlet and providers", (object)assembly.Location);
         string helpFile = PSSnapInHelpers.GetHelpFile(assembly.Location);
         Type[] types;
         try
         {
             types = assembly.GetTypes();
         }
         catch (ReflectionTypeLoadException ex)
         {
             string str = ex.Message + "\nLoader Exceptions: \n";
             if (ex.LoaderExceptions != null)
             {
                 foreach (Exception loaderException in ex.LoaderExceptions)
                 {
                     str = str + "\n" + loaderException.Message;
                 }
             }
             PSSnapInHelpers._PSSnapInTracer.TraceError(str);
             throw new PSSnapInException(name, str);
         }
         foreach (Type type in types)
         {
             if ((type.IsPublic || type.IsNestedPublic) && !type.IsAbstract)
             {
                 object[] customAttributes = type.GetCustomAttributes(false);
                 string   str1             = (string)null;
                 string   str2             = (string)null;
                 foreach (object obj in customAttributes)
                 {
                     if (obj.GetType() == typeof(CmdletAttribute))
                     {
                         str1 = PSSnapInHelpers.GetCmdletName(obj as CmdletAttribute);
                         break;
                     }
                     if (obj.GetType() == typeof(CmdletProviderAttribute))
                     {
                         str2 = PSSnapInHelpers.GetProviderName(obj as CmdletProviderAttribute);
                         break;
                     }
                 }
                 if (!string.IsNullOrEmpty(str1))
                 {
                     if (PSSnapInHelpers.IsCmdletClass(type) && PSSnapInHelpers.HasDefaultConstructor(type))
                     {
                         if (cmdlets != null && cmdlets.ContainsKey(str1))
                         {
                             string str3 = ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "PSSnapInDuplicateCmdlets", (object)str1, (object)name);
                             PSSnapInHelpers._PSSnapInTracer.TraceError(str3);
                             throw new PSSnapInException(name, str3);
                         }
                         SessionStateCmdletEntry stateCmdletEntry = new SessionStateCmdletEntry(str1, type, helpFile);
                         if (psSnapInInfo != null)
                         {
                             stateCmdletEntry.SetPSSnapIn(psSnapInInfo);
                         }
                         if (cmdlets == null)
                         {
                             cmdlets = new Dictionary <string, SessionStateCmdletEntry>((IEqualityComparer <string>)StringComparer.OrdinalIgnoreCase);
                         }
                         cmdlets.Add(str1, stateCmdletEntry);
                         PSSnapInHelpers._PSSnapInTracer.WriteLine("{0} from type {1} is added as a cmdlet. ", (object)str1, (object)type.FullName);
                         continue;
                     }
                     PSSnapInHelpers._PSSnapInTracer.TraceWarning("{0} is not valid cmdlet because it doesn't derive from the Cmdlet type or it doesn't have a default constructor.", (object)str1);
                 }
                 if (!string.IsNullOrEmpty(str2))
                 {
                     if (PSSnapInHelpers.IsProviderClass(type) && PSSnapInHelpers.HasDefaultConstructor(type))
                     {
                         if (providers != null && providers.ContainsKey(str2))
                         {
                             string str3 = ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "PSSnapInDuplicateProviders", (object)str2, (object)psSnapInInfo.Name);
                             PSSnapInHelpers._PSSnapInTracer.TraceError(str3);
                             throw new PSSnapInException(psSnapInInfo.Name, str3);
                         }
                         SessionStateProviderEntry stateProviderEntry = new SessionStateProviderEntry(str2, type, helpFile);
                         stateProviderEntry.SetPSSnapIn(psSnapInInfo);
                         if (providers == null)
                         {
                             providers = new Dictionary <string, SessionStateProviderEntry>((IEqualityComparer <string>)StringComparer.OrdinalIgnoreCase);
                         }
                         providers.Add(str2, stateProviderEntry);
                         PSSnapInHelpers._PSSnapInTracer.WriteLine("{0} from type {1} is added as a provider. ", (object)str2, (object)type.FullName);
                     }
                     else
                     {
                         PSSnapInHelpers._PSSnapInTracer.TraceWarning("{0} is not valid provider because it doesn't derive from the provider type or it doesn't have a default constructor.", (object)str2);
                     }
                 }
             }
         }
         lock (PSSnapInHelpers._syncObject)
         {
             if (cmdlets != null)
             {
                 if (PSSnapInHelpers._cmdletCache == null)
                 {
                     PSSnapInHelpers._cmdletCache = new Dictionary <Assembly, Dictionary <string, SessionStateCmdletEntry> >();
                 }
                 PSSnapInHelpers._cmdletCache[assembly] = cmdlets;
             }
             if (providers == null)
             {
                 return;
             }
             if (PSSnapInHelpers._providerCache == null)
             {
                 PSSnapInHelpers._providerCache = new Dictionary <Assembly, Dictionary <string, SessionStateProviderEntry> >();
             }
             PSSnapInHelpers._providerCache[assembly] = providers;
         }
     }
 }
        /// <summary>
        /// Removes pssnapins from the current console file.
        /// </summary>
        /// <remarks>
        /// The pssnapin is not unloaded from the current engine. So all the cmdlets that are
        /// represented by this pssnapin will continue to work.
        /// </remarks>
        protected override void ProcessRecord()
        {
            foreach (string psSnapIn in _pssnapins)
            {
                Collection <PSSnapInInfo> snapIns = GetSnapIns(psSnapIn);

                // snapIns won't be null..
                Diagnostics.Assert(snapIns != null, "GetSnapIns() returned null");
                if (snapIns.Count == 0)
                {
                    WriteNonTerminatingError(psSnapIn, "NoPSSnapInsFound",
                                             PSTraceSource.NewArgumentException(psSnapIn,
                                                                                MshSnapInCmdletResources.NoPSSnapInsFound, psSnapIn),
                                             ErrorCategory.InvalidArgument);

                    continue;
                }

                foreach (PSSnapInInfo snapIn in snapIns)
                {
                    // confirm the operation first
                    // this is always false if WhatIf is set
                    if (ShouldProcess(snapIn.Name))
                    {
                        Exception exception = null;

                        if (this.Runspace == null && this.Context.InitialSessionState != null)
                        {
                            try
                            {
                                // Check if this snapin can be removed

                                // Monad has specific restrictions on the mshsnapinid like
                                // mshsnapinid should be A-Za-z0-9.-_ etc.
                                PSSnapInInfo.VerifyPSSnapInFormatThrowIfError(snapIn.Name);

                                if (MshConsoleInfo.IsDefaultPSSnapIn(snapIn.Name, this.Context.InitialSessionState.defaultSnapins))
                                {
                                    throw PSTraceSource.NewArgumentException(snapIn.Name, ConsoleInfoErrorStrings.CannotRemoveDefault, snapIn.Name);
                                }

                                // Handle the initial session state case...
                                InitialSessionState iss = InitialSessionState.Create();
                                PSSnapInException   warning;

                                // Get the snapin information...
                                iss.ImportPSSnapIn(snapIn, out warning);
                                iss.Unbind(Context);
                                Context.InitialSessionState.ImportedSnapins.Remove(snapIn.Name);
                            }
                            catch (PSArgumentException ae)
                            {
                                exception = ae;
                            }

                            if (exception != null)
                            {
                                WriteNonTerminatingError(psSnapIn, "RemovePSSnapIn", exception, ErrorCategory.InvalidArgument);
                            }
                        }
                        else
                        {
                            try
                            {
                                PSSnapInException warning = null;

                                PSSnapInInfo psSnapInInfo = this.Runspace.RemovePSSnapIn(snapIn.Name, out warning);

                                if (warning != null)
                                {
                                    WriteNonTerminatingError(snapIn.Name, "RemovePSSnapInRead", warning, ErrorCategory.InvalidData);
                                }

                                if (_passThru)
                                {
                                    // Load the pssnapin info properties that are localizable and redirected in the registry
                                    psSnapInInfo.LoadIndirectResources(ResourceReader);
                                    WriteObject(psSnapInInfo);
                                }
                            }
                            catch (PSArgumentException ae)
                            {
                                exception = ae;
                            }

                            if (exception != null)
                            {
                                WriteNonTerminatingError(psSnapIn, "RemovePSSnapIn", exception, ErrorCategory.InvalidArgument);
                            }
                        }
                    } // ShouldContinue
                }
            }
        }