Esempio n. 1
0
        /// <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);
        }
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of System.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (ProcessorArchitecture.Expression != null)
            {
                targetCommand.AddParameter("ProcessorArchitecture", ProcessorArchitecture.Get(context));
            }

            if (SessionType.Expression != null)
            {
                targetCommand.AddParameter("SessionType", SessionType.Get(context));
            }

            if (Name.Expression != null)
            {
                targetCommand.AddParameter("Name", Name.Get(context));
            }

            if (AssemblyName.Expression != null)
            {
                targetCommand.AddParameter("AssemblyName", AssemblyName.Get(context));
            }

            if (ApplicationBase.Expression != null)
            {
                targetCommand.AddParameter("ApplicationBase", ApplicationBase.Get(context));
            }

            if (ConfigurationTypeName.Expression != null)
            {
                targetCommand.AddParameter("ConfigurationTypeName", ConfigurationTypeName.Get(context));
            }

            if (RunAsCredential.Expression != null)
            {
                targetCommand.AddParameter("RunAsCredential", RunAsCredential.Get(context));
            }

            if (ThreadApartmentState.Expression != null)
            {
                targetCommand.AddParameter("ThreadApartmentState", ThreadApartmentState.Get(context));
            }

            if (ThreadOptions.Expression != null)
            {
                targetCommand.AddParameter("ThreadOptions", ThreadOptions.Get(context));
            }

            if (AccessMode.Expression != null)
            {
                targetCommand.AddParameter("AccessMode", AccessMode.Get(context));
            }

            if (UseSharedProcess.Expression != null)
            {
                targetCommand.AddParameter("UseSharedProcess", UseSharedProcess.Get(context));
            }

            if (StartupScript.Expression != null)
            {
                targetCommand.AddParameter("StartupScript", StartupScript.Get(context));
            }

            if (MaximumReceivedDataSizePerCommandMB.Expression != null)
            {
                targetCommand.AddParameter("MaximumReceivedDataSizePerCommandMB", MaximumReceivedDataSizePerCommandMB.Get(context));
            }

            if (MaximumReceivedObjectSizeMB.Expression != null)
            {
                targetCommand.AddParameter("MaximumReceivedObjectSizeMB", MaximumReceivedObjectSizeMB.Get(context));
            }

            if (SecurityDescriptorSddl.Expression != null)
            {
                targetCommand.AddParameter("SecurityDescriptorSddl", SecurityDescriptorSddl.Get(context));
            }

            if (ShowSecurityDescriptorUI.Expression != null)
            {
                targetCommand.AddParameter("ShowSecurityDescriptorUI", ShowSecurityDescriptorUI.Get(context));
            }

            if (Force.Expression != null)
            {
                targetCommand.AddParameter("Force", Force.Get(context));
            }

            if (NoServiceRestart.Expression != null)
            {
                targetCommand.AddParameter("NoServiceRestart", NoServiceRestart.Get(context));
            }

            if (PSVersion.Expression != null)
            {
                targetCommand.AddParameter("PSVersion", PSVersion.Get(context));
            }

            if (SessionTypeOption.Expression != null)
            {
                targetCommand.AddParameter("SessionTypeOption", SessionTypeOption.Get(context));
            }

            if (TransportOption.Expression != null)
            {
                targetCommand.AddParameter("TransportOption", TransportOption.Get(context));
            }

            if (ModulesToImport.Expression != null)
            {
                targetCommand.AddParameter("ModulesToImport", ModulesToImport.Get(context));
            }

            if (Path.Expression != null)
            {
                targetCommand.AddParameter("Path", Path.Get(context));
            }


            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
        /// <summary>
        /// Loads a Monad Console file specified by <paramref name="path"/>
        /// </summary>
        /// <param name="path">
        /// The absolute path from which the content is loaded.
        /// </param>
        /// <param name="cle">
        /// PSConsoleLoadException occurred while loading this console file. This object
        /// also contains specific PSSnapInExceptions that occurred while loading.
        /// </param>
        /// <returns>
        /// A list of <see cref="PSSnapInInfo"/> objects specified in the console file.
        /// </returns>
        /// <exception cref="PSArgumentNullException">
        /// Path is null.
        /// </exception>
        /// <exception cref="PSArgumentException">
        /// 1. Path does not specify proper file extension.
        /// 2. PSSnapInId doesnt contain valid characters.
        /// 3. Path is not an Absolute Path.
        ///    Example of valid paths:"\\MyDir\\MyFile.txt" and "C:\\MyDir".
        /// </exception>
        /// <exception cref="ArgumentException">
        /// path contains one or more of the invalid characters defined in System.IO.Path.InvalidPathChars.
        /// </exception>
        /// <exception cref="XmlException">
        /// Unable to load/parse the file specified by path.
        /// </exception>
        private Collection <PSSnapInInfo> Load(string path, out PSConsoleLoadException cle)
        {
            // Initialize the out parameter..
            cle = null;

            s_mshsnapinTracer.WriteLine("Load mshsnapins from console file {0}", path);

            if (string.IsNullOrEmpty(path))
            {
                throw PSTraceSource.NewArgumentNullException("path");
            }

            // Check whether the path is an absolute path
            if (!Path.IsPathRooted(path))
            {
                s_mshsnapinTracer.TraceError("Console file {0} needs to be a absolute path.", path);

                throw PSTraceSource.NewArgumentException("path", ConsoleInfoErrorStrings.PathNotAbsolute, path);
            }

            if (!path.EndsWith(StringLiterals.PowerShellConsoleFileExtension, StringComparison.OrdinalIgnoreCase))
            {
                s_mshsnapinTracer.TraceError("Console file {0} needs to have {1} extension.", path, StringLiterals.PowerShellConsoleFileExtension);

                throw PSTraceSource.NewArgumentException("path", ConsoleInfoErrorStrings.BadConsoleExtension);
            }

            PSConsoleFileElement consoleFileElement;

            // exceptions are thrown to the caller
            consoleFileElement = PSConsoleFileElement.CreateFromFile(path);

            // consoleFileElement will never be null..
            if (!Utils.IsPSVersionSupported(consoleFileElement.MonadVersion))
            {
                s_mshsnapinTracer.TraceError("Console version {0} is not supported in current monad session.", consoleFileElement.MonadVersion);

                throw PSTraceSource.NewArgumentException("PSVersion", ConsoleInfoErrorStrings.BadMonadVersion, consoleFileElement.MonadVersion,
                                                         PSVersion.ToString());
            }

            // Create a store for exceptions
            Collection <PSSnapInException> exceptions = new Collection <PSSnapInException>();

            foreach (string mshsnapin in consoleFileElement.PSSnapIns)
            {
                try
                {
                    this.AddPSSnapIn(mshsnapin);
                }
                catch (PSArgumentException ae)
                {
                    PSSnapInException sle = new PSSnapInException(mshsnapin, ae.Message, ae);

                    // Eat ArgumentException and continue..
                    exceptions.Add(sle);
                }
                catch (System.Security.SecurityException se)
                {
                    string            message = ConsoleInfoErrorStrings.PSSnapInReadError;
                    PSSnapInException sle     = new PSSnapInException(mshsnapin, message, se);
                    // Eat SecurityException and continue..

                    exceptions.Add(sle);
                }
            }

            // Before returning check whether there are any exceptions
            if (exceptions.Count > 0)
            {
                cle = new PSConsoleLoadException(this, exceptions);
            }

            // We are able to load console file and currently monad engine
            // can service this. So mark the isdirty flag.
            IsDirty = false;

            return(_externalPSSnapIns);
        }
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of System.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (DefinitionName.Expression != null)
            {
                targetCommand.AddParameter("DefinitionName", DefinitionName.Get(context));
            }

            if (DefinitionPath.Expression != null)
            {
                targetCommand.AddParameter("DefinitionPath", DefinitionPath.Get(context));
            }

            if (Type.Expression != null)
            {
                targetCommand.AddParameter("Type", Type.Get(context));
            }

            if (Name.Expression != null)
            {
                targetCommand.AddParameter("Name", Name.Get(context));
            }

            if (ScriptBlock.Expression != null)
            {
                targetCommand.AddParameter("ScriptBlock", ScriptBlock.Get(context));
            }

            if (Credential.Expression != null)
            {
                targetCommand.AddParameter("Credential", Credential.Get(context));
            }

            if (FilePath.Expression != null)
            {
                targetCommand.AddParameter("FilePath", FilePath.Get(context));
            }

            if (LiteralPath.Expression != null)
            {
                targetCommand.AddParameter("LiteralPath", LiteralPath.Get(context));
            }

            if (Authentication.Expression != null)
            {
                targetCommand.AddParameter("Authentication", Authentication.Get(context));
            }

            if (InitializationScript.Expression != null)
            {
                targetCommand.AddParameter("InitializationScript", InitializationScript.Get(context));
            }

            if (RunAs32.Expression != null)
            {
                targetCommand.AddParameter("RunAs32", RunAs32.Get(context));
            }

            if (PSVersion.Expression != null)
            {
                targetCommand.AddParameter("PSVersion", PSVersion.Get(context));
            }

            if (InputObject.Expression != null)
            {
                targetCommand.AddParameter("InputObject", InputObject.Get(context));
            }

            if (ArgumentList.Expression != null)
            {
                targetCommand.AddParameter("ArgumentList", ArgumentList.Get(context));
            }


            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }