Beispiel #1
0
        protected override void ProcessRecord()
        {
            if (ModuleInfo.ModuleType != ModuleType.Binary)
            {
                var ex = new PSInvalidOperationException("This cmdlet can only be executed on binary modules.");
                WriteError(ex.ErrorRecord);
                return;
            }

            var cmdletsToExport = ModuleInfo.ImplementingAssembly
                                  .GetExportedTypes()
                                  .Select(x => x.GetCustomAttribute <CmdletAttribute>())
                                  .Where(x => x != null)
                                  .Select(x => $"{x.VerbName}-{x.NounName}")
                                  .ToList();

            WriteObject(cmdletsToExport, true);
        }
Beispiel #2
0
        internal IEnumerable <PSObject> ParseSchemaJson(string filePath, bool useNewRunspace = false)
        {
            try
            {
                string json = File.ReadAllText(filePath);
                string fileNameDefiningClass = Path.GetFileNameWithoutExtension(filePath);
                int    dotIndex = fileNameDefiningClass.IndexOf(".schema", StringComparison.InvariantCultureIgnoreCase);
                if (dotIndex != -1)
                {
                    fileNameDefiningClass = fileNameDefiningClass.Substring(0, dotIndex);
                }

                IEnumerable <PSObject> result = _jsonDeserializer.DeserializeClasses(json, useNewRunspace);
                foreach (dynamic classObject in result)
                {
                    string superClassName = classObject.SuperClassName;
                    string className      = classObject.ClassName;
                    if (string.Equals(superClassName, "OMI_BaseResource", StringComparison.OrdinalIgnoreCase))
                    {
                        // Get the name of the file without schema.mof/json extension
                        if (!className.Equals(fileNameDefiningClass, StringComparison.OrdinalIgnoreCase))
                        {
                            PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
                                ParserStrings.ClassNameNotSameAsDefiningFile, className, fileNameDefiningClass);
                            throw e;
                        }
                    }
                }

                return(result);
            }
            catch (Exception exception)
            {
                PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
                    exception, ParserStrings.CimDeserializationError, filePath);

                e.SetErrorId("CimDeserializationError");
                throw e;
            }
        }
