Ejemplo n.º 1
0
 internal AliasInfo SetAliasItem(AliasInfo aliasToSet, bool force, CommandOrigin origin = CommandOrigin.Internal)
 {
     if (!this.GetAliases().ContainsKey(aliasToSet.Name))
     {
         if (this.GetAliases().Count > (this.AliasCapacity.FastValue - 1))
         {
             SessionStateOverflowException exception = new SessionStateOverflowException(aliasToSet.Name, SessionStateCategory.Alias, "AliasOverflow", SessionStateStrings.AliasOverflow, new object[] { this.AliasCapacity.FastValue });
             throw exception;
         }
         this.GetAliases()[aliasToSet.Name] = aliasToSet;
     }
     else
     {
         AliasInfo valueToCheck = this.GetAliases()[aliasToSet.Name];
         SessionState.ThrowIfNotVisible(origin, valueToCheck);
         if (((valueToCheck.Options & ScopedItemOptions.Constant) != ScopedItemOptions.None) || (((valueToCheck.Options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None) && !force))
         {
             SessionStateUnauthorizedAccessException exception2 = new SessionStateUnauthorizedAccessException(aliasToSet.Name, SessionStateCategory.Alias, "AliasNotWritable", SessionStateStrings.AliasNotWritable);
             throw exception2;
         }
         if (((aliasToSet.Options & ScopedItemOptions.AllScope) == ScopedItemOptions.None) && ((valueToCheck.Options & ScopedItemOptions.AllScope) != ScopedItemOptions.None))
         {
             SessionStateUnauthorizedAccessException exception3 = new SessionStateUnauthorizedAccessException(aliasToSet.Name, SessionStateCategory.Alias, "AliasAllScopeOptionCannotBeRemoved", SessionStateStrings.AliasAllScopeOptionCannotBeRemoved);
             throw exception3;
         }
         this.RemoveAliasFromCache(valueToCheck.Name, valueToCheck.Definition);
         this.GetAliases()[aliasToSet.Name] = aliasToSet;
     }
     this.AddAliasToCache(aliasToSet.Name, aliasToSet.Definition);
     return(this.GetAliases()[aliasToSet.Name]);
 }
Ejemplo n.º 2
0
 internal void Update(System.Management.Automation.ScriptBlock newFunction, bool force, ScopedItemOptions options, string helpFile)
 {
     if (newFunction == null)
     {
         throw PSTraceSource.NewArgumentNullException("function");
     }
     if ((this._options & ScopedItemOptions.Constant) != ScopedItemOptions.None)
     {
         SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException(base.Name, SessionStateCategory.Function, "FunctionIsConstant", SessionStateStrings.FunctionIsConstant);
         throw exception;
     }
     if (!force && ((this._options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None))
     {
         SessionStateUnauthorizedAccessException exception2 = new SessionStateUnauthorizedAccessException(base.Name, SessionStateCategory.Function, "FunctionIsReadOnly", SessionStateStrings.FunctionIsReadOnly);
         throw exception2;
     }
     this._scriptBlock = newFunction;
     base.SetModule(newFunction.Module);
     this._commandMetadata         = null;
     base._parameterSets           = null;
     base._externalCommandMetadata = null;
     if (options != ScopedItemOptions.Unspecified)
     {
         this.Options = options;
     }
     this._helpFile = helpFile;
 }
Ejemplo n.º 3
0
        private void SetValue(object value)
        {
            if ((this.options & (ScopedItemOptions.Constant | ScopedItemOptions.ReadOnly)) != ScopedItemOptions.None)
            {
                SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException(this.name, SessionStateCategory.Variable, "VariableNotWritable", SessionStateStrings.VariableNotWritable);
                throw exception;
            }
            object obj2 = value;

            if ((this.attributes != null) && (this.attributes.Count > 0))
            {
                obj2 = TransformValue(this.attributes, value);
                if (!this.IsValidValue(obj2))
                {
                    ValidationMetadataException exception2 = new ValidationMetadataException("ValidateSetFailure", null, Metadata.InvalidValueFailure, new object[] { this.name, (obj2 != null) ? obj2.ToString() : "" });
                    throw exception2;
                }
            }
            if (obj2 != null)
            {
                obj2 = CopyMutableValues(obj2);
            }
            this._value = obj2;
            this.DebuggerCheckVariableWrite();
        }
Ejemplo n.º 4
0
 internal AliasInfo SetAliasValue(string name, string value, System.Management.Automation.ExecutionContext context, bool force, CommandOrigin origin)
 {
     if (!this.GetAliases().ContainsKey(name))
     {
         if (this.GetAliases().Count > (this.AliasCapacity.FastValue - 1))
         {
             SessionStateOverflowException exception = new SessionStateOverflowException(name, SessionStateCategory.Alias, "AliasOverflow", SessionStateStrings.AliasOverflow, new object[] { this.AliasCapacity.FastValue });
             throw exception;
         }
         this.GetAliases()[name] = new AliasInfo(name, value, context);
     }
     else
     {
         AliasInfo valueToCheck = this.GetAliases()[name];
         if (((valueToCheck.Options & ScopedItemOptions.Constant) != ScopedItemOptions.None) || (!force && ((valueToCheck.Options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None)))
         {
             SessionStateUnauthorizedAccessException exception2 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Alias, "AliasNotWritable", SessionStateStrings.AliasNotWritable);
             throw exception2;
         }
         SessionState.ThrowIfNotVisible(origin, valueToCheck);
         this.RemoveAliasFromCache(valueToCheck.Name, valueToCheck.Definition);
         if (force)
         {
             this.GetAliases().Remove(name);
             valueToCheck            = new AliasInfo(name, value, context);
             this.GetAliases()[name] = valueToCheck;
         }
         else
         {
             valueToCheck.SetDefinition(value, false);
         }
     }
     this.AddAliasToCache(name, value);
     return(this.GetAliases()[name]);
 }
Ejemplo n.º 5
0
 internal void SetOptions(ScopedItemOptions newOptions, bool force)
 {
     if ((this.options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None)
     {
         SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException(base.Name, SessionStateCategory.Cmdlet, "CmdletIsReadOnly", SessionStateStrings.CmdletIsReadOnly);
         throw exception;
     }
     this.options = newOptions;
 }
Ejemplo n.º 6
0
 internal void SetDefinition(string definition, bool force)
 {
     if (((this.options & ScopedItemOptions.Constant) != ScopedItemOptions.None) || (!force && ((this.options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None)))
     {
         SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException(base.Name, SessionStateCategory.Alias, "AliasNotWritable", SessionStateStrings.AliasNotWritable);
         throw exception;
     }
     this._definition = definition;
 }
Ejemplo n.º 7
0
        internal void SetOptions(ScopedItemOptions newOptions, bool force)
        {
            // Check to see if the variable is constant or readonly, if so
            // throw an exception because the options cannot be changed.

            if (IsConstant || (!force && IsReadOnly))
            {
                SessionStateUnauthorizedAccessException e =
                    new SessionStateUnauthorizedAccessException(
                        Name,
                        SessionStateCategory.Variable,
                        "VariableNotWritable",
                        SessionStateStrings.VariableNotWritable);

                throw e;
            }

            // Now check to see if the caller is trying to set
            // the options to constant. This is only allowed at
            // variable creation

            if ((newOptions & ScopedItemOptions.Constant) != 0)
            {
                // user is trying to set the variable to constant after
                // creating the variable. Do not allow this (as per spec).

                SessionStateUnauthorizedAccessException e =
                    new SessionStateUnauthorizedAccessException(
                        Name,
                        SessionStateCategory.Variable,
                        "VariableCannotBeMadeConstant",
                        SessionStateStrings.VariableCannotBeMadeConstant);

                throw e;
            }

            // Now check to see if the caller is trying to
            // remove the AllScope option. This is not allowed
            // at any time.

            if (IsAllScope && ((newOptions & ScopedItemOptions.AllScope) == 0))
            {
                // user is trying to remove the AllScope option from the variable.
                // Do not allow this (as per spec).

                SessionStateUnauthorizedAccessException e =
                    new SessionStateUnauthorizedAccessException(
                        Name,
                        SessionStateCategory.Variable,
                        "VariableAllScopeOptionCannotBeRemoved",
                        SessionStateStrings.VariableAllScopeOptionCannotBeRemoved);

                throw e;
            }

            _options = newOptions;
        }
Ejemplo n.º 8
0
 internal void SetDefinition(string definition, bool force)
 {
     if (((this.options & ScopedItemOptions.Constant) != ScopedItemOptions.None) || (!force && ((this.options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None)))
     {
         SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException(base.Name, SessionStateCategory.Alias, "AliasNotWritable", SessionStateStrings.AliasNotWritable);
         throw exception;
     }
     this._definition = definition;
 }
Ejemplo n.º 9
0
 internal void SetDefinition(string definition, bool force)
 {
     if ((this.options & ScopedItemOptions.Constant) != ScopedItemOptions.None || !force && (this.options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None)
     {
         SessionStateUnauthorizedAccessException unauthorizedAccessException = new SessionStateUnauthorizedAccessException(this.Name, SessionStateCategory.Alias, "AliasNotWritable");
         AliasInfo.tracer.TraceException((Exception)unauthorizedAccessException);
         throw unauthorizedAccessException;
     }
     this._definition = definition;
 }
Ejemplo n.º 10
0
        private static void CheckVariableCanBeChanged(PSVariable variable, bool force = false)
        {
            if ((variable.ItemOptions.HasFlag(ScopedItemOptions.ReadOnly) && !force) ||
                variable.ItemOptions.HasFlag(ScopedItemOptions.Constant))
            {
                var ex = SessionStateUnauthorizedAccessException.CreateVariableNotWritableError(variable);
                throw ex;
            }

            ThrowIfVariableIsPrivate(variable);
        }
Ejemplo n.º 11
0
 internal FunctionInfo SetFunction(string name, ScriptBlock function, FunctionInfo originalFunction, ScopedItemOptions options, bool force, CommandOrigin origin, System.Management.Automation.ExecutionContext context, string helpFile, Func <string, ScriptBlock, FunctionInfo, ScopedItemOptions, System.Management.Automation.ExecutionContext, string, FunctionInfo> functionFactory)
 {
     if (!this.GetFunctions().ContainsKey(name))
     {
         if (this.GetFunctions().Count > (this.FunctionCapacity.FastValue - 1))
         {
             SessionStateOverflowException exception = new SessionStateOverflowException(name, SessionStateCategory.Function, "FunctionOverflow", SessionStateStrings.FunctionOverflow, new object[] { this.FunctionCapacity.FastValue });
             throw exception;
         }
         FunctionInfo info = functionFactory(name, function, originalFunction, options, context, helpFile);
         this.GetFunctions()[name] = info;
         if (IsFunctionOptionSet(info, ScopedItemOptions.AllScope))
         {
             this.GetAllScopeFunctions()[name] = info;
         }
     }
     else
     {
         FunctionInfo valueToCheck = this.GetFunctions()[name];
         SessionState.ThrowIfNotVisible(origin, valueToCheck);
         if (IsFunctionOptionSet(valueToCheck, ScopedItemOptions.Constant) || (!force && IsFunctionOptionSet(valueToCheck, ScopedItemOptions.ReadOnly)))
         {
             SessionStateUnauthorizedAccessException exception2 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Function, "FunctionNotWritable", SessionStateStrings.FunctionNotWritable);
             throw exception2;
         }
         if ((options & ScopedItemOptions.Constant) != ScopedItemOptions.None)
         {
             SessionStateUnauthorizedAccessException exception3 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Function, "FunctionCannotBeMadeConstant", SessionStateStrings.FunctionCannotBeMadeConstant);
             throw exception3;
         }
         if (((options & ScopedItemOptions.AllScope) == ScopedItemOptions.None) && IsFunctionOptionSet(valueToCheck, ScopedItemOptions.AllScope))
         {
             SessionStateUnauthorizedAccessException exception4 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Function, "FunctionAllScopeOptionCannotBeRemoved", SessionStateStrings.FunctionAllScopeOptionCannotBeRemoved);
             throw exception4;
         }
         FunctionInfo info3       = valueToCheck;
         FunctionInfo newFunction = null;
         if (info3 != null)
         {
             newFunction = functionFactory(name, function, originalFunction, options, context, helpFile);
             if (!info3.GetType().Equals(newFunction.GetType()) || (((info3.Options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None) && force))
             {
                 this.GetFunctions()[name] = newFunction;
             }
             else
             {
                 bool flag2 = force || ((options & ScopedItemOptions.ReadOnly) == ScopedItemOptions.None);
                 info3.Update(newFunction, flag2, options, helpFile);
             }
         }
     }
     return(this.GetFunctions()[name]);
 }
Ejemplo n.º 12
0
 internal void RemoveAlias(string name, bool force)
 {
     if (this.GetAliases().ContainsKey(name))
     {
         AliasInfo info = this.GetAliases()[name];
         if (((info.Options & ScopedItemOptions.Constant) != ScopedItemOptions.None) || (!force && ((info.Options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None)))
         {
             SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Alias, "AliasNotRemovable", SessionStateStrings.AliasNotRemovable);
             throw exception;
         }
         this.RemoveAliasFromCache(info.Name, info.Definition);
     }
     this.GetAliases().Remove(name);
 }
Ejemplo n.º 13
0
 internal override bool CanRenameItem(object item)
 {
     bool flag = false;
     FunctionInfo info = item as FunctionInfo;
     if (info == null)
     {
         return flag;
     }
     if (((info.Options & ScopedItemOptions.Constant) != ScopedItemOptions.None) || (((info.Options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None) && (base.Force == 0)))
     {
         SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException(info.Name, SessionStateCategory.Function, "CannotRenameFunction", SessionStateStrings.CannotRenameFunction);
         throw exception;
     }
     return true;
 }
Ejemplo n.º 14
0
 internal override bool CanRenameItem(object item)
 {
     bool flag = false;
     PSVariable variable = item as PSVariable;
     if (variable == null)
     {
         return flag;
     }
     if (((variable.Options & ScopedItemOptions.Constant) != ScopedItemOptions.None) || (((variable.Options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None) && (base.Force == 0)))
     {
         SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException(variable.Name, SessionStateCategory.Variable, "CannotRenameVariable", SessionStateStrings.CannotRenameVariable);
         throw exception;
     }
     return true;
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Verifies the constraints and attributes before setting the value
        /// </summary>
        /// <param name="value">
        /// The value to be set.
        /// </param>
        /// <exception cref="SessionStateUnauthorizedAccessException">
        /// If the variable is read-only or constant.
        /// </exception>
        /// <exception cref="ValidationMetadataException">
        /// If the validation metadata throws an exception or the value doesn't
        /// pass the validation metadata.
        /// </exception>
        private void SetValue(object value)
        {
            // Check to see if the variable is writable

            if ((_options & (ScopedItemOptions.ReadOnly | ScopedItemOptions.Constant)) != ScopedItemOptions.None)
            {
                SessionStateUnauthorizedAccessException e =
                    new SessionStateUnauthorizedAccessException(
                        Name,
                        SessionStateCategory.Variable,
                        "VariableNotWritable",
                        SessionStateStrings.VariableNotWritable);

                throw e;
            }

            // Now perform all ArgumentTransformations that are needed
            object transformedValue = value;

            if (_attributes != null && _attributes.Count > 0)
            {
                transformedValue = TransformValue(_attributes, value);

                // Next check to make sure the value is valid

                if (!IsValidValue(transformedValue))
                {
                    ValidationMetadataException e = new ValidationMetadataException(
                        "ValidateSetFailure",
                        null,
                        Metadata.InvalidValueFailure,
                        Name,
                        ((transformedValue != null) ? transformedValue.ToString() : "$null"));

                    throw e;
                }
            }

            if (transformedValue != null)
            {
                transformedValue = CopyMutableValues(transformedValue);
            }

            // Set the value before triggering any write breakpoints
            _value = transformedValue;

            DebuggerCheckVariableWrite();
        }
Ejemplo n.º 16
0
 internal void RemoveFunction(string name, bool force)
 {
     if (this.GetFunctions().ContainsKey(name))
     {
         FunctionInfo function = this.GetFunctions()[name];
         if (IsFunctionOptionSet(function, ScopedItemOptions.Constant) || (!force && IsFunctionOptionSet(function, ScopedItemOptions.ReadOnly)))
         {
             SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Function, "FunctionNotRemovable", SessionStateStrings.FunctionNotRemovable);
             throw exception;
         }
         if (IsFunctionOptionSet(function, ScopedItemOptions.AllScope))
         {
             this.GetAllScopeFunctions().Remove(name);
         }
     }
     this.GetFunctions().Remove(name);
 }
Ejemplo n.º 17
0
        /// <summary>
        /// Updates a function.
        /// </summary>
        /// <param name="newFunction">
        /// The script block that the function should represent.
        /// </param>
        /// <param name="force">
        /// If true, the script block will be applied even if the filter is ReadOnly.
        /// </param>
        /// <param name="options">
        /// Any options to set on the new function, null if none.
        /// </param>
        /// <param name="helpFile">
        /// The helpfile for this function.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="newFunction"/> is null.
        /// </exception>
        internal void Update(ScriptBlock newFunction, bool force, ScopedItemOptions options, string helpFile)
        {
            if (newFunction == null)
            {
                throw PSTraceSource.NewArgumentNullException("function");
            }

            if ((_options & ScopedItemOptions.Constant) != 0)
            {
                SessionStateUnauthorizedAccessException e =
                    new SessionStateUnauthorizedAccessException(
                        Name,
                        SessionStateCategory.Function,
                        "FunctionIsConstant",
                        SessionStateStrings.FunctionIsConstant);

                throw e;
            }

            if (!force && (_options & ScopedItemOptions.ReadOnly) != 0)
            {
                SessionStateUnauthorizedAccessException e =
                    new SessionStateUnauthorizedAccessException(
                        Name,
                        SessionStateCategory.Function,
                        "FunctionIsReadOnly",
                        SessionStateStrings.FunctionIsReadOnly);

                throw e;
            }

            _scriptBlock = newFunction;

            this.Module                  = newFunction.Module;
            _commandMetadata             = null;
            this._parameterSets          = null;
            this.ExternalCommandMetadata = null;

            if (options != ScopedItemOptions.Unspecified)
            {
                this.Options = options;
            }

            _helpFile = helpFile;
        }
Ejemplo n.º 18
0
        internal PSVariable NewVariable(PSVariable newVariable, bool force, SessionStateInternal sessionState)
        {
            PSVariable variable;
            bool       flag = this.TryGetVariable(newVariable.Name, this.ScopeOrigin, true, out variable);

            if (flag)
            {
                if (((variable == null) || variable.IsConstant) || (!force && variable.IsReadOnly))
                {
                    SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException(newVariable.Name, SessionStateCategory.Variable, "VariableNotWritable", SessionStateStrings.VariableNotWritable);
                    throw exception;
                }
                if (variable is LocalVariable)
                {
                    SessionStateUnauthorizedAccessException exception2 = new SessionStateUnauthorizedAccessException(newVariable.Name, SessionStateCategory.Variable, "VariableNotWritableRare", SessionStateStrings.VariableNotWritableRare);
                    throw exception2;
                }
                if (!object.ReferenceEquals(newVariable, variable))
                {
                    variable.WasRemoved = true;
                    variable            = newVariable;
                }
            }
            else
            {
                variable = newVariable;
            }
            if (!flag && (this._variables.Count > (this.VariableCapacity.FastValue - 1)))
            {
                SessionStateOverflowException exception3 = new SessionStateOverflowException(newVariable.Name, SessionStateCategory.Variable, "VariableOverflow", SessionStateStrings.VariableOverflow, new object[] { this.VariableCapacity.FastValue });
                throw exception3;
            }
            if (System.Management.Automation.ExecutionContext.HasEverUsedConstrainedLanguage)
            {
                System.Management.Automation.ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();
                if (((executionContextFromTLS != null) && (executionContextFromTLS.LanguageMode == PSLanguageMode.ConstrainedLanguage)) && ((variable.Options & ScopedItemOptions.AllScope) == ScopedItemOptions.AllScope))
                {
                    throw new PSNotSupportedException();
                }
            }
            this._variables[variable.Name] = variable;
            variable.SessionState          = sessionState;
            return(variable);
        }
Ejemplo n.º 19
0
 internal void SetOptions(ScopedItemOptions newOptions, bool force)
 {
     if (this.IsConstant || (!force && this.IsReadOnly))
     {
         SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException(this.name, SessionStateCategory.Variable, "VariableNotWritable", SessionStateStrings.VariableNotWritable);
         throw exception;
     }
     if ((newOptions & ScopedItemOptions.Constant) != ScopedItemOptions.None)
     {
         SessionStateUnauthorizedAccessException exception2 = new SessionStateUnauthorizedAccessException(this.name, SessionStateCategory.Variable, "VariableCannotBeMadeConstant", SessionStateStrings.VariableCannotBeMadeConstant);
         throw exception2;
     }
     if (this.IsAllScope && ((newOptions & ScopedItemOptions.AllScope) == ScopedItemOptions.None))
     {
         SessionStateUnauthorizedAccessException exception3 = new SessionStateUnauthorizedAccessException(this.name, SessionStateCategory.Variable, "VariableAllScopeOptionCannotBeRemoved", SessionStateStrings.VariableAllScopeOptionCannotBeRemoved);
         throw exception3;
     }
     this.options = newOptions;
 }
Ejemplo n.º 20
0
        /// <summary>
        /// Sets the options for the cmdlet and allows changes ReadOnly options only if force is specified.
        /// </summary>
        /// <param name="newOptions">
        /// The new options value.
        /// </param>
        /// <param name="force">
        /// If true the change to the options will happen even if the existing options are read-only.
        /// </param>
        internal void SetOptions(ScopedItemOptions newOptions, bool force)
        {
            // Check to see if the cmdlet is readonly, if so
            // throw an exception because the options cannot be changed.

            if ((_options & ScopedItemOptions.ReadOnly) != 0)
            {
                SessionStateUnauthorizedAccessException e =
                    new SessionStateUnauthorizedAccessException(
                        Name,
                        SessionStateCategory.Cmdlet,
                        "CmdletIsReadOnly",
                        SessionStateStrings.CmdletIsReadOnly);

                throw e;
            }

            _options = newOptions;
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Sets the new definition for the alias.
        /// </summary>
        ///
        /// <param name="definition">
        /// The new definition for the alias.
        /// </param>
        ///
        /// <param name="force">
        /// If true, the value will be set even if the alias is ReadOnly.
        /// </param>
        ///
        /// <exception cref="SessionStateUnauthorizedAccessException">
        /// If the alias is readonly or constant.
        /// </exception>
        ///
        internal void SetDefinition(string definition, bool force)
        {
            // Check to see if the variable is writable

            if ((_options & ScopedItemOptions.Constant) != 0 ||
                (!force && (_options & ScopedItemOptions.ReadOnly) != 0))
            {
                SessionStateUnauthorizedAccessException e =
                    new SessionStateUnauthorizedAccessException(
                        Name,
                        SessionStateCategory.Alias,
                        "AliasNotWritable",
                        SessionStateStrings.AliasNotWritable);

                throw e;
            }

            _definition = definition;
        } // SetDefinition
        static SessionStateUnauthorizedAccessException CreateError(
            PSVariable variable,
            string message,
            string errorId)
        {
            var ex = new SessionStateUnauthorizedAccessException(
                message,
                variable.Name,
                SessionStateCategory.Variable);

            var error = new ErrorRecord(
                new ParentContainsErrorRecordException(ex),
                errorId,
                ErrorCategory.WriteError,
                variable.Name);

            ex.ErrorRecord = error;
            ex.Source      = typeof(PSVariable).Namespace;

            return(ex);
        }
        static SessionStateUnauthorizedAccessException CreateError(
            PSVariable variable,
            string message,
            string errorId)
        {
            var ex = new SessionStateUnauthorizedAccessException(
                message,
                variable.Name,
                SessionStateCategory.Variable);

            var error = new ErrorRecord(
                new ParentContainsErrorRecordException(ex),
                errorId,
                ErrorCategory.WriteError,
                variable.Name);

            ex.ErrorRecord = error;
            ex.Source = typeof(PSVariable).Namespace;

            return ex;
        }
Ejemplo n.º 24
0
        internal void RemoveVariable(string name, bool force)
        {
            PSVariable variable = this.GetVariable(name);

            if (variable.IsConstant || (variable.IsReadOnly && !force))
            {
                SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Variable, "VariableNotRemovable", SessionStateStrings.VariableNotRemovable);
                throw exception;
            }
            if (variable is SessionStateCapacityVariable)
            {
                SessionStateUnauthorizedAccessException exception2 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Variable, "VariableNotRemovableSystem", SessionStateStrings.VariableNotRemovableSystem);
                throw exception2;
            }
            if (variable is LocalVariable)
            {
                SessionStateUnauthorizedAccessException exception3 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Variable, "VariableNotRemovableRare", SessionStateStrings.VariableNotRemovableRare);
                throw exception3;
            }
            this._variables.Remove(name);
            variable.WasRemoved = true;
        }
Ejemplo n.º 25
0
 internal void SetOptions(ScopedItemOptions newOptions, bool force)
 {
     if ((this.options & ScopedItemOptions.Constant) != ScopedItemOptions.None)
     {
         SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException(base.Name, SessionStateCategory.Alias, "AliasIsConstant", SessionStateStrings.AliasIsConstant);
         throw exception;
     }
     if (!force && ((this.options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None))
     {
         SessionStateUnauthorizedAccessException exception2 = new SessionStateUnauthorizedAccessException(base.Name, SessionStateCategory.Alias, "AliasIsReadOnly", SessionStateStrings.AliasIsReadOnly);
         throw exception2;
     }
     if ((newOptions & ScopedItemOptions.Constant) != ScopedItemOptions.None)
     {
         SessionStateUnauthorizedAccessException exception3 = new SessionStateUnauthorizedAccessException(base.Name, SessionStateCategory.Alias, "AliasCannotBeMadeConstant", SessionStateStrings.AliasCannotBeMadeConstant);
         throw exception3;
     }
     if (((newOptions & ScopedItemOptions.AllScope) == ScopedItemOptions.None) && ((this.options & ScopedItemOptions.AllScope) != ScopedItemOptions.None))
     {
         SessionStateUnauthorizedAccessException exception4 = new SessionStateUnauthorizedAccessException(base.Name, SessionStateCategory.Alias, "AliasAllScopeOptionCannotBeRemoved", SessionStateStrings.AliasAllScopeOptionCannotBeRemoved);
         throw exception4;
     }
     this.options = newOptions;
 }
Ejemplo n.º 26
0
 internal void SetOptions(ScopedItemOptions newOptions, bool force)
 {
     if ((this.options & ScopedItemOptions.Constant) != ScopedItemOptions.None)
     {
         SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException(base.Name, SessionStateCategory.Alias, "AliasIsConstant", SessionStateStrings.AliasIsConstant);
         throw exception;
     }
     if (!force && ((this.options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None))
     {
         SessionStateUnauthorizedAccessException exception2 = new SessionStateUnauthorizedAccessException(base.Name, SessionStateCategory.Alias, "AliasIsReadOnly", SessionStateStrings.AliasIsReadOnly);
         throw exception2;
     }
     if ((newOptions & ScopedItemOptions.Constant) != ScopedItemOptions.None)
     {
         SessionStateUnauthorizedAccessException exception3 = new SessionStateUnauthorizedAccessException(base.Name, SessionStateCategory.Alias, "AliasCannotBeMadeConstant", SessionStateStrings.AliasCannotBeMadeConstant);
         throw exception3;
     }
     if (((newOptions & ScopedItemOptions.AllScope) == ScopedItemOptions.None) && ((this.options & ScopedItemOptions.AllScope) != ScopedItemOptions.None))
     {
         SessionStateUnauthorizedAccessException exception4 = new SessionStateUnauthorizedAccessException(base.Name, SessionStateCategory.Alias, "AliasAllScopeOptionCannotBeRemoved", SessionStateStrings.AliasAllScopeOptionCannotBeRemoved);
         throw exception4;
     }
     this.options = newOptions;
 }
Ejemplo n.º 27
0
 internal void SetScriptBlock(ScriptBlock function, bool force)
 {
     if (function == null)
     {
         throw FunctionInfo.tracer.NewArgumentNullException(nameof(function));
     }
     if ((this.options & ScopedItemOptions.Constant) != ScopedItemOptions.None)
     {
         SessionStateUnauthorizedAccessException unauthorizedAccessException = new SessionStateUnauthorizedAccessException(this.Name, SessionStateCategory.Function, "FunctionIsConstant");
         FunctionInfo.tracer.TraceException((Exception)unauthorizedAccessException);
         throw unauthorizedAccessException;
     }
     if (!force && (this.options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None)
     {
         SessionStateUnauthorizedAccessException unauthorizedAccessException = new SessionStateUnauthorizedAccessException(this.Name, SessionStateCategory.Function, "FunctionIsReadOnly");
         FunctionInfo.tracer.TraceException((Exception)unauthorizedAccessException);
         throw unauthorizedAccessException;
     }
     this._function = function;
     this.SetModule(function.Module);
     this.commandMetadata          = (CommandMetadata)null;
     this.parameterSets            = (ReadOnlyCollection <CommandParameterSetInfo>)null;
     this._externalCommandMetadata = (CommandMetadata)null;
 }
Ejemplo n.º 28
0
        internal PSVariable SetVariable(string name, object value, bool asValue, bool force, SessionStateInternal sessionState, CommandOrigin origin = CommandOrigin.Internal, bool fastPath = false)
        {
            PSVariable variable;
            PSVariable variable2 = value as PSVariable;

            if (fastPath)
            {
                if (this.Parent != null)
                {
                    throw new NotImplementedException("fastPath");
                }
                variable = new PSVariable(name, variable2.Value, variable2.Options, variable2.Attributes)
                {
                    Description = variable2.Description
                };
                this.GetPrivateVariables()[name] = variable;
                return(variable);
            }
            bool flag = this.TryGetVariable(name, origin, true, out variable);

            if (!asValue && (variable2 != null))
            {
                if (flag)
                {
                    if (((variable == null) || variable.IsConstant) || (!force && variable.IsReadOnly))
                    {
                        SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Variable, "VariableNotWritable", SessionStateStrings.VariableNotWritable);
                        throw exception;
                    }
                    if ((variable is LocalVariable) && (variable2.Attributes.Any <Attribute>() || (variable2.Options != variable.Options)))
                    {
                        SessionStateUnauthorizedAccessException exception2 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Variable, "VariableNotWritableRare", SessionStateStrings.VariableNotWritableRare);
                        throw exception2;
                    }
                    if (variable.IsReadOnly && force)
                    {
                        this._variables.Remove(name);
                        flag     = false;
                        variable = new PSVariable(name, variable2.Value, variable2.Options, variable2.Attributes)
                        {
                            Description = variable2.Description
                        };
                    }
                    else
                    {
                        variable.Attributes.Clear();
                        variable.Value       = variable2.Value;
                        variable.Options     = variable2.Options;
                        variable.Description = variable2.Description;
                        foreach (Attribute attribute in variable2.Attributes)
                        {
                            variable.Attributes.Add(attribute);
                        }
                    }
                }
                else
                {
                    variable = variable2;
                }
            }
            else if (variable != null)
            {
                variable.Value = value;
            }
            else
            {
                variable = (this.LocalsTuple != null) ? (this.LocalsTuple.TrySetVariable(name, value)) ?? new PSVariable(name, value) : new PSVariable(name, value);
            }
            if (!flag && (this._variables.Count > (this.VariableCapacity.FastValue - 1)))
            {
                SessionStateOverflowException exception3 = new SessionStateOverflowException(name, SessionStateCategory.Variable, "VariableOverflow", SessionStateStrings.VariableOverflow, new object[] { this.VariableCapacity.FastValue });
                throw exception3;
            }
            if (System.Management.Automation.ExecutionContext.HasEverUsedConstrainedLanguage)
            {
                System.Management.Automation.ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();
                if (((executionContextFromTLS != null) && (executionContextFromTLS.LanguageMode == PSLanguageMode.ConstrainedLanguage)) && ((variable.Options & ScopedItemOptions.AllScope) == ScopedItemOptions.AllScope))
                {
                    /* TODO: Review how to  get around this: */ /* throw new PSNotSupportedException(); */
                }
            }
            this._variables[name] = variable;
            variable.SessionState = sessionState;
            return(variable);
        }
Ejemplo n.º 29
0
        } // SetFunction

        /// <summary>
        /// Removes a function from the function table.
        /// </summary>
        ///
        /// <param name="name">
        /// The name of the function to remove.
        /// </param>
        ///
        /// <param name="force">
        /// If true, the function is removed even if it is ReadOnly.
        /// </param>
        /// 
        /// <exception cref="SessionStateUnauthorizedAccessException">
        /// If the function is constant.
        /// </exception> 
        /// 
        internal void RemoveFunction(string name, bool force)
        {
            Diagnostics.Assert(
                name != null,
                "The caller should verify the name");

            var functionInfos = GetFunctions();
            FunctionInfo function;
            if (functionInfos.TryGetValue(name, out function))
            {
                if (IsFunctionOptionSet(function, ScopedItemOptions.Constant) ||
                    (!force && IsFunctionOptionSet(function, ScopedItemOptions.ReadOnly)))
                {
                    SessionStateUnauthorizedAccessException e =
                        new SessionStateUnauthorizedAccessException(
                                name,
                                SessionStateCategory.Function,
                                "FunctionNotRemovable",
                                SessionStateStrings.FunctionNotRemovable);

                    throw e;
                }

                if (IsFunctionOptionSet(function, ScopedItemOptions.AllScope))
                {
                    GetAllScopeFunctions().Remove(name);
                }
            }
            functionInfos.Remove(name);
        } // RemoveFunction
Ejemplo n.º 30
0
        } // SetVariable

        /// <summary>
        /// Sets a variable to the given value.
        /// </summary>
        ///
        /// <param name="newVariable">
        /// The new variable to create.
        /// </param>
        /// 
        /// <param name="force">
        /// If true, the variable will be set even if it is readonly.
        /// </param>
        /// 
        /// <param name="sessionState">
        /// Which SessionState this variable belongs to.
        /// </param>
        /// 
        /// <returns>
        /// The PSVariable representing the variable that was set.
        /// </returns>
        ///
        /// <exception cref="SessionStateUnauthorizedAccessException">
        /// If the variable is read-only or constant.
        /// </exception> 
        /// 
        /// <exception cref="SessionStateOverflowException">
        /// If the maximum number of variables has been reached for this scope.
        /// </exception>
        /// 
        internal PSVariable NewVariable(PSVariable newVariable, bool force, SessionStateInternal sessionState)
        {
            PSVariable variable;
            bool varExists = TryGetVariable(newVariable.Name, ScopeOrigin, true, out variable);

            if (varExists)
            {
                // First check the variable to ensure that it
                // is not constant or readonly

                if (variable == null || variable.IsConstant || (!force && variable.IsReadOnly))
                {
                    SessionStateUnauthorizedAccessException e =
                        new SessionStateUnauthorizedAccessException(
                                newVariable.Name,
                                SessionStateCategory.Variable,
                                "VariableNotWritable",
                                SessionStateStrings.VariableNotWritable);

                    throw e;
                }

                if (variable is LocalVariable)
                {
                    SessionStateUnauthorizedAccessException e =
                        new SessionStateUnauthorizedAccessException(
                                newVariable.Name,
                                SessionStateCategory.Variable,
                                "VariableNotWritableRare",
                                SessionStateStrings.VariableNotWritableRare);

                    throw e;
                }

                // If the new and old variable are the same then don't bother
                // doing the assignment and marking as "removed".
                // This can happen when a module variable is imported twice.
                if (!ReferenceEquals(newVariable, variable))
                {
                    // Mark the old variable as removed...
                    variable.WasRemoved = true;
                    variable = newVariable;
                }
            }
            else
            {
                // Since the variable doesn't exist, use the new Variable
                // object

                variable = newVariable;
            }

            // Now check to make sure we don't exceed the max variable count
            // if this is a new variable.

            if (!varExists && _variables.Count > VariableCapacity.FastValue - 1)
            {
                SessionStateOverflowException e =
                    new SessionStateOverflowException(
                            newVariable.Name,
                            SessionStateCategory.Variable,
                            "VariableOverflow",
                                SessionStateStrings.VariableOverflow,
                            VariableCapacity.FastValue);

                throw e;
            }

            // Don't let people set AllScope variables in ConstrainedLanguage,
            // as they can be used to interfere with the session state of
            // trusted commands.
            if (ExecutionContext.HasEverUsedConstrainedLanguage)
            {
                var context = System.Management.Automation.Runspaces.LocalPipeline.GetExecutionContextFromTLS();

                if ((context != null) &&
                    (context.LanguageMode == PSLanguageMode.ConstrainedLanguage) &&
                    ((variable.Options & ScopedItemOptions.AllScope) == ScopedItemOptions.AllScope))
                {
                    throw new PSNotSupportedException();
                }
            }

            _variables[variable.Name] = variable;
            variable.SessionState = sessionState;
            return variable;
        } // NewVariable
Ejemplo n.º 31
0
 internal void RemoveFunction(string name, bool force)
 {
     if (this.GetFunctions().ContainsKey(name))
     {
         FunctionInfo function = this.GetFunctions()[name];
         if (IsFunctionOptionSet(function, ScopedItemOptions.Constant) || (!force && IsFunctionOptionSet(function, ScopedItemOptions.ReadOnly)))
         {
             SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Function, "FunctionNotRemovable", SessionStateStrings.FunctionNotRemovable);
             throw exception;
         }
         if (IsFunctionOptionSet(function, ScopedItemOptions.AllScope))
         {
             this.GetAllScopeFunctions().Remove(name);
         }
     }
     this.GetFunctions().Remove(name);
 }
Ejemplo n.º 32
0
        /// <summary>
        /// Updates a function.
        /// </summary>
        /// 
        /// <param name="newFunction">
        /// The script block that the function should represent.
        /// </param>
        /// 
        /// <param name="force">
        /// If true, the script block will be applied even if the filter is ReadOnly.
        /// </param>
        /// 
        /// <param name="options">
        /// Any options to set on the new function, null if none.
        /// </param>
        /// 
        /// <param name="helpFile">
        /// The helpfile for this function.
        /// </param>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="newFunction"/> is null.
        /// </exception>
        /// 
        internal void Update(ScriptBlock newFunction, bool force, ScopedItemOptions options, string helpFile)
        {
            if (newFunction == null)
            {
                throw PSTraceSource.NewArgumentNullException("function");
            }

            if ((_options & ScopedItemOptions.Constant) != 0)
            {
                SessionStateUnauthorizedAccessException e =
                    new SessionStateUnauthorizedAccessException(
                            Name,
                            SessionStateCategory.Function,
                            "FunctionIsConstant",
                            SessionStateStrings.FunctionIsConstant);

                throw e;
            }

            if (!force && (_options & ScopedItemOptions.ReadOnly) != 0)
            {
                SessionStateUnauthorizedAccessException e =
                    new SessionStateUnauthorizedAccessException(
                            Name,
                            SessionStateCategory.Function,
                            "FunctionIsReadOnly",
                            SessionStateStrings.FunctionIsReadOnly);

                throw e;
            }

            _scriptBlock = newFunction;

            this.Module = newFunction.Module;
            _commandMetadata = null;
            this._parameterSets = null;
            this.ExternalCommandMetadata = null;

            if (options != ScopedItemOptions.Unspecified)
            {
                this.Options = options;
            }

            _helpFile = helpFile;
        }
Ejemplo n.º 33
0
        } // NewScope

        /// <summary>
        /// Removes the current scope from the scope tree and
        /// changes the current scope to the parent scope.
        /// </summary>
        /// <param name="scope">
        /// The scope to cleanup and remove.
        /// </param>
        /// <exception cref="SessionStateUnauthorizedAccessException">
        /// The global scope cannot be removed.
        /// </exception>
        internal void RemoveScope(SessionStateScope scope)
        {
            Diagnostics.Assert(
                _currentScope != null,
                "The currentScope should always be set.");

            if (scope == GlobalScope)
            {
                SessionStateUnauthorizedAccessException e =
                    new SessionStateUnauthorizedAccessException(
                        StringLiterals.Global,
                        SessionStateCategory.Scope,
                        "GlobalScopeCannotRemove",
                        SessionStateStrings.GlobalScopeCannotRemove);

                throw e;
            }

            // Give the provider a chance to cleanup the drive data associated
            // with drives in this scope

            foreach (PSDriveInfo drive in scope.Drives)
            {
                if (drive == null)
                {
                    continue;
                }

                CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);

                // Call CanRemoveDrive to give the provider a chance to cleanup
                // but ignore the return value and exceptions

                try
                {
                    CanRemoveDrive(drive, context);
                }
                catch (LoopFlowException)
                {
                    throw;
                }
                catch (PipelineStoppedException)
                {
                    throw;
                }
                catch (ActionPreferenceStopException)
                {
                    throw;
                }
                catch (Exception) // Catch-all OK, 3rd party callout.
                {
                    // Ignore all exceptions from the provider as we are
                    // going to force the removal anyway
                }
            } // foreach drive

            scope.RemoveAllDrives();

            // If the scope being removed is the current scope,
            // then it must be removed from the tree.

            if (scope == _currentScope && _currentScope.Parent != null)
            {
                _currentScope = _currentScope.Parent;
            }
            scope.Parent = null;
        } // RemoveScope