Beispiel #3
0
        public override void ResetRunspaceState()
        {
            PSInvalidOperationException exception = null;

            if (this.InitialSessionState == null)
            {
                exception = PSTraceSource.NewInvalidOperationException();
            }
            else if (base.RunspaceState != RunspaceState.Opened)
            {
                exception = PSTraceSource.NewInvalidOperationException("RunspaceStrings", "RunspaceNotInOpenedState", new object[] { base.RunspaceState });
            }
            else if (this.RunspaceAvailability != RunspaceAvailability.Available)
            {
                exception = PSTraceSource.NewInvalidOperationException("RunspaceStrings", "ConcurrentInvokeNotAllowed", new object[0]);
            }
            if (exception != null)
            {
                exception.Source = "ResetRunspaceState";
                throw exception;
            }
            this.InitialSessionState.ResetRunspaceState(base.ExecutionContext);
            this._history = new Microsoft.PowerShell.Commands.History(base.ExecutionContext);
        }
        protected override void ProcessRecord()
        {
            CmdletProviderContext cmdletProviderContext = this.CmdletProviderContext;

            try
            {
                if (!base.InvokeProvider.Item.Exists(this.Path, cmdletProviderContext))
                {
                    object[] path = new object[1];
                    path[0] = this.Path;
                    PSInvalidOperationException pSInvalidOperationException = PSTraceSource.NewInvalidOperationException("NavigationResources", "RenameItemDoesntExist", path);
                    base.WriteError(new ErrorRecord(pSInvalidOperationException.ErrorRecord, pSInvalidOperationException));
                    return;
                }
            }
            catch (PSNotSupportedException pSNotSupportedException1)
            {
                PSNotSupportedException pSNotSupportedException = pSNotSupportedException1;
                base.WriteError(new ErrorRecord(pSNotSupportedException.ErrorRecord, pSNotSupportedException));
                return;
            }
            catch (DriveNotFoundException driveNotFoundException1)
            {
                DriveNotFoundException driveNotFoundException = driveNotFoundException1;
                base.WriteError(new ErrorRecord(driveNotFoundException.ErrorRecord, driveNotFoundException));
                return;
            }
            catch (ProviderNotFoundException providerNotFoundException1)
            {
                ProviderNotFoundException providerNotFoundException = providerNotFoundException1;
                base.WriteError(new ErrorRecord(providerNotFoundException.ErrorRecord, providerNotFoundException));
                return;
            }
            catch (ItemNotFoundException itemNotFoundException1)
            {
                ItemNotFoundException itemNotFoundException = itemNotFoundException1;
                base.WriteError(new ErrorRecord(itemNotFoundException.ErrorRecord, itemNotFoundException));
                return;
            }
            bool flag = false;

            try
            {
                flag = base.SessionState.Path.IsCurrentLocationOrAncestor(this.path, cmdletProviderContext);
            }
            catch (PSNotSupportedException pSNotSupportedException3)
            {
                PSNotSupportedException pSNotSupportedException2 = pSNotSupportedException3;
                base.WriteError(new ErrorRecord(pSNotSupportedException2.ErrorRecord, pSNotSupportedException2));
                return;
            }
            catch (DriveNotFoundException driveNotFoundException3)
            {
                DriveNotFoundException driveNotFoundException2 = driveNotFoundException3;
                base.WriteError(new ErrorRecord(driveNotFoundException2.ErrorRecord, driveNotFoundException2));
                return;
            }
            catch (ProviderNotFoundException providerNotFoundException3)
            {
                ProviderNotFoundException providerNotFoundException2 = providerNotFoundException3;
                base.WriteError(new ErrorRecord(providerNotFoundException2.ErrorRecord, providerNotFoundException2));
                return;
            }
            catch (ItemNotFoundException itemNotFoundException3)
            {
                ItemNotFoundException itemNotFoundException2 = itemNotFoundException3;
                base.WriteError(new ErrorRecord(itemNotFoundException2.ErrorRecord, itemNotFoundException2));
                return;
            }
            if (!flag)
            {
                cmdletProviderContext.PassThru = this.PassThru;
                object[] newName = new object[2];
                newName[0] = this.Path;
                newName[1] = this.NewName;
                CoreCommandBase.tracer.WriteLine("Rename {0} to {1}", newName);
                try
                {
                    base.InvokeProvider.Item.Rename(this.Path, this.NewName, cmdletProviderContext);
                }
                catch (PSNotSupportedException pSNotSupportedException5)
                {
                    PSNotSupportedException pSNotSupportedException4 = pSNotSupportedException5;
                    base.WriteError(new ErrorRecord(pSNotSupportedException4.ErrorRecord, pSNotSupportedException4));
                    return;
                }
                catch (DriveNotFoundException driveNotFoundException5)
                {
                    DriveNotFoundException driveNotFoundException4 = driveNotFoundException5;
                    base.WriteError(new ErrorRecord(driveNotFoundException4.ErrorRecord, driveNotFoundException4));
                    return;
                }
                catch (ProviderNotFoundException providerNotFoundException5)
                {
                    ProviderNotFoundException providerNotFoundException4 = providerNotFoundException5;
                    base.WriteError(new ErrorRecord(providerNotFoundException4.ErrorRecord, providerNotFoundException4));
                    return;
                }
                catch (ItemNotFoundException itemNotFoundException5)
                {
                    ItemNotFoundException itemNotFoundException4 = itemNotFoundException5;
                    base.WriteError(new ErrorRecord(itemNotFoundException4.ErrorRecord, itemNotFoundException4));
                    return;
                }
                return;
            }
            else
            {
                object[] objArray = new object[1];
                objArray[0] = this.Path;
                PSInvalidOperationException pSInvalidOperationException1 = PSTraceSource.NewInvalidOperationException("NavigationResources", "RenamedItemInUse", objArray);
                base.WriteError(new ErrorRecord(pSInvalidOperationException1.ErrorRecord, pSInvalidOperationException1));
            }
        }
        /// <summary>
        /// Sets a string value for a WSMan Session option.
        /// </summary>
        /// <param name="option"></param>
        /// <param name="stringData"></param>
        /// <exception cref="PSInvalidOperationException">
        /// Setting session option failed with a non-zero error code.
        /// </exception>
        internal void SetWSManSessionOption(WSManNativeApi.WSManSessionOption option, string stringData)
        {
            using (WSManNativeApi.WSManData_ManToUn data = new WSManNativeApi.WSManData_ManToUn(stringData))
            {
                int result = WSManNativeApi.WSManSetSessionOption(_wsManSessionHandle,
                      option, data);

                if (result != 0)
                {
                    // Get the error message from WSMan
                    string errorMessage = WSManNativeApi.WSManGetErrorMessage(WSManAPIData.WSManAPIHandle, result);

                    PSInvalidOperationException exception = new PSInvalidOperationException(errorMessage);
                    throw exception;
                }
            }
        }
        /// <summary>
        /// Sets a DWORD value for a WSMan Session option.
        /// </summary>
        /// <param name="option"></param>
        /// <param name="dwordData"></param>
        /// <exception cref="PSInvalidOperationException">
        /// Setting session option failed with a non-zero error code.
        /// </exception>
        internal void SetWSManSessionOption(WSManNativeApi.WSManSessionOption option, int dwordData)
        {
            int result = WSManNativeApi.WSManSetSessionOption(_wsManSessionHandle,
                option, new WSManNativeApi.WSManDataDWord(dwordData));

            if (result != 0)
            {
                // Get the error message from WSMan
                string errorMessage = WSManNativeApi.WSManGetErrorMessage(WSManAPIData.WSManAPIHandle, result);

                PSInvalidOperationException exception = new PSInvalidOperationException(errorMessage);
                throw exception;
            }
        }
        /// <summary>
        /// Sets timeout for Signal operation in milliseconds
        /// </summary>
        /// <param name="milliseconds"></param>
        /// <returns></returns>
        /// <exception cref="PSInvalidOperationException">
        /// Setting session option failed with a non-zero error code.
        /// </exception>
        internal void SetSignalTimeOut(int milliseconds)
        {
            Dbg.Assert(_wsManSessionHandle != IntPtr.Zero, "Session handle cannot be null");
            using (tracer.TraceMethod("Setting SignalShell timeout: {0} milliseconds", milliseconds))
            {
                int result = WSManNativeApi.WSManSetSessionOption(_wsManSessionHandle,
                    WSManNativeApi.WSManSessionOption.WSMAN_OPTION_TIMEOUTMS_SIGNAL_SHELL,
                    new WSManNativeApi.WSManDataDWord(milliseconds));

                if (result != 0)
                {
                    // Get the error message from WSMan
                    string errorMessage = WSManNativeApi.WSManGetErrorMessage(WSManAPIData.WSManAPIHandle, result);

                    PSInvalidOperationException exception = new PSInvalidOperationException(errorMessage);
                    throw exception;
                }
            }
        }
        /// <summary>
        /// Initializes the session.
        /// </summary>
        /// <param name="connectionUri">
        /// Uri to connect to.
        /// </param>
        /// <param name="connectionInfo">
        /// Connection info object used for retrieving credential, auth. mechanism etc.
        /// </param>
        /// <exception cref="PSInvalidOperationException">
        /// 1. Create Session failed with a non-zero error code.
        /// </exception>
        private void Initialize(Uri connectionUri, WSManConnectionInfo connectionInfo)
        {
            Dbg.Assert(null != connectionInfo, "connectionInfo cannot be null.");

            ConnectionInfo = connectionInfo;

            // this will generate: http://ComputerName:port/appname?PSVersion=<version>
            // PSVersion= pattern is needed to make Exchange compatible with PS V2 CTP3
            // release. Using the PSVersion= logic, Exchange R4 server will redirect
            // clients to an R3 endpoint.
            bool isSSLSpecified = false;
            string connectionStr = connectionUri.OriginalString;
            if ((connectionUri == connectionInfo.ConnectionUri) &&
                (connectionInfo.UseDefaultWSManPort))
            {
                connectionStr = WSManConnectionInfo.GetConnectionString(connectionInfo.ConnectionUri,
                    out isSSLSpecified);
            }

            // TODO: Remove this after RDS moved to $using
            string additionalUriSuffixString = string.Empty;
            if (PSSessionConfigurationData.IsServerManager)
            {
                additionalUriSuffixString = ";MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8";
            }
            if (string.IsNullOrEmpty(connectionUri.Query))
            {
                // if there is no query string already, create one..see RFC 3986
                connectionStr = string.Format(CultureInfo.InvariantCulture,
                    "{0}?PSVersion={1}{2}",
                    // Trimming the last '/' as this will allow WSMan to
                    // properly apply URLPrefix. 
                    // Ex: http://localhost?PSVersion=2.0 will be converted
                    // to http://localhost:<port>/<urlprefix>?PSVersion=2.0
                    // by WSMan
                    connectionStr.TrimEnd('/'),
                    PSVersionInfo.PSVersion,
                    additionalUriSuffixString);
            }
            else
            {
                // if there is already a query string, append using & .. see RFC 3986
                connectionStr = string.Format(CultureInfo.InvariantCulture,
                       "{0};PSVersion={1}{2}",
                       connectionStr,
                       PSVersionInfo.PSVersion,
                       additionalUriSuffixString);
            }

            WSManNativeApi.BaseWSManAuthenticationCredentials authCredentials;
            // use certificate thumbprint for authentication
            if (connectionInfo.CertificateThumbprint != null)
            {
                authCredentials = new WSManNativeApi.WSManCertificateThumbprintCredentials(connectionInfo.CertificateThumbprint);
            }
            else
            {
                // use credential based authentication
                string userName = null;
                System.Security.SecureString password = null;
                if ((null != connectionInfo.Credential) && (!string.IsNullOrEmpty(connectionInfo.Credential.UserName)))
                {
                    userName = connectionInfo.Credential.UserName;
                    password = connectionInfo.Credential.Password;
                }

                WSManNativeApi.WSManUserNameAuthenticationCredentials userNameCredentials =
                    new WSManNativeApi.WSManUserNameAuthenticationCredentials(userName,
                        password,
                        connectionInfo.WSManAuthenticationMechanism);

                authCredentials = userNameCredentials;
            }

            // proxy related data
            WSManNativeApi.WSManUserNameAuthenticationCredentials proxyAuthCredentials = null;
            if (connectionInfo.ProxyCredential != null)
            {
                WSManNativeApi.WSManAuthenticationMechanism authMechanism = WSManNativeApi.WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_NEGOTIATE;
                string userName = null;
                System.Security.SecureString password = null;

                switch (connectionInfo.ProxyAuthentication)
                {
                    case AuthenticationMechanism.Negotiate:
                        authMechanism = WSManNativeApi.WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_NEGOTIATE;
                        break;
                    case AuthenticationMechanism.Basic:
                        authMechanism = WSManNativeApi.WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_BASIC;
                        break;
                    case AuthenticationMechanism.Digest:
                        authMechanism = WSManNativeApi.WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_DIGEST;
                        break;
                }

                if (!string.IsNullOrEmpty(connectionInfo.ProxyCredential.UserName))
                {
                    userName = connectionInfo.ProxyCredential.UserName;
                    password = connectionInfo.ProxyCredential.Password;
                }

                // use credential based authentication
                proxyAuthCredentials = new WSManNativeApi.WSManUserNameAuthenticationCredentials(userName, password, authMechanism);
            }

            WSManNativeApi.WSManProxyInfo proxyInfo = (ProxyAccessType.None == connectionInfo.ProxyAccessType) ?
                null :
                new WSManNativeApi.WSManProxyInfo(connectionInfo.ProxyAccessType, proxyAuthCredentials);

            int result = 0;

            try
            {
                result = WSManNativeApi.WSManCreateSession(WSManAPIData.WSManAPIHandle, connectionStr, 0,
                     authCredentials.GetMarshalledObject(),
                     (null == proxyInfo) ? IntPtr.Zero : (IntPtr)proxyInfo,
                     ref _wsManSessionHandle);
            }
            finally
            {
                // release resources
                if (null != proxyAuthCredentials)
                {
                    proxyAuthCredentials.Dispose();
                }

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

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

            if (result != 0)
            {
                // Get the error message from WSMan
                string errorMessage = WSManNativeApi.WSManGetErrorMessage(WSManAPIData.WSManAPIHandle, result);

                PSInvalidOperationException exception = new PSInvalidOperationException(errorMessage);
                throw exception;
            }

            // set the packet size for this session
            int packetSize;
            WSManNativeApi.WSManGetSessionOptionAsDword(_wsManSessionHandle,
                WSManNativeApi.WSManSessionOption.WSMAN_OPTION_SHELL_MAX_DATA_SIZE_PER_MESSAGE_KB,
                out packetSize);
            // packet size returned is in KB. Convert this into bytes..
            Fragmentor.FragmentSize = packetSize << 10;

            // Get robust connections maximum retries time.
            WSManNativeApi.WSManGetSessionOptionAsDword(_wsManSessionHandle,
                WSManNativeApi.WSManSessionOption.WSMAN_OPTION_MAX_RETRY_TIME,
                out _maxRetryTime);

            this.dataToBeSent.Fragmentor = base.Fragmentor;
            _noCompression = !connectionInfo.UseCompression;
            _noMachineProfile = connectionInfo.NoMachineProfile;

            // set other WSMan session related defaults            
            if (isSSLSpecified)
            {
                // WSMan Port DCR related changes - BUG 542726
                // this session option will tell WSMan to use port for HTTPS from
                // config provider.
                SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_USE_SSL, 1);
            }
            if (connectionInfo.NoEncryption)
            {
                // send unencrypted messages
                SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_UNENCRYPTED_MESSAGES, 1);
            }
            // check if implicit credentials can be used for Negotiate
            if (connectionInfo.AllowImplicitCredentialForNegotiate)
            {
                result = WSManNativeApi.WSManSetSessionOption(_wsManSessionHandle,
                    WSManNativeApi.WSManSessionOption.WSMAN_OPTION_ALLOW_NEGOTIATE_IMPLICIT_CREDENTIALS,
                    new WSManNativeApi.WSManDataDWord(1));
            }
            if (connectionInfo.UseUTF16)
            {
                SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_UTF16, 1);
            }

            if (connectionInfo.SkipCACheck)
            {
                SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_SKIP_CA_CHECK, 1);
            }

            if (connectionInfo.SkipCNCheck)
            {
                SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_SKIP_CN_CHECK, 1);
            }

            if (connectionInfo.SkipRevocationCheck)
            {
                SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_SKIP_REVOCATION_CHECK, 1);
            }

            if (connectionInfo.IncludePortInSPN)
            {
                SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_ENABLE_SPN_SERVER_PORT, 1);
            }

            // Set use interactive token flag based on EnableNetworkAccess property.
            SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_USE_INTERACTIVE_TOKEN,
                (connectionInfo.EnableNetworkAccess) ? 1 : 0);

            // set UI Culture for this session from current thread's UI Culture
            string currentUICulture = connectionInfo.UICulture.Name;
            if (!string.IsNullOrEmpty(currentUICulture))
            {
                // WSMan API cannot handle empty culture names
                SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_UI_LANGUAGE, currentUICulture);
            }

            // set Culture for this session from current thread's Culture
            string currentCulture = connectionInfo.Culture.Name;
            if (!string.IsNullOrEmpty(currentCulture))
            {
                SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_LOCALE, currentCulture);
            }

            // set the PowerShell specific default client timeouts
            SetDefaultTimeOut(connectionInfo.OperationTimeout);
            SetConnectTimeOut(connectionInfo.OpenTimeout);
            SetCloseTimeOut(connectionInfo.CancelTimeout);
            SetSignalTimeOut(connectionInfo.CancelTimeout);
        }
        /// <summary>
        /// The main processing loop of the command.
        /// </summary>
        protected override void ProcessRecord()
        {
            string path = GetFilePath();

            if (path == null)
            {
                return;
            }

            if (!File.Exists(path))
            {
                InvalidOperationException ioe =
                    PSTraceSource.NewInvalidOperationException(
                        ImportLocalizedDataStrings.FileNotExist,
                        path);
                WriteError(new ErrorRecord(ioe, "ImportLocalizedData", ErrorCategory.ObjectNotFound, path));
                return;
            }

            // Prevent additional commands in ConstrainedLanguage mode
            if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage)
            {
                if (_setSupportedCommand)
                {
                    NotSupportedException nse =
                        PSTraceSource.NewNotSupportedException(
                            ImportLocalizedDataStrings.CannotDefineSupportedCommand);
                    ThrowTerminatingError(
                        new ErrorRecord(nse, "CannotDefineSupportedCommand", ErrorCategory.PermissionDenied, null));
                }
            }

            string script = GetScript(path);

            if (script == null)
            {
                return;
            }

            try
            {
                var scriptBlock = Context.Engine.ParseScriptBlock(script, false);
                scriptBlock.CheckRestrictedLanguage(SupportedCommand, null, false);
                object         result;
                PSLanguageMode oldLanguageMode = Context.LanguageMode;
                Context.LanguageMode = PSLanguageMode.RestrictedLanguage;
                try
                {
                    result = scriptBlock.InvokeReturnAsIs();
                    if (result == AutomationNull.Value)
                    {
                        result = null;
                    }
                }
                finally
                {
                    Context.LanguageMode = oldLanguageMode;
                }

                if (_bindingVariable != null)
                {
                    VariablePath variablePath = new(_bindingVariable);
                    if (variablePath.IsUnscopedVariable)
                    {
                        variablePath = variablePath.CloneAndSetLocal();
                    }

                    if (string.IsNullOrEmpty(variablePath.UnqualifiedPath))
                    {
                        InvalidOperationException ioe = PSTraceSource.NewInvalidOperationException(
                            ImportLocalizedDataStrings.IncorrectVariableName, _bindingVariable);
                        WriteError(new ErrorRecord(ioe, "ImportLocalizedData", ErrorCategory.InvalidArgument,
                                                   _bindingVariable));
                        return;
                    }

                    SessionStateScope scope    = null;
                    PSVariable        variable = SessionState.Internal.GetVariableItem(variablePath, out scope);

                    if (variable == null)
                    {
                        variable = new PSVariable(variablePath.UnqualifiedPath, result, ScopedItemOptions.None);
                        Context.EngineSessionState.SetVariable(variablePath, variable, false, CommandOrigin.Internal);
                    }
                    else
                    {
                        variable.Value = result;

                        if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage)
                        {
                            // Mark untrusted values for assignments to 'Global:' variables, and 'Script:' variables in
                            // a module scope, if it's necessary.
                            ExecutionContext.MarkObjectAsUntrustedForVariableAssignment(variable, scope, Context.EngineSessionState);
                        }
                    }
                }

                // If binding variable is null, write the object to stream
                else
                {
                    WriteObject(result);
                }
            }
            catch (RuntimeException e)
            {
                PSInvalidOperationException ioe = PSTraceSource.NewInvalidOperationException(e,
                                                                                             ImportLocalizedDataStrings.ErrorLoadingDataFile,
                                                                                             path,
                                                                                             e.Message);

                throw ioe;
            }

            return;
        }
Beispiel #10
0
        /// <summary>
        /// Attempts to open the item in Orca, if installed; otherwise, tries to invoke the "edit" verb on the package.
        /// </summary>
        /// <param name="item">The <see cref="PSObject"/> representing a package to open.</param>
        protected override void ProcessItem(PSObject item)
        {
            string path = item.GetPropertyValue <string>("PSPath");

            path = this.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path);

            // Make sure the item is an MSI or MSP package.
            var type = FileInfo.GetFileTypeInternal(path);

            if (FileType.Package != type && FileType.Patch != type)
            {
                var message = string.Format(CultureInfo.CurrentCulture, Resources.Error_InvalidStorage, path);
                var ex      = new PSInvalidOperationException(message);
                this.WriteError(ex.ErrorRecord);

                return;
            }

            var info = new ProcessStartInfo()
            {
                WorkingDirectory = System.IO.Path.GetDirectoryName(path),
            };

            if (!string.IsNullOrEmpty(this.orcaPath))
            {
                // Open in Orca, if installed.
                info.FileName  = this.orcaPath;
                info.Arguments = "\"" + path + "\"";
            }
            else
            {
                // Try to use the edit verb instead.
                info.FileName        = path;
                info.UseShellExecute = true;
                info.Verb            = "edit";
            }

            Process process = null;

            try
            {
                process = Process.Start(info);
                if (this.Wait)
                {
                    process.WaitForExit();
                }
            }
            catch (Exception ex)
            {
                if (ex is InvalidOperationException || ex is Win32Exception)
                {
                    // Likely the "edit" verb is not supported so terminate.
                    var pse = new PSInvalidOperationException(ex.Message, ex);
                    this.ThrowTerminatingError(pse.ErrorRecord);
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                if (null != process)
                {
                    process.Dispose();
                }
            }
        }