Ejemplo n.º 34
0
        } // GetValueOfItem        

        /// <summary>
        /// Determines if the item can be renamed. Derived classes that need
        /// to perform a check should override this method.
        /// </summary>
        /// 
        /// <param name="item">
        /// The item to verify if it can be renamed.
        /// </param>
        /// 
        /// <returns>
        /// true if the item can be renamed or false otherwise.
        /// </returns>
        /// 
        internal override bool CanRenameItem(object item)
        {
            bool result = false;

            PSVariable variable = item as PSVariable;
            if (variable != null)
            {
                if ((variable.Options & ScopedItemOptions.Constant) != 0 ||
                    ((variable.Options & ScopedItemOptions.ReadOnly) != 0 && !Force))
                {
                    SessionStateUnauthorizedAccessException e =
                        new SessionStateUnauthorizedAccessException(
                            variable.Name,
                            SessionStateCategory.Variable,
                            "CannotRenameVariable",
                            SessionStateStrings.CannotRenameVariable);

                    throw e;
                }

                result = true;
            }

            return result;
        }
Ejemplo n.º 35
0
 internal void Update(System.Management.Automation.ScriptBlock newFunction, bool force, ScopedItemOptions options, string helpFile)
 {
     if (newFunction == null)
     {
         throw PSTraceSource.NewArgumentNullException("function");
     }
     if ((this._options & ScopedItemOptions.Constant) != ScopedItemOptions.None)
     {
         SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException(base.Name, SessionStateCategory.Function, "FunctionIsConstant", SessionStateStrings.FunctionIsConstant);
         throw exception;
     }
     if (!force && ((this._options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None))
     {
         SessionStateUnauthorizedAccessException exception2 = new SessionStateUnauthorizedAccessException(base.Name, SessionStateCategory.Function, "FunctionIsReadOnly", SessionStateStrings.FunctionIsReadOnly);
         throw exception2;
     }
     this._scriptBlock = newFunction;
     base.SetModule(newFunction.Module);
     this._commandMetadata = null;
     base._parameterSets = null;
     base._externalCommandMetadata = null;
     if (options != ScopedItemOptions.Unspecified)
     {
         this.Options = options;
     }
     this._helpFile = helpFile;
 }
Ejemplo n.º 36
0
 internal AliasInfo SetAliasItem(AliasInfo aliasToSet, bool force, CommandOrigin origin = CommandOrigin.Internal)
 {
     if (!this.GetAliases().ContainsKey(aliasToSet.Name))
     {
         if (this.GetAliases().Count > (this.AliasCapacity.FastValue - 1))
         {
             SessionStateOverflowException exception = new SessionStateOverflowException(aliasToSet.Name, SessionStateCategory.Alias, "AliasOverflow", SessionStateStrings.AliasOverflow, new object[] { this.AliasCapacity.FastValue });
             throw exception;
         }
         this.GetAliases()[aliasToSet.Name] = aliasToSet;
     }
     else
     {
         AliasInfo valueToCheck = this.GetAliases()[aliasToSet.Name];
         SessionState.ThrowIfNotVisible(origin, valueToCheck);
         if (((valueToCheck.Options & ScopedItemOptions.Constant) != ScopedItemOptions.None) || (((valueToCheck.Options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None) && !force))
         {
             SessionStateUnauthorizedAccessException exception2 = new SessionStateUnauthorizedAccessException(aliasToSet.Name, SessionStateCategory.Alias, "AliasNotWritable", SessionStateStrings.AliasNotWritable);
             throw exception2;
         }
         if (((aliasToSet.Options & ScopedItemOptions.AllScope) == ScopedItemOptions.None) && ((valueToCheck.Options & ScopedItemOptions.AllScope) != ScopedItemOptions.None))
         {
             SessionStateUnauthorizedAccessException exception3 = new SessionStateUnauthorizedAccessException(aliasToSet.Name, SessionStateCategory.Alias, "AliasAllScopeOptionCannotBeRemoved", SessionStateStrings.AliasAllScopeOptionCannotBeRemoved);
             throw exception3;
         }
         this.RemoveAliasFromCache(valueToCheck.Name, valueToCheck.Definition);
         this.GetAliases()[aliasToSet.Name] = aliasToSet;
     }
     this.AddAliasToCache(aliasToSet.Name, aliasToSet.Definition);
     return this.GetAliases()[aliasToSet.Name];
 }
Ejemplo n.º 37
0
 internal void RemoveAlias(string name, bool force)
 {
     if (this.GetAliases().ContainsKey(name))
     {
         AliasInfo info = this.GetAliases()[name];
         if (((info.Options & ScopedItemOptions.Constant) != ScopedItemOptions.None) || (!force && ((info.Options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None)))
         {
             SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Alias, "AliasNotRemovable", SessionStateStrings.AliasNotRemovable);
             throw exception;
         }
         this.RemoveAliasFromCache(info.Name, info.Definition);
     }
     this.GetAliases().Remove(name);
 }
Ejemplo n.º 38
0
 internal FunctionInfo SetFunction(string name, ScriptBlock function, FunctionInfo originalFunction, ScopedItemOptions options, bool force, CommandOrigin origin, System.Management.Automation.ExecutionContext context, string helpFile, Func<string, ScriptBlock, FunctionInfo, ScopedItemOptions, System.Management.Automation.ExecutionContext, string, FunctionInfo> functionFactory)
 {
     if (!this.GetFunctions().ContainsKey(name))
     {
         if (this.GetFunctions().Count > (this.FunctionCapacity.FastValue - 1))
         {
             SessionStateOverflowException exception = new SessionStateOverflowException(name, SessionStateCategory.Function, "FunctionOverflow", SessionStateStrings.FunctionOverflow, new object[] { this.FunctionCapacity.FastValue });
             throw exception;
         }
         FunctionInfo info = functionFactory(name, function, originalFunction, options, context, helpFile);
         this.GetFunctions()[name] = info;
         if (IsFunctionOptionSet(info, ScopedItemOptions.AllScope))
         {
             this.GetAllScopeFunctions()[name] = info;
         }
     }
     else
     {
         FunctionInfo valueToCheck = this.GetFunctions()[name];
         SessionState.ThrowIfNotVisible(origin, valueToCheck);
         if (IsFunctionOptionSet(valueToCheck, ScopedItemOptions.Constant) || (!force && IsFunctionOptionSet(valueToCheck, ScopedItemOptions.ReadOnly)))
         {
             SessionStateUnauthorizedAccessException exception2 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Function, "FunctionNotWritable", SessionStateStrings.FunctionNotWritable);
             throw exception2;
         }
         if ((options & ScopedItemOptions.Constant) != ScopedItemOptions.None)
         {
             SessionStateUnauthorizedAccessException exception3 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Function, "FunctionCannotBeMadeConstant", SessionStateStrings.FunctionCannotBeMadeConstant);
             throw exception3;
         }
         if (((options & ScopedItemOptions.AllScope) == ScopedItemOptions.None) && IsFunctionOptionSet(valueToCheck, ScopedItemOptions.AllScope))
         {
             SessionStateUnauthorizedAccessException exception4 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Function, "FunctionAllScopeOptionCannotBeRemoved", SessionStateStrings.FunctionAllScopeOptionCannotBeRemoved);
             throw exception4;
         }
         FunctionInfo info3 = valueToCheck;
         FunctionInfo newFunction = null;
         if (info3 != null)
         {
             newFunction = functionFactory(name, function, originalFunction, options, context, helpFile);
             if (!info3.GetType().Equals(newFunction.GetType()) || (((info3.Options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None) && force))
             {
                 this.GetFunctions()[name] = newFunction;
             }
             else
             {
                 bool flag2 = force || ((options & ScopedItemOptions.ReadOnly) == ScopedItemOptions.None);
                 info3.Update(newFunction, flag2, options, helpFile);
             }
         }
     }
     return this.GetFunctions()[name];
 }