Beispiel #11
0
        protected override void ProcessRecord()
        {
            Collection <PathInfo> resolvedPSPathFromPSPath;
            CmdletProviderContext cmdletProviderContext = this.CmdletProviderContext;
            bool flag  = false;
            bool flag1 = false;

            string[] path = this.Path;
            for (int i = 0; i < (int)path.Length; i++)
            {
                string str = path[i];
                resolvedPSPathFromPSPath = null;
                try
                {
                    resolvedPSPathFromPSPath = base.SessionState.Path.GetResolvedPSPathFromPSPath(str, cmdletProviderContext);
                    goto Label0;
                }
                catch (PSNotSupportedException pSNotSupportedException1)
                {
                    PSNotSupportedException pSNotSupportedException = pSNotSupportedException1;
                    base.WriteError(new ErrorRecord(pSNotSupportedException.ErrorRecord, pSNotSupportedException));
                }
                catch (DriveNotFoundException driveNotFoundException1)
                {
                    DriveNotFoundException driveNotFoundException = driveNotFoundException1;
                    base.WriteError(new ErrorRecord(driveNotFoundException.ErrorRecord, driveNotFoundException));
                }
                catch (ProviderNotFoundException providerNotFoundException1)
                {
                    ProviderNotFoundException providerNotFoundException = providerNotFoundException1;
                    base.WriteError(new ErrorRecord(providerNotFoundException.ErrorRecord, providerNotFoundException));
                }
                catch (ItemNotFoundException itemNotFoundException1)
                {
                    ItemNotFoundException itemNotFoundException = itemNotFoundException1;
                    base.WriteError(new ErrorRecord(itemNotFoundException.ErrorRecord, itemNotFoundException));
                }
            }
            return;

Label0:
            IEnumerator <PathInfo> enumerator = resolvedPSPathFromPSPath.GetEnumerator();

            using (enumerator)
            {
                while (enumerator.MoveNext())
                {
                    PathInfo current = enumerator.Current;
                    bool     flag2   = false;
                    try
                    {
                        flag2 = base.SessionState.Path.IsCurrentLocationOrAncestor(current.Path, cmdletProviderContext);
                    }
                    catch (PSNotSupportedException pSNotSupportedException3)
                    {
                        PSNotSupportedException pSNotSupportedException2 = pSNotSupportedException3;
                        base.WriteError(new ErrorRecord(pSNotSupportedException2.ErrorRecord, pSNotSupportedException2));
                        continue;
                    }
                    catch (DriveNotFoundException driveNotFoundException3)
                    {
                        DriveNotFoundException driveNotFoundException2 = driveNotFoundException3;
                        base.WriteError(new ErrorRecord(driveNotFoundException2.ErrorRecord, driveNotFoundException2));
                        continue;
                    }
                    catch (ProviderNotFoundException providerNotFoundException3)
                    {
                        ProviderNotFoundException providerNotFoundException2 = providerNotFoundException3;
                        base.WriteError(new ErrorRecord(providerNotFoundException2.ErrorRecord, providerNotFoundException2));
                        continue;
                    }
                    catch (ItemNotFoundException itemNotFoundException3)
                    {
                        ItemNotFoundException itemNotFoundException2 = itemNotFoundException3;
                        base.WriteError(new ErrorRecord(itemNotFoundException2.ErrorRecord, itemNotFoundException2));
                        continue;
                    }
                    if (!flag2)
                    {
                        bool   flag3 = false;
                        string unresolvedProviderPathFromPSPath = base.GetUnresolvedProviderPathFromPSPath(current.Path);
                        try
                        {
                            flag3 = base.SessionState.Internal.HasChildItems(current.Provider.Name, unresolvedProviderPathFromPSPath, cmdletProviderContext);
                            cmdletProviderContext.ThrowFirstErrorOrDoNothing();
                        }
                        catch (PSNotSupportedException pSNotSupportedException5)
                        {
                            PSNotSupportedException pSNotSupportedException4 = pSNotSupportedException5;
                            base.WriteError(new ErrorRecord(pSNotSupportedException4.ErrorRecord, pSNotSupportedException4));
                            continue;
                        }
                        catch (DriveNotFoundException driveNotFoundException5)
                        {
                            DriveNotFoundException driveNotFoundException4 = driveNotFoundException5;
                            base.WriteError(new ErrorRecord(driveNotFoundException4.ErrorRecord, driveNotFoundException4));
                            continue;
                        }
                        catch (ProviderNotFoundException providerNotFoundException5)
                        {
                            ProviderNotFoundException providerNotFoundException4 = providerNotFoundException5;
                            base.WriteError(new ErrorRecord(providerNotFoundException4.ErrorRecord, providerNotFoundException4));
                            continue;
                        }
                        catch (ItemNotFoundException itemNotFoundException5)
                        {
                            ItemNotFoundException itemNotFoundException4 = itemNotFoundException5;
                            base.WriteError(new ErrorRecord(itemNotFoundException4.ErrorRecord, itemNotFoundException4));
                            continue;
                        }
                        if (!this.Recurse && flag3)
                        {
                            string str1 = StringUtil.Format(NavigationResources.RemoveItemWithChildren, current.Path);
                            if (!base.ShouldContinue(str1, null, ref flag, ref flag1))
                            {
                                continue;
                            }
                        }
                        try
                        {
                            base.SessionState.Internal.RemoveItem(current.Provider.Name, unresolvedProviderPathFromPSPath, this.Recurse, cmdletProviderContext);
                        }
                        catch (PSNotSupportedException pSNotSupportedException7)
                        {
                            PSNotSupportedException pSNotSupportedException6 = pSNotSupportedException7;
                            base.WriteError(new ErrorRecord(pSNotSupportedException6.ErrorRecord, pSNotSupportedException6));
                        }
                        catch (DriveNotFoundException driveNotFoundException7)
                        {
                            DriveNotFoundException driveNotFoundException6 = driveNotFoundException7;
                            base.WriteError(new ErrorRecord(driveNotFoundException6.ErrorRecord, driveNotFoundException6));
                        }
                        catch (ProviderNotFoundException providerNotFoundException7)
                        {
                            ProviderNotFoundException providerNotFoundException6 = providerNotFoundException7;
                            base.WriteError(new ErrorRecord(providerNotFoundException6.ErrorRecord, providerNotFoundException6));
                        }
                        catch (ItemNotFoundException itemNotFoundException7)
                        {
                            ItemNotFoundException itemNotFoundException6 = itemNotFoundException7;
                            base.WriteError(new ErrorRecord(itemNotFoundException6.ErrorRecord, itemNotFoundException6));
                        }
                    }
                    else
                    {
                        object[] objArray = new object[1];
                        objArray[0] = current.Path;
                        PSInvalidOperationException pSInvalidOperationException = PSTraceSource.NewInvalidOperationException("NavigationResources", "RemoveItemInUse", objArray);
                        base.WriteError(new ErrorRecord(pSInvalidOperationException.ErrorRecord, pSInvalidOperationException));
                    }
                }
                return;
            }
        }
Beispiel #12
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;
                    }
                }
            }
        }
Beispiel #13
0
        protected override void ProcessRecord()
        {
            Collection <string> collection  = UpdateData.Glob(base.PrependPath, "FormatPrependPathException", this);
            Collection <string> collection2 = UpdateData.Glob(base.AppendPath, "FormatAppendPathException", this);

            if (((base.PrependPath.Length <= 0) && (base.AppendPath.Length <= 0)) || ((collection.Count != 0) || (collection2.Count != 0)))
            {
                string updateFormatDataAction = UpdateDataStrings.UpdateFormatDataAction;
                string updateTarget           = UpdateDataStrings.UpdateTarget;
                if (base.Context.RunspaceConfiguration != null)
                {
                    for (int i = collection.Count - 1; i >= 0; i--)
                    {
                        string target = string.Format(Thread.CurrentThread.CurrentCulture, updateTarget, new object[] { collection[i] });
                        if (base.ShouldProcess(target, updateFormatDataAction))
                        {
                            base.Context.RunspaceConfiguration.Formats.Prepend(new FormatConfigurationEntry(collection[i]));
                        }
                    }
                    foreach (string str4 in collection2)
                    {
                        string str5 = string.Format(Thread.CurrentThread.CurrentCulture, updateTarget, new object[] { str4 });
                        if (base.ShouldProcess(str5, updateFormatDataAction))
                        {
                            base.Context.RunspaceConfiguration.Formats.Append(new FormatConfigurationEntry(str4));
                        }
                    }
                    try
                    {
                        base.Context.CurrentRunspace.RunspaceConfiguration.Formats.Update(true);
                        return;
                    }
                    catch (RuntimeException exception)
                    {
                        base.WriteError(new ErrorRecord(exception, "FormatXmlUpdateException", ErrorCategory.InvalidOperation, null));
                        return;
                    }
                }
                if (base.Context.InitialSessionState != null)
                {
                    if (base.Context.InitialSessionState.DisableFormatUpdates)
                    {
                        throw new PSInvalidOperationException(UpdateDataStrings.FormatUpdatesDisabled);
                    }
                    HashSet <string> set = new HashSet <string>(StringComparer.CurrentCultureIgnoreCase);
                    Collection <SessionStateFormatEntry> collection3 = new Collection <SessionStateFormatEntry>();
                    for (int j = collection.Count - 1; j >= 0; j--)
                    {
                        string str6 = string.Format(Thread.CurrentThread.CurrentCulture, updateTarget, new object[] { collection[j] });
                        if (base.ShouldProcess(str6, updateFormatDataAction) && !set.Contains(collection[j]))
                        {
                            set.Add(collection[j]);
                            collection3.Add(new SessionStateFormatEntry(collection[j]));
                        }
                    }
                    foreach (SessionStateFormatEntry entry in base.Context.InitialSessionState.Formats)
                    {
                        if (entry.FileName != null)
                        {
                            if (!set.Contains(entry.FileName))
                            {
                                set.Add(entry.FileName);
                                collection3.Add(entry);
                            }
                        }
                        else
                        {
                            collection3.Add(entry);
                        }
                    }
                    foreach (string str7 in collection2)
                    {
                        string str8 = string.Format(Thread.CurrentThread.CurrentCulture, updateTarget, new object[] { str7 });
                        if (base.ShouldProcess(str8, updateFormatDataAction) && !set.Contains(str7))
                        {
                            set.Add(str7);
                            collection3.Add(new SessionStateFormatEntry(str7));
                        }
                    }
                    try
                    {
                        base.Context.InitialSessionState.Formats.Clear();
                        Collection <PSSnapInTypeAndFormatErrors> mshsnapins = new Collection <PSSnapInTypeAndFormatErrors>();
                        foreach (SessionStateFormatEntry entry2 in collection3)
                        {
                            string       fileName = entry2.FileName;
                            PSSnapInInfo pSSnapIn = entry2.PSSnapIn;
                            if ((pSSnapIn != null) && !string.IsNullOrEmpty(pSSnapIn.Name))
                            {
                                fileName = pSSnapIn.Name;
                            }
                            if (entry2.Formattable != null)
                            {
                                PSInvalidOperationException exception2 = new PSInvalidOperationException(UpdateDataStrings.CannotUpdateFormatWithFormatTable);
                                base.WriteError(new ErrorRecord(exception2, "CannotUpdateFormatWithFormatTable", ErrorCategory.InvalidOperation, null));
                            }
                            else
                            {
                                if (entry2.FormatData != null)
                                {
                                    mshsnapins.Add(new PSSnapInTypeAndFormatErrors(fileName, entry2.FormatData));
                                }
                                else
                                {
                                    mshsnapins.Add(new PSSnapInTypeAndFormatErrors(fileName, entry2.FileName));
                                }
                                base.Context.InitialSessionState.Formats.Add(entry2);
                            }
                        }
                        if (mshsnapins.Count > 0)
                        {
                            base.Context.FormatDBManager.UpdateDataBase(mshsnapins, base.Context.AuthorizationManager, base.Context.EngineHostInterface, false);
                            FormatAndTypeDataHelper.ThrowExceptionOnError("ErrorsUpdatingFormats", null, mshsnapins, RunspaceConfigurationCategory.Formats);
                        }
                    }
                    catch (RuntimeException exception3)
                    {
                        base.WriteError(new ErrorRecord(exception3, "FormatXmlUpdateException", ErrorCategory.InvalidOperation, null));
                    }
                }
            }
        }
        protected override void EndProcessing()
        {
            Uri projectUri = null;

            if (!String.IsNullOrEmpty(ProjectUri) && !Utils.TryCreateValidUri(uriString: ProjectUri,
                                                                              cmdletPassedIn: this,
                                                                              uriResult: out projectUri,
                                                                              errorRecord: out ErrorRecord projectErrorRecord))
            {
                ThrowTerminatingError(projectErrorRecord);
            }

            Uri licenseUri = null;

            if (!String.IsNullOrEmpty(LicenseUri) && !Utils.TryCreateValidUri(uriString: LicenseUri,
                                                                              cmdletPassedIn: this,
                                                                              uriResult: out licenseUri,
                                                                              errorRecord: out ErrorRecord licenseErrorRecord))
            {
                ThrowTerminatingError(licenseErrorRecord);
            }

            Uri iconUri = null;

            if (!String.IsNullOrEmpty(IconUri) && !Utils.TryCreateValidUri(uriString: IconUri,
                                                                           cmdletPassedIn: this,
                                                                           uriResult: out iconUri,
                                                                           errorRecord: out ErrorRecord iconErrorRecord))
            {
                ThrowTerminatingError(iconErrorRecord);
            }

            if (!Path.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase))
            {
                var exMessage = "File path needs to end with a .ps1 extension. Example: C:/Users/john/x/MyScript.ps1";
                var ex        = new ArgumentException(exMessage);
                var InvalidOrNonExistantPathError = new ErrorRecord(ex, "InvalidOrNonExistantPath", ErrorCategory.InvalidArgument, null);
                ThrowTerminatingError(InvalidOrNonExistantPathError);
            }

            var resolvedPaths = SessionState.Path.GetResolvedPSPathFromPSPath(Path);

            if (resolvedPaths.Count != 1)
            {
                var exMessage = "Error: Could not resolve provided Path argument into a single path.";
                var ex        = new PSArgumentException(exMessage);
                var InvalidPathArgumentError = new ErrorRecord(ex, "InvalidPathArgumentError", ErrorCategory.InvalidArgument, null);
                ThrowTerminatingError(InvalidPathArgumentError);
            }

            string resolvedPath = resolvedPaths[0].Path;

            if (!File.Exists(resolvedPath))
            {
                var exMessage             = "A script file does not exist at the location specified";
                var ex                    = new ArgumentException(exMessage);
                var FileDoesNotExistError = new ErrorRecord(ex, "FileDoesNotExistAtPath", ErrorCategory.InvalidArgument, null);
                ThrowTerminatingError(FileDoesNotExistError);
            }

            ModuleSpecification[] validatedRequiredModuleSpecifications = Array.Empty <ModuleSpecification>();
            if (RequiredModules != null && RequiredModules.Length > 0)
            {
                if (!Utils.TryCreateModuleSpecification(
                        moduleSpecHashtables: RequiredModules,
                        out validatedRequiredModuleSpecifications,
                        out ErrorRecord[] moduleSpecErrors))
                {
                    foreach (ErrorRecord err in moduleSpecErrors)
                    {
                        WriteError(err);
                    }

                    return;
                }
            }

            if (!PSScriptFileInfo.TryTestPSScriptFile(
                    scriptFileInfoPath: resolvedPath,
                    parsedScript: out PSScriptFileInfo parsedScriptInfo,
                    errors: out ErrorRecord[] errors,
                    out string[] verboseMsgs))
            {
                foreach (string msg in verboseMsgs)
                {
                    WriteVerbose(msg);
                }

                foreach (ErrorRecord error in errors)
                {
                    WriteError(error);
                }

                return;
            }

            bool signatureRemoved = false;

            if (parsedScriptInfo.ScriptContent.ContainsSignature)
            {
                if (!RemoveSignature)
                {
                    var exMessage = "Cannot update the script file because the file contains a signature block and updating will invalidate the signature. Use -RemoveSignature to remove the signature block, and then re-sign the file after it is updated.";
                    var ex        = new PSInvalidOperationException(exMessage);
                    var ScriptToBeUpdatedContainsSignatureError = new ErrorRecord(ex, "ScriptToBeUpdatedContainsSignature", ErrorCategory.InvalidOperation, null);
                    ThrowTerminatingError(ScriptToBeUpdatedContainsSignatureError);
                }

                signatureRemoved = true;
            }

            if (!PSScriptFileInfo.TryUpdateScriptFileContents(
                    scriptInfo: parsedScriptInfo,
                    updatedPSScriptFileContents: out string[] updatedPSScriptFileContents,
                    errors: out ErrorRecord[] updateErrors,
                    version: Version,
                    guid: Guid,
                    author: Author,
                    companyName: CompanyName,
                    copyright: Copyright,
                    tags: Tags,
                    licenseUri: licenseUri,
                    projectUri: projectUri,
                    iconUri: iconUri,
                    requiredModules: validatedRequiredModuleSpecifications,
                    externalModuleDependencies: ExternalModuleDependencies,
                    requiredScripts: RequiredScripts,
                    externalScriptDependencies: ExternalScriptDependencies,
                    releaseNotes: ReleaseNotes,
                    privateData: PrivateData,
                    description: Description))
            {
                WriteWarning("Updating the specified script file failed due to the following error(s):");
                foreach (ErrorRecord error in updateErrors)
                {
                    WriteError(error);
                }

                return;
            }

            string tempScriptPath = null;

            try
            {
                tempScriptPath = System.IO.Path.GetTempFileName();

                File.WriteAllLines(tempScriptPath, updatedPSScriptFileContents);
                File.Copy(tempScriptPath, resolvedPath, overwrite: true);
            }
            catch (Exception e)
            {
                WriteError(new ErrorRecord(
                               new PSInvalidOperationException($"Could not update .ps1 file due to: {e.Message}"),
                               "FileIOErrorDuringUpdate",
                               ErrorCategory.InvalidArgument,
                               this));
            }
            finally
            {
                if (tempScriptPath != null)
                {
                    File.Delete(tempScriptPath);
                }
            }

            if (signatureRemoved)
            {
                WriteWarning("Re-sign this script, as the original signature was removed during update.");
            }
        }