Ejemplo n.º 39
0
 internal void RemoveVariable(string name, bool force)
 {
     PSVariable variable = this.GetVariable(name);
     if (variable.IsConstant || (variable.IsReadOnly && !force))
     {
         SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Variable, "VariableNotRemovable", SessionStateStrings.VariableNotRemovable);
         throw exception;
     }
     if (variable is SessionStateCapacityVariable)
     {
         SessionStateUnauthorizedAccessException exception2 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Variable, "VariableNotRemovableSystem", SessionStateStrings.VariableNotRemovableSystem);
         throw exception2;
     }
     if (variable is LocalVariable)
     {
         SessionStateUnauthorizedAccessException exception3 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Variable, "VariableNotRemovableRare", SessionStateStrings.VariableNotRemovableRare);
         throw exception3;
     }
     this._variables.Remove(name);
     variable.WasRemoved = true;
 }
Ejemplo n.º 40
0
 internal void SetOptions(ScopedItemOptions newOptions, bool force)
 {
     if ((this.options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None)
     {
         SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException(base.Name, SessionStateCategory.Cmdlet, "CmdletIsReadOnly", SessionStateStrings.CmdletIsReadOnly);
         throw exception;
     }
     this.options = newOptions;
 }
Ejemplo n.º 41
0
 internal AliasInfo SetAliasValue(string name, string value, ScopedItemOptions options, System.Management.Automation.ExecutionContext context, bool force, CommandOrigin origin)
 {
     if (!this.GetAliases().ContainsKey(name))
     {
         if (this.GetAliases().Count > (this.AliasCapacity.FastValue - 1))
         {
             SessionStateOverflowException exception = new SessionStateOverflowException(name, SessionStateCategory.Alias, "AliasOverflow", SessionStateStrings.AliasOverflow, new object[] { this.AliasCapacity.FastValue });
             throw exception;
         }
         AliasInfo info = new AliasInfo(name, value, context, options);
         this.GetAliases()[name] = info;
     }
     else
     {
         AliasInfo valueToCheck = this.GetAliases()[name];
         if (((valueToCheck.Options & ScopedItemOptions.Constant) != ScopedItemOptions.None) || (!force && ((valueToCheck.Options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None)))
         {
             SessionStateUnauthorizedAccessException exception2 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Alias, "AliasNotWritable", SessionStateStrings.AliasNotWritable);
             throw exception2;
         }
         if ((options & ScopedItemOptions.Constant) != ScopedItemOptions.None)
         {
             SessionStateUnauthorizedAccessException exception3 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Alias, "AliasCannotBeMadeConstant", SessionStateStrings.AliasCannotBeMadeConstant);
             throw exception3;
         }
         if (((options & ScopedItemOptions.AllScope) == ScopedItemOptions.None) && ((valueToCheck.Options & ScopedItemOptions.AllScope) != ScopedItemOptions.None))
         {
             SessionStateUnauthorizedAccessException exception4 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Alias, "AliasAllScopeOptionCannotBeRemoved", SessionStateStrings.AliasAllScopeOptionCannotBeRemoved);
             throw exception4;
         }
         SessionState.ThrowIfNotVisible(origin, valueToCheck);
         this.RemoveAliasFromCache(valueToCheck.Name, valueToCheck.Definition);
         if (force)
         {
             this.GetAliases().Remove(name);
             valueToCheck = new AliasInfo(name, value, context, options);
             this.GetAliases()[name] = valueToCheck;
         }
         else
         {
             valueToCheck.Options = options;
             valueToCheck.SetDefinition(value, false);
         }
     }
     this.AddAliasToCache(name, value);
     return this.GetAliases()[name];
 }