Beispiel #15
0
        public override InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo)
        {
            InitialSessionState state = null;
            bool        flag          = false;
            string      str           = TryGetValue(this.configHash, ConfigFileContants.SessionType);
            SessionType type          = SessionType.Default;
            bool        flag2         = this.IsNonDefaultVisibiltySpecified(ConfigFileContants.VisibleCmdlets);
            bool        flag3         = this.IsNonDefaultVisibiltySpecified(ConfigFileContants.VisibleFunctions);
            bool        flag4         = this.IsNonDefaultVisibiltySpecified(ConfigFileContants.VisibleAliases);
            bool        flag5         = this.IsNonDefaultVisibiltySpecified(ConfigFileContants.VisibleProviders);

            if (!string.IsNullOrEmpty(str))
            {
                type = (SessionType)Enum.Parse(typeof(SessionType), str, true);
                switch (type)
                {
                case SessionType.Empty:
                    state = InitialSessionState.Create();
                    goto Label_00AD;

                case SessionType.RestrictedRemoteServer:
                    state = InitialSessionState.CreateRestricted(SessionCapabilities.RemoteServer);
                    if (flag5)
                    {
                        InitialSessionState state2 = InitialSessionState.CreateDefault2();
                        state.Providers.Add(state2.Providers);
                    }
                    goto Label_00AD;
                }
                state = InitialSessionState.CreateDefault2();
            }
            else
            {
                state = InitialSessionState.CreateDefault2();
            }
Label_00AD:
            if (this.configHash.ContainsKey(ConfigFileContants.AssembliesToLoad))
            {
                string[] strArray = TryGetStringArray(this.configHash[ConfigFileContants.AssembliesToLoad]);
                if (strArray != null)
                {
                    foreach (string str2 in strArray)
                    {
                        state.Assemblies.Add(new SessionStateAssemblyEntry(str2));
                    }
                }
            }
            if (this.configHash.ContainsKey(ConfigFileContants.ModulesToImport))
            {
                object[] objArray = TryGetObjectsOfType <object>(this.configHash[ConfigFileContants.ModulesToImport], new Type[] { typeof(string), typeof(Hashtable) });
                if ((this.configHash[ConfigFileContants.ModulesToImport] != null) && (objArray == null))
                {
                    PSInvalidOperationException exception = new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeStringOrHashtableArray, ConfigFileContants.ModulesToImport));
                    exception.SetErrorId("InvalidModulesToImportKeyEntries");
                    throw exception;
                }
                if (objArray != null)
                {
                    Collection <ModuleSpecification> modules = new Collection <ModuleSpecification>();
                    foreach (object obj2 in objArray)
                    {
                        ModuleSpecification item = null;
                        string str4 = obj2 as string;
                        if (!string.IsNullOrEmpty(str4))
                        {
                            item = new ModuleSpecification(str4);
                        }
                        else
                        {
                            Hashtable moduleSpecification = obj2 as Hashtable;
                            if (moduleSpecification != null)
                            {
                                item = new ModuleSpecification(moduleSpecification);
                            }
                        }
                        if (item != null)
                        {
                            if (string.Equals(InitialSessionState.CoreModule, item.Name, StringComparison.OrdinalIgnoreCase))
                            {
                                if (type == SessionType.Empty)
                                {
                                    state.ImportCorePSSnapIn();
                                }
                            }
                            else
                            {
                                modules.Add(item);
                            }
                        }
                    }
                    state.ImportPSModule(modules);
                }
            }
            if (this.configHash.ContainsKey(ConfigFileContants.AliasDefinitions))
            {
                Hashtable[] hashtableArray = TryGetHashtableArray(this.configHash[ConfigFileContants.AliasDefinitions]);
                if (hashtableArray != null)
                {
                    foreach (Hashtable hashtable2 in hashtableArray)
                    {
                        SessionStateAliasEntry entry = this.CreateSessionStateAliasEntry(hashtable2);
                        if (entry != null)
                        {
                            state.Commands.Add(entry);
                        }
                    }
                }
            }
            if (this.configHash.ContainsKey(ConfigFileContants.FunctionDefinitions))
            {
                Hashtable[] hashtableArray2 = TryGetHashtableArray(this.configHash[ConfigFileContants.FunctionDefinitions]);
                if (hashtableArray2 != null)
                {
                    foreach (Hashtable hashtable3 in hashtableArray2)
                    {
                        SessionStateFunctionEntry entry2 = this.CreateSessionStateFunctionEntry(hashtable3);
                        if (entry2 != null)
                        {
                            state.Commands.Add(entry2);
                        }
                    }
                }
            }
            if (this.configHash.ContainsKey(ConfigFileContants.VariableDefinitions))
            {
                Hashtable[] hashtableArray3 = TryGetHashtableArray(this.configHash[ConfigFileContants.VariableDefinitions]);
                if (hashtableArray3 != null)
                {
                    foreach (Hashtable hashtable4 in hashtableArray3)
                    {
                        if (!hashtable4.ContainsKey(ConfigFileContants.VariableValueToken) || !(hashtable4[ConfigFileContants.VariableValueToken] is ScriptBlock))
                        {
                            SessionStateVariableEntry entry3 = this.CreateSessionStateVariableEntry(hashtable4);
                            if (entry3 != null)
                            {
                                state.Variables.Add(entry3);
                            }
                        }
                    }
                }
            }
            if (this.configHash.ContainsKey(ConfigFileContants.TypesToProcess))
            {
                string[] strArray2 = TryGetStringArray(this.configHash[ConfigFileContants.TypesToProcess]);
                if (strArray2 != null)
                {
                    foreach (string str5 in strArray2)
                    {
                        if (!string.IsNullOrEmpty(str5))
                        {
                            state.Types.Add(new SessionStateTypeEntry(str5));
                        }
                    }
                }
            }
            if (this.configHash.ContainsKey(ConfigFileContants.FormatsToProcess))
            {
                string[] strArray3 = TryGetStringArray(this.configHash[ConfigFileContants.FormatsToProcess]);
                if (strArray3 != null)
                {
                    foreach (string str6 in strArray3)
                    {
                        if (!string.IsNullOrEmpty(str6))
                        {
                            state.Formats.Add(new SessionStateFormatEntry(str6));
                        }
                    }
                }
            }
            if ((flag2 || flag3) || (flag4 || flag5))
            {
                flag = true;
            }
            if (flag)
            {
                state.Variables.Add(new SessionStateVariableEntry("PSModuleAutoLoadingPreference", PSModuleAutoLoadingPreference.None, string.Empty, ScopedItemOptions.None));
                if (type == SessionType.Default)
                {
                    state.ImportPSCoreModule(InitialSessionState.EngineModules.ToArray <string>());
                }
                if (!flag2)
                {
                    state.Commands.Remove("Import-Module", typeof(SessionStateCmdletEntry));
                }
                if (!flag4)
                {
                    state.Commands.Remove("ipmo", typeof(SessionStateAliasEntry));
                }
            }
            return(state);
        }
        protected override void EndProcessing()
        {
            var vaultInfo = new Hashtable();

            // Validate mandatory parameters.
            var vaultItems = RegisteredVaultCache.GetAll();

            if (vaultItems.ContainsKey(Name))
            {
                ThrowTerminatingError(
                    new ErrorRecord(
                        new InvalidOperationException("Provided Name for vault is already being used."),
                        "RegisterSecretVaultInvalidVaultName",
                        ErrorCategory.InvalidArgument,
                        this));
            }

            if (!ShouldProcess(Name, VerbsLifecycle.Register))
            {
                return;
            }

            var moduleInfo = GetModuleInfo(ModuleName);

            if (moduleInfo == null)
            {
                var msg = string.Format(CultureInfo.InvariantCulture,
                                        "Could not load and retrieve module information for module: {0}.",
                                        ModuleName);

                ThrowTerminatingError(
                    new ErrorRecord(
                        new PSInvalidOperationException(msg),
                        "RegisterSecretVaultCantGetModuleInfo",
                        ErrorCategory.InvalidOperation,
                        this));
            }

            var modulePath = moduleInfo.Path;
            var dirPath    = System.IO.File.Exists(modulePath) ? System.IO.Path.GetDirectoryName(modulePath) : modulePath;

            // Check module required modules for implementing type of SecretManagementExtension class.
            Type implementingType = GetImplementingTypeFromRequiredAssemblies(moduleInfo);

            // Check if module supports implementing functions.
            var haveScriptFunctionImplementation = CheckForImplementingModule(
                dirPath: dirPath,
                error: out Exception error);

            if (implementingType == null && !haveScriptFunctionImplementation)
            {
                var invalidException = new PSInvalidOperationException(
                    message: "Could not find a SecretManagementExtension implementing type, or a valid implementing script module.",
                    innerException: error);

                ThrowTerminatingError(
                    new ErrorRecord(
                        invalidException,
                        "RegisterSecretVaultCantFindImplementingTypeOrScriptModule",
                        ErrorCategory.ObjectNotFound,
                        this));
            }

            vaultInfo.Add(ExtensionVaultModule.ModulePathStr, dirPath);
            vaultInfo.Add(ExtensionVaultModule.ModuleNameStr, moduleInfo.Name);

            vaultInfo.Add(
                key: ExtensionVaultModule.ImplementingTypeStr,
                value: new Hashtable()
            {
                { "AssemblyName", implementingType != null ? implementingType.Assembly.GetName().Name : string.Empty },
                { "TypeName", implementingType != null ? implementingType.FullName: string.Empty }
            });

            vaultInfo.Add(
                key: ExtensionVaultModule.ImplementingFunctionsStr,
                value: haveScriptFunctionImplementation);

            // Store the optional secret parameters
            StoreVaultParameters(
                vaultInfo: vaultInfo,
                vaultName: Name,
                parameters: VaultParameters);

            // Register new secret vault information.
            RegisteredVaultCache.Add(
                keyName: Name,
                vaultInfo: vaultInfo);
        }
        protected override void EndProcessing()
        {
            var vaultInfo = new Hashtable();

            // Validate mandatory parameters.
            var vaultItems = RegisteredVaultCache.GetAll();

            if (vaultItems.ContainsKey(Name))
            {
                ThrowTerminatingError(
                    new ErrorRecord(
                        new InvalidOperationException("Provided Name for vault is already being used."),
                        "RegisterSecretVaultInvalidVaultName",
                        ErrorCategory.InvalidArgument,
                        this));
            }

            if (!ShouldProcess(Name, VerbsLifecycle.Register))
            {
                return;
            }

            // Resolve the module name path in calling context, if it is a path and not a name.
            var results = InvokeCommand.InvokeScript(
                script: "param([string] $path) (Resolve-Path -Path $path -EA Silent).Path",
                args: new object[] { ModuleName });
            string resolvedPath     = (results.Count == 1 && results[0] != null) ? (string)results[0].BaseObject : null;
            string moduleNameOrPath = resolvedPath ?? ModuleName;

            results = InvokeCommand.InvokeScript(
                script: "(Get-Module -Name Microsoft.PowerShell.SecretManagement).ModuleBase");
            string secretMgtModulePath = (results.Count == 1 && results[0] != null) ? (string)results[0].BaseObject : string.Empty;

            secretMgtModulePath = System.IO.Path.Combine(secretMgtModulePath, "Microsoft.PowerShell.SecretManagement.psd1");

            var moduleInfo = GetModuleInfo(
                modulePath: moduleNameOrPath,
                secretMgtModulePath: secretMgtModulePath,
                error: out ErrorRecord moduleLoadError);

            if (moduleInfo == null)
            {
                var msg = string.Format(CultureInfo.InvariantCulture,
                                        "Could not load and retrieve module information for module: {0} with error : {1}.",
                                        ModuleName, moduleLoadError?.ToString() ?? string.Empty);

                ThrowTerminatingError(
                    new ErrorRecord(
                        new PSInvalidOperationException(msg),
                        "RegisterSecretVaultCantGetModuleInfo",
                        ErrorCategory.InvalidOperation,
                        this));
            }

            if (!CheckForImplementingModule(
                    dirPath: moduleInfo.ModuleBase,
                    moduleName: moduleInfo.Name,
                    secretMgtModulePath: secretMgtModulePath,
                    error: out Exception error))
            {
                var invalidException = new PSInvalidOperationException(
                    message: "Could not find a SecretManagement extension implementing script module.",
                    innerException: error);

                ThrowTerminatingError(
                    new ErrorRecord(
                        invalidException,
                        "RegisterSecretVaultCantFindImplementingScriptModule",
                        ErrorCategory.ObjectNotFound,
                        this));
            }

            // Find base path of module without version folder, to store in vault registry.
            string dirPath;

            if (System.IO.Path.GetFileName(moduleInfo.ModuleBase).Equals(moduleInfo.Name, StringComparison.OrdinalIgnoreCase))
            {
                dirPath = moduleInfo.ModuleBase;
            }
            else
            {
                var parent = System.IO.Directory.GetParent(moduleInfo.ModuleBase);
                while (parent != null && !parent.Name.Equals(moduleInfo.Name, StringComparison.OrdinalIgnoreCase))
                {
                    parent = parent.Parent;
                }
                dirPath = parent?.FullName ?? moduleInfo.ModuleBase;
            }

            // Store module information.
            vaultInfo.Add(
                key: ExtensionVaultModule.ModulePathStr,
                value: dirPath);
            vaultInfo.Add(
                key: ExtensionVaultModule.ModuleNameStr,
                value: moduleInfo.Name);

            // Store optional vault parameters.
            vaultInfo.Add(
                key: ExtensionVaultModule.VaultParametersStr,
                value: VaultParameters);

            // Register new secret vault information.
            RegisteredVaultCache.Add(
                keyName: Name,
                vaultInfo: vaultInfo,
                defaultVault: DefaultVault);
        }
Beispiel #18
0
        private void MoveItem(string path)
        {
            CmdletProviderContext cmdletProviderContext = this.CmdletProviderContext;

            try
            {
                string str = path;
                if (!base.SuppressWildcardExpansion)
                {
                    str = WildcardPattern.Escape(path);
                }
                if (!base.InvokeProvider.Item.Exists(str, cmdletProviderContext))
                {
                    object[] objArray = new object[1];
                    objArray[0] = path;
                    PSInvalidOperationException pSInvalidOperationException = PSTraceSource.NewInvalidOperationException("NavigationResources", "MoveItemDoesntExist", objArray);
                    base.WriteError(new ErrorRecord(pSInvalidOperationException.ErrorRecord, pSInvalidOperationException));
                    return;
                }
            }
            catch (PSNotSupportedException pSNotSupportedException1)
            {
                PSNotSupportedException pSNotSupportedException = pSNotSupportedException1;
                base.WriteError(new ErrorRecord(pSNotSupportedException.ErrorRecord, pSNotSupportedException));
                return;
            }
            catch (DriveNotFoundException driveNotFoundException1)
            {
                DriveNotFoundException driveNotFoundException = driveNotFoundException1;
                base.WriteError(new ErrorRecord(driveNotFoundException.ErrorRecord, driveNotFoundException));
                return;
            }
            catch (ProviderNotFoundException providerNotFoundException1)
            {
                ProviderNotFoundException providerNotFoundException = providerNotFoundException1;
                base.WriteError(new ErrorRecord(providerNotFoundException.ErrorRecord, providerNotFoundException));
                return;
            }
            catch (ItemNotFoundException itemNotFoundException1)
            {
                ItemNotFoundException itemNotFoundException = itemNotFoundException1;
                base.WriteError(new ErrorRecord(itemNotFoundException.ErrorRecord, itemNotFoundException));
                return;
            }
            bool flag = false;

            try
            {
                flag = base.SessionState.Path.IsCurrentLocationOrAncestor(path, cmdletProviderContext);
            }
            catch (PSNotSupportedException pSNotSupportedException3)
            {
                PSNotSupportedException pSNotSupportedException2 = pSNotSupportedException3;
                base.WriteError(new ErrorRecord(pSNotSupportedException2.ErrorRecord, pSNotSupportedException2));
                return;
            }
            catch (DriveNotFoundException driveNotFoundException3)
            {
                DriveNotFoundException driveNotFoundException2 = driveNotFoundException3;
                base.WriteError(new ErrorRecord(driveNotFoundException2.ErrorRecord, driveNotFoundException2));
                return;
            }
            catch (ProviderNotFoundException providerNotFoundException3)
            {
                ProviderNotFoundException providerNotFoundException2 = providerNotFoundException3;
                base.WriteError(new ErrorRecord(providerNotFoundException2.ErrorRecord, providerNotFoundException2));
                return;
            }
            catch (ItemNotFoundException itemNotFoundException3)
            {
                ItemNotFoundException itemNotFoundException2 = itemNotFoundException3;
                base.WriteError(new ErrorRecord(itemNotFoundException2.ErrorRecord, itemNotFoundException2));
                return;
            }
            if (!flag)
            {
                CmdletProviderContext passThru = cmdletProviderContext;
                passThru.PassThru = this.PassThru;
                object[] destination = new object[2];
                destination[0] = path;
                destination[1] = this.Destination;
                CoreCommandBase.tracer.WriteLine("Moving {0} to {1}", destination);
                try
                {
                    string str1 = path;
                    if (!base.SuppressWildcardExpansion)
                    {
                        str1 = WildcardPattern.Escape(path);
                    }
                    base.InvokeProvider.Item.Move(str1, this.Destination, passThru);
                }
                catch (PSNotSupportedException pSNotSupportedException5)
                {
                    PSNotSupportedException pSNotSupportedException4 = pSNotSupportedException5;
                    base.WriteError(new ErrorRecord(pSNotSupportedException4.ErrorRecord, pSNotSupportedException4));
                }
                catch (DriveNotFoundException driveNotFoundException5)
                {
                    DriveNotFoundException driveNotFoundException4 = driveNotFoundException5;
                    base.WriteError(new ErrorRecord(driveNotFoundException4.ErrorRecord, driveNotFoundException4));
                }
                catch (ProviderNotFoundException providerNotFoundException5)
                {
                    ProviderNotFoundException providerNotFoundException4 = providerNotFoundException5;
                    base.WriteError(new ErrorRecord(providerNotFoundException4.ErrorRecord, providerNotFoundException4));
                }
                catch (ItemNotFoundException itemNotFoundException5)
                {
                    ItemNotFoundException itemNotFoundException4 = itemNotFoundException5;
                    base.WriteError(new ErrorRecord(itemNotFoundException4.ErrorRecord, itemNotFoundException4));
                }
            }
            else
            {
                object[] objArray1 = new object[1];
                objArray1[0] = path;
                PSInvalidOperationException pSInvalidOperationException1 = PSTraceSource.NewInvalidOperationException("NavigationResources", "MoveItemInUse", objArray1);
                base.WriteError(new ErrorRecord(pSInvalidOperationException1.ErrorRecord, pSInvalidOperationException1));
                return;
            }
        }