Ejemplo n.º 42
0
        internal static object SetVariableValue(VariablePath variablePath, object value, ExecutionContext executionContext, AttributeBaseAst[] attributeAsts)
        {
            SessionStateInternal sessionState = executionContext.EngineSessionState;
            CommandOrigin        origin       = sessionState.CurrentScope.ScopeOrigin;

            if (!variablePath.IsVariable)
            {
                sessionState.SetVariable(variablePath, value, true, origin);
                return(value);
            }

            // Variable assignment is traced only if trace level 2 is specified.
            if (executionContext.PSDebugTraceLevel > 1)
            {
                executionContext.Debugger.TraceVariableSet(variablePath.UnqualifiedPath, value);
            }

            if (variablePath.IsUnscopedVariable)
            {
                variablePath = variablePath.CloneAndSetLocal();
            }

            SessionStateScope scope;
            PSVariable        var = sessionState.GetVariableItem(variablePath, out scope, origin);

            if (var == null)
            {
                var attributes = attributeAsts == null
                                     ? new Collection <Attribute>()
                                     : GetAttributeCollection(attributeAsts);
                var = new PSVariable(variablePath.UnqualifiedPath, value, ScopedItemOptions.None, attributes);

                sessionState.SetVariable(variablePath, var, false, origin);

                if (executionContext._debuggingMode > 0)
                {
                    executionContext.Debugger.CheckVariableWrite(variablePath.UnqualifiedPath);
                }
            }
            else if (attributeAsts != null)
            {
                // Use bytewise operation directly instead of 'var.IsReadOnly || var.IsConstant' on
                // a hot path (setting variable with type constraint) to get better performance.
                if ((var.Options & (ScopedItemOptions.ReadOnly | ScopedItemOptions.Constant)) != ScopedItemOptions.None)
                {
                    SessionStateUnauthorizedAccessException e =
                        new SessionStateUnauthorizedAccessException(
                            var.Name,
                            SessionStateCategory.Variable,
                            "VariableNotWritable",
                            SessionStateStrings.VariableNotWritable);
                    throw e;
                }

                var attributes = GetAttributeCollection(attributeAsts);
                value = PSVariable.TransformValue(attributes, value);
                if (!PSVariable.IsValidValue(attributes, value))
                {
                    ValidationMetadataException e = new ValidationMetadataException(
                        "ValidateSetFailure",
                        null,
                        Metadata.InvalidValueFailure,
                        var.Name,
                        ((value != null) ? value.ToString() : "$null"));

                    throw e;
                }
                var.SetValueRaw(value, true);
                // Don't update the PSVariable's attributes until we successfully set the value
                var.Attributes.Clear();
                var.AddParameterAttributesNoChecks(attributes);

                if (executionContext._debuggingMode > 0)
                {
                    executionContext.Debugger.CheckVariableWrite(variablePath.UnqualifiedPath);
                }
            }
            else
            {
                // The setter will handle checking for variable writes.
                var.Value = value;
            }

            return(value);
        }
Ejemplo n.º 43
0
 internal PSVariable SetVariable(string name, object value, bool asValue, bool force, SessionStateInternal sessionState, CommandOrigin origin = CommandOrigin.Internal, bool fastPath = false)
 {
     PSVariable variable;
     PSVariable variable2 = value as PSVariable;
     if (fastPath)
     {
         if (this.Parent != null)
         {
             throw new NotImplementedException("fastPath");
         }
         variable = new PSVariable(name, variable2.Value, variable2.Options, variable2.Attributes) {
             Description = variable2.Description
         };
         this.GetPrivateVariables()[name] = variable;
         return variable;
     }
     bool flag = this.TryGetVariable(name, origin, true, out variable);
     if (!asValue && (variable2 != null))
     {
         if (flag)
         {
             if (((variable == null) || variable.IsConstant) || (!force && variable.IsReadOnly))
             {
                 SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Variable, "VariableNotWritable", SessionStateStrings.VariableNotWritable);
                 throw exception;
             }
             if ((variable is LocalVariable) && (variable2.Attributes.Any<Attribute>() || (variable2.Options != variable.Options)))
             {
                 SessionStateUnauthorizedAccessException exception2 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Variable, "VariableNotWritableRare", SessionStateStrings.VariableNotWritableRare);
                 throw exception2;
             }
             if (variable.IsReadOnly && force)
             {
                 this._variables.Remove(name);
                 flag = false;
                 variable = new PSVariable(name, variable2.Value, variable2.Options, variable2.Attributes) {
                     Description = variable2.Description
                 };
             }
             else
             {
                 variable.Attributes.Clear();
                 variable.Value = variable2.Value;
                 variable.Options = variable2.Options;
                 variable.Description = variable2.Description;
                 foreach (Attribute attribute in variable2.Attributes)
                 {
                     variable.Attributes.Add(attribute);
                 }
             }
         }
         else
         {
             variable = variable2;
         }
     }
     else if (variable != null)
     {
         variable.Value = value;
     }
     else
     {
         variable = (this.LocalsTuple != null) ? (this.LocalsTuple.TrySetVariable(name, value)) ?? new PSVariable(name, value) : new PSVariable(name, value);
     }
     if (!flag && (this._variables.Count > (this.VariableCapacity.FastValue - 1)))
     {
         SessionStateOverflowException exception3 = new SessionStateOverflowException(name, SessionStateCategory.Variable, "VariableOverflow", SessionStateStrings.VariableOverflow, new object[] { this.VariableCapacity.FastValue });
         throw exception3;
     }
     if (System.Management.Automation.ExecutionContext.HasEverUsedConstrainedLanguage)
     {
         System.Management.Automation.ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();
         if (((executionContextFromTLS != null) && (executionContextFromTLS.LanguageMode == PSLanguageMode.ConstrainedLanguage)) && ((variable.Options & ScopedItemOptions.AllScope) == ScopedItemOptions.AllScope))
         {
             /* TODO: Review how to  get around this: */ /* throw new PSNotSupportedException(); */
         }
     }
     this._variables[name] = variable;
     variable.SessionState = sessionState;
     return variable;
 }