Beispiel #19
0
        private int _numberRemoved = 0;  // Maintains a count of the number of modules removed...

        /// <summary>
        /// Remove the specified modules. Modules can be specified either through a ModuleInfo or a name.
        /// </summary>
        protected override void ProcessRecord()
        {
            // This dictionary has the list of modules to be removed.
            // Key - Module specified as a parameter to Remove-Module
            // Values - List of all modules that need to be removed for this key (includes all nested modules of this module)
            Dictionary <PSModuleInfo, List <PSModuleInfo> > modulesToRemove = new Dictionary <PSModuleInfo, List <PSModuleInfo> >();

            foreach (var m in Context.Modules.GetModules(_name, false))
            {
                modulesToRemove.Add(m, new List <PSModuleInfo> {
                    m
                });
            }

            if (FullyQualifiedName != null)
            {
                foreach (var m in Context.Modules.GetModules(FullyQualifiedName, false))
                {
                    modulesToRemove.Add(m, new List <PSModuleInfo> {
                        m
                    });
                }
            }

            foreach (var m in _moduleInfo)
            {
                modulesToRemove.Add(m, new List <PSModuleInfo> {
                    m
                });
            }

            // Add any of the child modules of a manifests to the list of modules to remove...
            Dictionary <PSModuleInfo, List <PSModuleInfo> > nestedModules = new Dictionary <PSModuleInfo, List <PSModuleInfo> >();

            foreach (var entry in modulesToRemove)
            {
                var module = entry.Key;
                if (module.NestedModules != null && module.NestedModules.Count > 0)
                {
                    List <PSModuleInfo> nestedModulesWithNoCircularReference = new List <PSModuleInfo>();
                    GetAllNestedModules(module, ref nestedModulesWithNoCircularReference);
                    nestedModules.Add(module, nestedModulesWithNoCircularReference);
                }
            }

            // dont add duplicates to our original modulesToRemove list..so that the
            // evaluation loop below will not duplicate in case of WriteError and WriteWarning.
            // A global list of modules to be removed is maintained for this purpose
            HashSet <PSModuleInfo> globalListOfModules = new HashSet <PSModuleInfo>(new PSModuleInfoComparer());

            if (nestedModules.Count > 0)
            {
                foreach (var entry in nestedModules)
                {
                    List <PSModuleInfo> values = null;
                    if (modulesToRemove.TryGetValue(entry.Key, out values))
                    {
                        foreach (var module in entry.Value)
                        {
                            if (!globalListOfModules.Contains(module))
                            {
                                values.Add(module);
                                globalListOfModules.Add(module);
                            }
                        }
                    }
                }
            }

            // Check the list of modules to remove and exclude those that cannot or should not be removed
            Dictionary <PSModuleInfo, List <PSModuleInfo> > actualModulesToRemove = new Dictionary <PSModuleInfo, List <PSModuleInfo> >();

            // We want to remove the modules starting from the nested modules
            // If we start from the parent module, the nested modules do not get removed and are left orphaned in the parent modules's sessionstate.
            foreach (var entry in modulesToRemove)
            {
                List <PSModuleInfo> moduleList = new List <PSModuleInfo>();
                for (int i = entry.Value.Count - 1; i >= 0; i--)
                {
                    PSModuleInfo module = entry.Value[i];
                    // See if the module is constant...
                    if (module.AccessMode == ModuleAccessMode.Constant)
                    {
                        string message = StringUtil.Format(Modules.ModuleIsConstant, module.Name);
                        InvalidOperationException moduleNotRemoved = new InvalidOperationException(message);
                        ErrorRecord er = new ErrorRecord(moduleNotRemoved, "Modules_ModuleIsConstant",
                                                         ErrorCategory.PermissionDenied, module);
                        WriteError(er);
                        continue;
                    }

                    // See if the module is readonly...
                    if (module.AccessMode == ModuleAccessMode.ReadOnly && !BaseForce)
                    {
                        string message = StringUtil.Format(Modules.ModuleIsReadOnly, module.Name);

                        if (InitialSessionState.IsConstantEngineModule(module.Name))
                        {
                            WriteWarning(message);
                        }
                        else
                        {
                            InvalidOperationException moduleNotRemoved = new InvalidOperationException(message);
                            ErrorRecord er = new ErrorRecord(moduleNotRemoved, "Modules_ModuleIsReadOnly",
                                                             ErrorCategory.PermissionDenied, module);
                            WriteError(er);
                        }
                        continue;
                    }

                    if (!ShouldProcess(StringUtil.Format(Modules.ConfirmRemoveModule, module.Name, module.Path)))
                    {
                        continue;
                    }

                    // If this module provides the current session drive, then we cannot remove it.
                    // Abort this command since we don't want to do a partial removal of a module manifest.
                    if (ModuleProvidesCurrentSessionDrive(module))
                    {
                        if (InitialSessionState.IsEngineModule(module.Name))
                        {
                            if (!BaseForce)
                            {
                                string message = StringUtil.Format(Modules.CoreModuleCannotBeRemoved, module.Name);
                                this.WriteWarning(message);
                            }
                            continue;
                        }
                        // Specify the overall module name if there is only one.
                        // Otherwise specify the particular module name.
                        string moduleName = (_name.Length == 1) ? _name[0] : module.Name;

                        PSInvalidOperationException invalidOperation =
                            PSTraceSource.NewInvalidOperationException(
                                Modules.ModuleDriveInUse,
                                moduleName);

                        throw (invalidOperation);
                    }

                    // Add module to remove list.
                    moduleList.Add(module);
                }
                actualModulesToRemove[entry.Key] = moduleList;
            }

            // Now remove the modules, first checking the RequiredModules dependencies
            Dictionary <PSModuleInfo, List <PSModuleInfo> > requiredDependencies = GetRequiredDependencies();

            foreach (var entry in actualModulesToRemove)
            {
                foreach (var module in entry.Value)
                {
                    if (!BaseForce)
                    {
                        List <PSModuleInfo> requiredBy = null;

                        if (requiredDependencies.TryGetValue(module, out requiredBy))
                        {
                            for (int i = requiredBy.Count - 1; i >= 0; i--)
                            {
                                if (actualModulesToRemove.ContainsKey(requiredBy[i]))
                                {
                                    requiredBy.RemoveAt(i);
                                }
                            }

                            if (requiredBy.Count > 0)
                            {
                                string message = StringUtil.Format(Modules.ModuleIsRequired, module.Name, requiredBy[0].Name);
                                InvalidOperationException moduleNotRemoved = new InvalidOperationException(message);
                                ErrorRecord er = new ErrorRecord(moduleNotRemoved, "Modules_ModuleIsRequired",
                                                                 ErrorCategory.PermissionDenied, module);
                                WriteError(er);
                                continue;
                            }
                        }
                    }

                    _numberRemoved++;

                    this.RemoveModule(module, entry.Key.Name);
                }
            }
        }
        /// <summary>
        /// Adjusts for any variations in different protocol versions. Following changes are considered
        /// - In V2, default max envelope size is 150KB while in V3 it has been changed to 500KB. 
        ///   With default configuration remoting from V3 client to V2 server will break as V3 client can send upto 500KB in a single Send packet
        ///   So if server version is known to be V2, we'll downgrade the max env size to 150KB (V2's default) if the current value is 500KB (V3 default)
        /// </summary>
        /// <param name="serverProtocolVersion">server negotiated protocol version</param>
        internal void AdjustForProtocolVariations(Version serverProtocolVersion)
        {
            if (serverProtocolVersion <= RemotingConstants.ProtocolVersionWin7RTM)
            {
                int maxEnvSize;
                WSManNativeApi.WSManGetSessionOptionAsDword(_wsManSessionHandle,
                    WSManNativeApi.WSManSessionOption.WSMAN_OPTION_MAX_ENVELOPE_SIZE_KB,
                    out maxEnvSize);

                if (maxEnvSize == WSManNativeApi.WSMAN_DEFAULT_MAX_ENVELOPE_SIZE_KB_V3)
                {
                    int result = WSManNativeApi.WSManSetSessionOption(_wsManSessionHandle,
                    WSManNativeApi.WSManSessionOption.WSMAN_OPTION_MAX_ENVELOPE_SIZE_KB,
                    new WSManNativeApi.WSManDataDWord(WSManNativeApi.WSMAN_DEFAULT_MAX_ENVELOPE_SIZE_KB_V2));

                    if (result != 0)
                    {
                        // Get the error message from WSMan
                        string errorMessage = WSManNativeApi.WSManGetErrorMessage(WSManAPIData.WSManAPIHandle, result);

                        PSInvalidOperationException exception = new PSInvalidOperationException(errorMessage);
                        throw exception;
                    }

                    //retrieve the packet size again
                    int packetSize;
                    WSManNativeApi.WSManGetSessionOptionAsDword(_wsManSessionHandle,
                        WSManNativeApi.WSManSessionOption.WSMAN_OPTION_SHELL_MAX_DATA_SIZE_PER_MESSAGE_KB,
                        out packetSize);
                    // packet size returned is in KB. Convert this into bytes
                    Fragmentor.FragmentSize = packetSize << 10;
                }
            }
        }