Ejemplo n.º 44
0
        internal void SetOptions(ScopedItemOptions newOptions, bool force)
        {
            // Check to see if the variable is constant or readonly, if so
            // throw an exception because the options cannot be changed.

            if (IsConstant || (!force && IsReadOnly))
            {
                SessionStateUnauthorizedAccessException e =
                    new SessionStateUnauthorizedAccessException(
                            Name,
                            SessionStateCategory.Variable,
                            "VariableNotWritable",
                            SessionStateStrings.VariableNotWritable);

                throw e;
            }

            // Now check to see if the caller is trying to set
            // the options to constant. This is only allowed at
            // variable creation

            if ((newOptions & ScopedItemOptions.Constant) != 0)
            {
                // user is trying to set the variable to constant after
                // creating the variable. Do not allow this (as per spec).

                SessionStateUnauthorizedAccessException e =
                    new SessionStateUnauthorizedAccessException(
                            Name,
                            SessionStateCategory.Variable,
                            "VariableCannotBeMadeConstant",
                            SessionStateStrings.VariableCannotBeMadeConstant);

                throw e;
            }

            // Now check to see if the caller is trying to 
            // remove the AllScope option. This is not allowed
            // at any time.

            if (IsAllScope && ((newOptions & ScopedItemOptions.AllScope) == 0))
            {
                // user is trying to remove the AllScope option from the variable. 
                // Do not allow this (as per spec).

                SessionStateUnauthorizedAccessException e =
                    new SessionStateUnauthorizedAccessException(
                            Name,
                            SessionStateCategory.Variable,
                            "VariableAllScopeOptionCannotBeRemoved",
                            SessionStateStrings.VariableAllScopeOptionCannotBeRemoved);

                throw e;
            }

            _options = newOptions;
        }
Ejemplo n.º 45
0
 internal void SetOptions(ScopedItemOptions newOptions, bool force)
 {
     if (this.IsConstant || (!force && this.IsReadOnly))
     {
         SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException(this.name, SessionStateCategory.Variable, "VariableNotWritable", SessionStateStrings.VariableNotWritable);
         throw exception;
     }
     if ((newOptions & ScopedItemOptions.Constant) != ScopedItemOptions.None)
     {
         SessionStateUnauthorizedAccessException exception2 = new SessionStateUnauthorizedAccessException(this.name, SessionStateCategory.Variable, "VariableCannotBeMadeConstant", SessionStateStrings.VariableCannotBeMadeConstant);
         throw exception2;
     }
     if (this.IsAllScope && ((newOptions & ScopedItemOptions.AllScope) == ScopedItemOptions.None))
     {
         SessionStateUnauthorizedAccessException exception3 = new SessionStateUnauthorizedAccessException(this.name, SessionStateCategory.Variable, "VariableAllScopeOptionCannotBeRemoved", SessionStateStrings.VariableAllScopeOptionCannotBeRemoved);
         throw exception3;
     }
     this.options = newOptions;
 }
Ejemplo n.º 46
0
        /// <summary>
        /// Verifies the constraints and attributes before setting the value
        /// </summary>
        /// 
        /// <param name="value">
        /// The value to be set.
        /// </param>
        /// 
        /// <exception cref="SessionStateUnauthorizedAccessException">
        /// If the variable is read-only or constant.
        /// </exception>
        /// 
        /// <exception cref="ValidationMetadataException">
        /// If the validation metadata throws an exception or the value doesn't
        /// pass the validation metadata.
        /// </exception>
        /// 
        private void SetValue(object value)
        {
            // Check to see if the variable is writable

            if ((_options & (ScopedItemOptions.ReadOnly | ScopedItemOptions.Constant)) != ScopedItemOptions.None)
            {
                SessionStateUnauthorizedAccessException e =
                    new SessionStateUnauthorizedAccessException(
                            Name,
                            SessionStateCategory.Variable,
                            "VariableNotWritable",
                            SessionStateStrings.VariableNotWritable);

                throw e;
            }

            // Now perform all ArgumentTransformations that are needed
            object transformedValue = value;
            if (_attributes != null && _attributes.Count > 0)
            {
                transformedValue = TransformValue(_attributes, value);

                // Next check to make sure the value is valid

                if (!IsValidValue(transformedValue))
                {
                    ValidationMetadataException e = new ValidationMetadataException(
                        "ValidateSetFailure",
                        null,
                        Metadata.InvalidValueFailure,
                        Name,
                        ((transformedValue != null) ? transformedValue.ToString() : "$null"));

                    throw e;
                }
            }

            if (transformedValue != null)
            {
                transformedValue = CopyMutableValues(transformedValue);
            }

            // Set the value before triggering any write breakpoints
            _value = transformedValue;

            DebuggerCheckVariableWrite();
        }
Ejemplo n.º 47
0
        } // NewScope

        /// <summary>
        /// Removes the current scope from the scope tree and
        /// changes the current scope to the parent scope.
        /// </summary>
        /// 
        /// <param name="scope">
        /// The scope to cleanup and remove.
        /// </param>
        /// 
        /// <exception cref="SessionStateUnauthorizedAccessException">
        /// The global scope cannot be removed.
        /// </exception>
        /// 
        internal void RemoveScope(SessionStateScope scope)
        {
            Diagnostics.Assert(
                _currentScope != null,
                "The currentScope should always be set.");

            if (scope == GlobalScope)
            {
                SessionStateUnauthorizedAccessException e =
                    new SessionStateUnauthorizedAccessException(
                            StringLiterals.Global,
                            SessionStateCategory.Scope,
                            "GlobalScopeCannotRemove",
                            SessionStateStrings.GlobalScopeCannotRemove);

                throw e;
            }

            // Give the provider a chance to cleanup the drive data associated
            // with drives in this scope

            foreach (PSDriveInfo drive in scope.Drives)
            {
                if (drive == null)
                {
                    continue;
                }

                CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);

                // Call CanRemoveDrive to give the provider a chance to cleanup
                // but ignore the return value and exceptions

                try
                {
                    CanRemoveDrive(drive, context);
                }
                catch (LoopFlowException)
                {
                    throw;
                }
                catch (PipelineStoppedException)
                {
                    throw;
                }
                catch (ActionPreferenceStopException)
                {
                    throw;
                }
                catch (Exception e) // Catch-all OK, 3rd party callout.
                {
                    CommandProcessorBase.CheckForSevereException(e);
                    // Ignore all exceptions from the provider as we are 
                    // going to force the removal anyway
                }
            } // foreach drive

            scope.RemoveAllDrives();

            // If the scope being removed is the current scope,
            // then it must be removed from the tree.

            if (scope == _currentScope && _currentScope.Parent != null)
            {
                _currentScope = _currentScope.Parent;
            }
            scope.Parent = null;
        } // RemoveScope
Ejemplo n.º 48
0
        } // GetAlias

        /// <summary>
        /// Sets an alias to the given value.
        /// </summary>
        ///
        /// <param name="name">
        /// The name of the alias to set.
        /// </param>
        ///
        /// <param name="value">
        /// The value for the alias
        /// </param>
        ///
        /// <param name="context">
        /// The execution context for this engine instance.
        /// </param>
        /// 
        /// <param name="force">
        /// If true, the value will be set even if the alias is ReadOnly.
        /// </param>
        /// 
        /// <param name="origin">
        /// Origin of the caller of this API
        /// </param>
        /// 
        /// <returns>
        /// The string representing the value that was set.
        /// </returns>
        ///
        /// <exception cref="SessionStateUnauthorizedAccessException">
        /// if the alias is read-only or constant.
        /// </exception>
        /// 
        /// <exception cref="SessionStateOverflowException">
        /// If the maximum number of aliases has been reached for this scope.
        /// </exception>
        /// 
        internal AliasInfo SetAliasValue(string name, string value, ExecutionContext context, bool force, CommandOrigin origin)
        {
            Diagnostics.Assert(
                name != null,
                "The caller should verify the name");

            var aliasInfos = GetAliases();
            AliasInfo aliasInfo;
            if (!aliasInfos.TryGetValue(name, out aliasInfo))
            {
                if (aliasInfos.Count > AliasCapacity.FastValue - 1)
                {
                    SessionStateOverflowException e =
                        new SessionStateOverflowException(
                                name,
                                SessionStateCategory.Alias,
                                "AliasOverflow",
                            SessionStateStrings.AliasOverflow,
                                AliasCapacity.FastValue);

                    throw e;
                }
                aliasInfos[name] = new AliasInfo(name, value, context);
            }
            else
            {
                // Make sure the alias isn't constant or readonly
                if ((aliasInfo.Options & ScopedItemOptions.Constant) != 0 ||
                    (!force && (aliasInfo.Options & ScopedItemOptions.ReadOnly) != 0))
                {
                    SessionStateUnauthorizedAccessException e =
                        new SessionStateUnauthorizedAccessException(
                                name,
                                SessionStateCategory.Alias,
                                "AliasNotWritable",
                                SessionStateStrings.AliasNotWritable);

                    throw e;
                }

                SessionState.ThrowIfNotVisible(origin, aliasInfo);
                RemoveAliasFromCache(aliasInfo.Name, aliasInfo.Definition);

                if (force)
                {
                    aliasInfos.Remove(name);
                    aliasInfo = new AliasInfo(name, value, context);
                    aliasInfos[name] = aliasInfo;
                }
                else
                {
                    aliasInfo.SetDefinition(value, false);
                }
            }

            AddAliasToCache(name, value);

            return aliasInfos[name];
        } // SetAliasValue
Ejemplo n.º 49
0
        /// <summary>
        /// Sets a variable to the given value.
        /// </summary>
        ///
        /// <param name="name">
        /// The name of the variable to set.
        /// </param>
        ///
        /// <param name="value">
        /// The value for the variable
        /// </param>
        ///
        /// <param name="asValue">
        /// If true, sets the variable value to newValue. If false, newValue must
        /// be a PSVariable object and the item will be set rather than the value.
        /// </param>
        /// 
        /// <param name="force">
        /// If true, the variable will be set even if it is readonly.
        /// </param>
        ///
        /// <param name="sessionState">
        /// Which SessionState this variable belongs to.
        /// </param>
        /// 
        /// <param name="origin">
        /// The origin of the caller
        /// </param>
        /// 
        /// <param name="fastPath">
        /// If true and the variable is being set in the global scope,
        /// then all of the normal variable lookup stuff is bypassed and
        /// the variable is added directly to the dictionary.
        /// </param>
        /// <returns>
        /// The PSVariable representing the variable that was set.
        /// </returns>
        ///
        /// <exception cref="SessionStateUnauthorizedAccessException">
        /// If the variable is read-only or constant.
        /// </exception> 
        /// 
        /// <exception cref="SessionStateOverflowException">
        /// If the maximum number of variables has been reached for this scope.
        /// </exception>
        /// 
        internal PSVariable SetVariable(string name, object value, bool asValue, bool force, SessionStateInternal sessionState, CommandOrigin origin = CommandOrigin.Internal, bool fastPath = false)
        {
            Diagnostics.Assert(name != null, "The caller should verify the name");

            PSVariable variable;
            PSVariable variableToSet = value as PSVariable;

            // Set the variable directly in the table, bypassing all of the checks. This
            // can only be used for global scope otherwise the slow path is used.
            if (fastPath)
            {
                if (Parent != null)
                {
                    throw new NotImplementedException("fastPath");
                }
                variable = new PSVariable(name, variableToSet.Value, variableToSet.Options, variableToSet.Attributes) { Description = variableToSet.Description };
                GetPrivateVariables()[name] = variable;
                return variable;
            }

            bool varExists = TryGetVariable(name, origin, true, out variable);

            // Initialize the private variable dictionary if it's not yet
            if (_variables == null) { GetPrivateVariables(); }

            if (!asValue && variableToSet != null)
            {
                if (varExists)
                {
                    // First check the variable to ensure that it
                    // is not constant or readonly

                    if (variable == null || variable.IsConstant || (!force && variable.IsReadOnly))
                    {
                        SessionStateUnauthorizedAccessException e =
                            new SessionStateUnauthorizedAccessException(
                                    name,
                                    SessionStateCategory.Variable,
                                    "VariableNotWritable",
                                    SessionStateStrings.VariableNotWritable);

                        throw e;
                    }

                    if (variable is LocalVariable
                        && (variableToSet.Attributes.Any() || variableToSet.Options != variable.Options))
                    {
                        SessionStateUnauthorizedAccessException e =
                            new SessionStateUnauthorizedAccessException(
                                    name,
                                    SessionStateCategory.Variable,
                                    "VariableNotWritableRare",
                                    SessionStateStrings.VariableNotWritableRare);

                        throw e;
                    }

                    if (variable.IsReadOnly && force)
                    {
                        _variables.Remove(name);
                        varExists = false;
                        variable = new PSVariable(name, variableToSet.Value, variableToSet.Options, variableToSet.Attributes) { Description = variableToSet.Description };
                    }
                    else
                    {
                        // Since the variable already exists, copy
                        // the value, options, description, and attributes
                        // to it.
                        variable.Attributes.Clear();

                        variable.Value = variableToSet.Value;
                        variable.Options = variableToSet.Options;
                        variable.Description = variableToSet.Description;

                        foreach (Attribute attr in variableToSet.Attributes)
                        {
                            variable.Attributes.Add(attr);
                        }
                    }
                }
                else
                {
                    // Since the variable doesn't exist, use the new Variable
                    // object

                    variable = variableToSet;
                }
            }
            else if (variable != null)
            {
                variable.Value = value;
            }
            else
            {
                variable = (LocalsTuple != null ? LocalsTuple.TrySetVariable(name, value) : null) ?? new PSVariable(name, value);
            }

            // Now check to make sure we don't exceed the max variable count
            // if this is a new variable.

            if (!varExists && _variables.Count > VariableCapacity.FastValue - 1)
            {
                SessionStateOverflowException e =
                    new SessionStateOverflowException(
                            name,
                            SessionStateCategory.Variable,
                            "VariableOverflow",
                                SessionStateStrings.VariableOverflow,
                            VariableCapacity.FastValue);

                throw e;
            }

            // Don't let people set AllScope variables in ConstrainedLanguage,
            // as they can be used to interfere with the session state of
            // trusted commands.
            if (ExecutionContext.HasEverUsedConstrainedLanguage)
            {
                var context = System.Management.Automation.Runspaces.LocalPipeline.GetExecutionContextFromTLS();

                if ((context != null) &&
                    (context.LanguageMode == PSLanguageMode.ConstrainedLanguage) &&
                    ((variable.Options & ScopedItemOptions.AllScope) == ScopedItemOptions.AllScope))
                {
                    throw new PSNotSupportedException();
                }
            }


            _variables[name] = variable;
            variable.SessionState = sessionState;
            return variable;
        } // SetVariable
Ejemplo n.º 50
0
 private void SetValue(object value)
 {
     if ((this.options & (ScopedItemOptions.Constant | ScopedItemOptions.ReadOnly)) != ScopedItemOptions.None)
     {
         SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException(this.name, SessionStateCategory.Variable, "VariableNotWritable", SessionStateStrings.VariableNotWritable);
         throw exception;
     }
     object obj2 = value;
     if ((this.attributes != null) && (this.attributes.Count > 0))
     {
         obj2 = TransformValue(this.attributes, value);
         if (!this.IsValidValue(obj2))
         {
             ValidationMetadataException exception2 = new ValidationMetadataException("ValidateSetFailure", null, Metadata.InvalidValueFailure, new object[] { this.name, (obj2 != null) ? obj2.ToString() : "" });
             throw exception2;
         }
     }
     if (obj2 != null)
     {
         obj2 = CopyMutableValues(obj2);
     }
     this._value = obj2;
     this.DebuggerCheckVariableWrite();
 }
Ejemplo n.º 51
0
        /// <summary>
        /// Sets an function to the given function declaration.
        /// </summary>
        ///
        /// <param name="name">
        /// The name of the function to set.
        /// </param>
        ///
        /// <param name="function">
        /// The script block that the function should represent.
        /// </param>
        ///
        /// <param name="originalFunction">
        /// The original function (if any) from which the scriptblock was derived.
        /// </param>
        ///
        /// <param name="options">
        /// The options that should be applied to the function.
        /// </param>
        /// 
        /// <param name="force">
        /// If true, the function will be set even if its ReadOnly.
        /// </param>
        /// 
        /// <param name="origin">
        /// The origin of the caller of this API
        /// </param>
        /// 
        /// <param name="context">
        /// The execution context for the function/filter.
        /// </param>
        /// 
        /// <param name="helpFile">
        /// The name of the help file associated with the function.
        /// </param>
        /// 
        /// <param name="functionFactory">
        /// Function to create the FunctionInfo.
        /// </param>
        ///
        /// <returns>
        /// A FunctionInfo that is either a FilterInfo or FunctionInfo representing the
        /// function or filter.
        /// </returns>
        ///
        /// <exception cref="SessionStateUnauthorizedAccessException">
        /// If the function is read-only or constant.
        /// </exception> 
        /// 
        /// <exception cref="SessionStateOverflowException">
        /// If the maximum number of functions have been reached for this scope.
        /// </exception>
        /// 
        internal FunctionInfo SetFunction(
            string name,
            ScriptBlock function,
            FunctionInfo originalFunction,
            ScopedItemOptions options,
            bool force,
            CommandOrigin origin,
            ExecutionContext context,
            string helpFile,
            Func<string, ScriptBlock, FunctionInfo, ScopedItemOptions, ExecutionContext, string, FunctionInfo> functionFactory)
        {
            Diagnostics.Assert(
                name != null,
                "The caller should verify the name");

            var functionInfos = GetFunctions();
            FunctionInfo existingValue;
            FunctionInfo result;
            if (!functionInfos.TryGetValue(name, out existingValue))
            {
                if (functionInfos.Count > FunctionCapacity.FastValue - 1)
                {
                    SessionStateOverflowException e =
                        new SessionStateOverflowException(
                                name,
                                SessionStateCategory.Function,
                                "FunctionOverflow",
                                SessionStateStrings.FunctionOverflow,
                                FunctionCapacity.FastValue);

                    throw e;
                }

                result = functionFactory(name, function, originalFunction, options, context, helpFile);
                functionInfos[name] = result;

                if (IsFunctionOptionSet(result, ScopedItemOptions.AllScope))
                {
                    GetAllScopeFunctions()[name] = result;
                }
            }
            else
            {
                // Make sure the function isn't constant or readonly

                SessionState.ThrowIfNotVisible(origin, existingValue);

                if (IsFunctionOptionSet(existingValue, ScopedItemOptions.Constant) ||
                    (!force && IsFunctionOptionSet(existingValue, ScopedItemOptions.ReadOnly)))
                {
                    SessionStateUnauthorizedAccessException e =
                        new SessionStateUnauthorizedAccessException(
                                name,
                                SessionStateCategory.Function,
                                "FunctionNotWritable",
                                SessionStateStrings.FunctionNotWritable);

                    throw e;
                }

                // Ensure we are not trying to set the function to constant as this can only be
                // done at creation time.

                if ((options & ScopedItemOptions.Constant) != 0)
                {
                    SessionStateUnauthorizedAccessException e =
                        new SessionStateUnauthorizedAccessException(
                                name,
                                SessionStateCategory.Function,
                                "FunctionCannotBeMadeConstant",
                                SessionStateStrings.FunctionCannotBeMadeConstant);

                    throw e;
                }

                // Ensure we are not trying to remove the AllScope option

                if ((options & ScopedItemOptions.AllScope) == 0 &&
                    IsFunctionOptionSet(existingValue, ScopedItemOptions.AllScope))
                {
                    SessionStateUnauthorizedAccessException e =
                        new SessionStateUnauthorizedAccessException(
                                name,
                                SessionStateCategory.Function,
                                "FunctionAllScopeOptionCannotBeRemoved",
                                SessionStateStrings.FunctionAllScopeOptionCannotBeRemoved);

                    throw e;
                }

                FunctionInfo existingFunction = existingValue;
                FunctionInfo newValue = null;

                // If the function type changes (i.e.: function to workflow or back)
                // then we need to blast what was there
                newValue = functionFactory(name, function, originalFunction, options, context, helpFile);

                bool changesFunctionType = existingFunction.GetType() != newValue.GetType();

                // Since the options are set after the script block, we have to
                // forcefully apply the script block if the options will be
                // set to not being ReadOnly
                if (changesFunctionType ||
                    ((existingFunction.Options & ScopedItemOptions.ReadOnly) != 0 && force))
                {
                    result = newValue;
                    functionInfos[name] = newValue;
                }
                else
                {
                    bool applyForce = force || (options & ScopedItemOptions.ReadOnly) == 0;

                    existingFunction.Update(newValue, applyForce, options, helpFile);
                    result = existingFunction;
                }
            }

            return result;
        } // SetFunction
Ejemplo n.º 52
0
 internal PSVariable NewVariable(PSVariable newVariable, bool force, SessionStateInternal sessionState)
 {
     PSVariable variable;
     bool flag = this.TryGetVariable(newVariable.Name, this.ScopeOrigin, true, out variable);
     if (flag)
     {
         if (((variable == null) || variable.IsConstant) || (!force && variable.IsReadOnly))
         {
             SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException(newVariable.Name, SessionStateCategory.Variable, "VariableNotWritable", SessionStateStrings.VariableNotWritable);
             throw exception;
         }
         if (variable is LocalVariable)
         {
             SessionStateUnauthorizedAccessException exception2 = new SessionStateUnauthorizedAccessException(newVariable.Name, SessionStateCategory.Variable, "VariableNotWritableRare", SessionStateStrings.VariableNotWritableRare);
             throw exception2;
         }
         if (!object.ReferenceEquals(newVariable, variable))
         {
             variable.WasRemoved = true;
             variable = newVariable;
         }
     }
     else
     {
         variable = newVariable;
     }
     if (!flag && (this._variables.Count > (this.VariableCapacity.FastValue - 1)))
     {
         SessionStateOverflowException exception3 = new SessionStateOverflowException(newVariable.Name, SessionStateCategory.Variable, "VariableOverflow", SessionStateStrings.VariableOverflow, new object[] { this.VariableCapacity.FastValue });
         throw exception3;
     }
     if (System.Management.Automation.ExecutionContext.HasEverUsedConstrainedLanguage)
     {
         System.Management.Automation.ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();
         if (((executionContextFromTLS != null) && (executionContextFromTLS.LanguageMode == PSLanguageMode.ConstrainedLanguage)) && ((variable.Options & ScopedItemOptions.AllScope) == ScopedItemOptions.AllScope))
         {
             throw new PSNotSupportedException();
         }
     }
     this._variables[variable.Name] = variable;
     variable.SessionState = sessionState;
     return variable;
 }
Ejemplo n.º 53
0
        } // NewVariable

        /// <summary>
        /// Removes a variable from the variable table.
        /// </summary>
        ///
        /// <param name="name">
        /// The name of the variable to remove.
        /// </param>
        ///
        /// <param name="force">
        /// If true, the variable will be removed even if its ReadOnly.
        /// </param>
        /// 
        /// <exception cref="SessionStateUnauthorizedAccessException">
        /// if the variable is constant.
        /// </exception>
        /// 
        internal void RemoveVariable(string name, bool force)
        {
            Diagnostics.Assert(
                name != null,
                "The caller should verify the name");

            PSVariable variable = GetVariable(name);

            if (variable.IsConstant || (variable.IsReadOnly && !force))
            {
                SessionStateUnauthorizedAccessException e =
                    new SessionStateUnauthorizedAccessException(
                            name,
                            SessionStateCategory.Variable,
                            "VariableNotRemovable",
                            SessionStateStrings.VariableNotRemovable);

                throw e;
            }

            if (variable is SessionStateCapacityVariable)
            {
                SessionStateUnauthorizedAccessException e =
                    new SessionStateUnauthorizedAccessException(
                            name,
                            SessionStateCategory.Variable,
                            "VariableNotRemovableSystem",
                            SessionStateStrings.VariableNotRemovableSystem);

                throw e;
            }

            if (variable is LocalVariable)
            {
                SessionStateUnauthorizedAccessException e =
                    new SessionStateUnauthorizedAccessException(
                            name,
                            SessionStateCategory.Variable,
                            "VariableNotRemovableRare",
                            SessionStateStrings.VariableNotRemovableRare);

                throw e;
            }

            _variables.Remove(name);

            // Finally mark the variable itself has having been removed so
            // anyone holding a reference to it can be aware of this.
            variable.WasRemoved = true;
        } // RemoveVariable
Ejemplo n.º 54
0
        } // GetSessionStateTable

        /// <summary>
        /// Determines if the item can be renamed. Derived classes that need
        /// to perform a check should override this method.
        /// </summary>
        /// 
        /// <param name="item">
        /// The item to verify if it can be renamed.
        /// </param>
        /// 
        /// <returns>
        /// true if the item can be renamed or false otherwise.
        /// </returns>
        /// 
        internal override bool CanRenameItem(object item)
        {
            bool result = false;

            FunctionInfo functionInfo = item as FunctionInfo;
            if (functionInfo != null)
            {
                if ((functionInfo.Options & ScopedItemOptions.Constant) != 0 ||
                    ((functionInfo.Options & ScopedItemOptions.ReadOnly) != 0 && !Force))
                {
                    SessionStateUnauthorizedAccessException e =
                        new SessionStateUnauthorizedAccessException(
                            functionInfo.Name,
                            SessionStateCategory.Function,
                            "CannotRenameFunction",
                            SessionStateStrings.CannotRenameFunction);

                    throw e;
                }

                result = true;
            }

            return result;
        }
Ejemplo n.º 55
0
        /// <summary>
        /// Sets the options for the alias and allows changes ReadOnly options only if force is specified.
        /// </summary>
        ///
        /// <param name="newOptions">
        /// The new options value.
        /// </param>
        ///
        /// <param name="force">
        /// If true the change to the options will happen even if the existing options are read-only.
        /// </param>
        ///
        internal void SetOptions(ScopedItemOptions newOptions, bool force)
        {
            // Check to see if the variable is constant, if so
            // throw an exception because the options cannot be changed.

            if ((_options & ScopedItemOptions.Constant) != 0)
            {
                SessionStateUnauthorizedAccessException e =
                    new SessionStateUnauthorizedAccessException(
                        Name,
                        SessionStateCategory.Alias,
                        "AliasIsConstant",
                        SessionStateStrings.AliasIsConstant);

                throw e;
            }

            // Check to see if the variable is readonly, if so
            // throw an exception because the options cannot be changed.

            if (!force && (_options & ScopedItemOptions.ReadOnly) != 0)
            {
                SessionStateUnauthorizedAccessException e =
                    new SessionStateUnauthorizedAccessException(
                        Name,
                        SessionStateCategory.Alias,
                        "AliasIsReadOnly",
                        SessionStateStrings.AliasIsReadOnly);

                throw e;
            }

            // Now check to see if the caller is trying to set
            // the options to constant. This is only allowed at
            // variable creation

            if ((newOptions & ScopedItemOptions.Constant) != 0)
            {
                // user is trying to set the variable to constant after
                // creating the variable. Do not allow this (as per spec).

                SessionStateUnauthorizedAccessException e =
                    new SessionStateUnauthorizedAccessException(
                        Name,
                        SessionStateCategory.Alias,
                        "AliasCannotBeMadeConstant",
                        SessionStateStrings.AliasCannotBeMadeConstant);

                throw e;
            }

            if ((newOptions & ScopedItemOptions.AllScope) == 0 &&
                (_options & ScopedItemOptions.AllScope) != 0)
            {
                // user is trying to remove the AllScope option from the alias.
                // Do not allow this (as per spec).

                SessionStateUnauthorizedAccessException e =
                    new SessionStateUnauthorizedAccessException(
                        this.Name,
                        SessionStateCategory.Alias,
                        "AliasAllScopeOptionCannotBeRemoved",
                        SessionStateStrings.AliasAllScopeOptionCannotBeRemoved);

                throw e;
            }

            _options = newOptions;
        }
Ejemplo n.º 56
0
 internal void RemoveScope(SessionStateScope scope)
 {
     if (scope == this._globalScope)
     {
         SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException("GLOBAL", SessionStateCategory.Scope, "GlobalScopeCannotRemove", SessionStateStrings.GlobalScopeCannotRemove);
         throw exception;
     }
     foreach (PSDriveInfo info in scope.Drives)
     {
         if (info != null)
         {
             CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
             try
             {
                 this.CanRemoveDrive(info, context);
             }
             catch (LoopFlowException)
             {
                 throw;
             }
             catch (PipelineStoppedException)
             {
                 throw;
             }
             catch (ActionPreferenceStopException)
             {
                 throw;
             }
             catch (Exception exception2)
             {
                 CommandProcessorBase.CheckForSevereException(exception2);
             }
         }
     }
     scope.RemoveAllDrives();
     if ((scope == this.currentScope) && (this.currentScope.Parent != null))
     {
         this.currentScope = this.currentScope.Parent;
     }
     scope.Parent = null;
 }