Inheritance: IHasSessionStateEntryVisibility
Example #1
0
    public static string InvokeAutomation(string cmd)
    {
        Runspace newrunspace = RunspaceFactory.CreateRunspace();

        newrunspace.Open();

        // transcript evasion
        RunspaceInvoke scriptInvoker = new RunspaceInvoke(newrunspace);
        var            cmdin         = new System.Management.Automation.PSVariable("c");

        newrunspace.SessionStateProxy.PSVariable.Set(cmdin);
        var output = new System.Management.Automation.PSVariable("o");

        newrunspace.SessionStateProxy.PSVariable.Set(output);

        Pipeline pipeline = newrunspace.CreatePipeline();

        newrunspace.SessionStateProxy.SetVariable("c", cmd);
        pipeline.Commands.AddScript("$o = IEX $c | Out-String");
        Collection <PSObject> results = pipeline.Invoke();

        newrunspace.Close();

        StringBuilder stringBuilder = new StringBuilder();

        foreach (PSObject obj in results)
        {
            stringBuilder.Append(obj);
        }
        return(stringBuilder.ToString().Trim());
    }
Example #2
0
        internal override void SetSessionStateItem(string name, object value, bool writeItem)
        {
            Path path = PathIntrinsics.RemoveDriveName(name);
            name = path.TrimStartSlash();

            PSVariable variable = null;
            if (value != null)
            {
                variable = value as PSVariable;
                if (variable == null)
                {
                    variable = new PSVariable(name, value);
                }
                else if (String.Compare(name, variable.Name, true, System.Globalization.CultureInfo.CurrentCulture) != 0)
                {
                    PSVariable var = new PSVariable(name, variable.Value, variable.Options, variable.Attributes);
                    var.Description = variable.Description;
                    variable = var;
                }
            }
            else
            {
                variable = new PSVariable(name, null);
            }
            // TODO: can be Force'ed
            SessionState.PSVariable.Set(variable);
            PSVariable item = SessionState.PSVariable.Get(variable.Name);
            if (writeItem && (item != null))
            {
                WriteItemObject(item, item.Name, false);
            }
        }
        public static void Set__variable(this PSVariableProperty source, PSVariable value)
        {
            if (source == null)
                throw new ArgumentNullException("source");

            FieldSetterDelegate__variable.Set(source, value);
        }
Example #4
0
        protected override void ProcessRecord()
        {
            // TODO: deal with Force
            // TODO: deal with ShouldProcess

            PSVariable variable = new PSVariable(Name, Value, Option);
            if (Description != null)
            {
                variable.Description = Description;
            }
            //TODO: check if variable already exists and check if force has influence on behavior
            //implement also an overloaded Get method in PSVariableIntrniscs that allow to pass a scope
            try
            {
                //TODO: create a new overloaded method in PSVariableIntrinsics that allows to pass (bool)this.Force
                SessionState.PSVariable.Set(variable);
            }
            catch (Exception ex)
            {
                WriteError(new ErrorRecord(ex, "", ErrorCategory.InvalidOperation, variable));
                return;
            }
            if (PassThru.ToBool())
            {
                WriteObject(variable);
            }
        }
Example #5
0
 internal override void SetSessionStateItem(string name, object value, bool writeItem)
 {
     PSVariable variable = null;
     if (value != null)
     {
         variable = value as PSVariable;
         if (variable == null)
         {
             variable = new PSVariable(name, value);
         }
         else if (!string.Equals(name, variable.Name, StringComparison.OrdinalIgnoreCase))
         {
             variable = new PSVariable(name, variable.Value, variable.Options, variable.Attributes) {
                 Description = variable.Description
             };
         }
     }
     else
     {
         variable = new PSVariable(name, null);
     }
     PSVariable item = base.SessionState.Internal.SetVariable(variable, (bool) base.Force, base.Context.Origin) as PSVariable;
     if (writeItem && (item != null))
     {
         base.WriteItemObject(item, item.Name, false);
     }
 }
 /// <summary>
 /// Add an new SessionStateVariable entry to this session state object...
 /// </summary>
 /// <param name="entry">The entry to add</param>
 internal void AddSessionStateEntry(SessionStateVariableEntry entry)
 {
     PSVariable v = new PSVariable(entry.Name, entry.Value,
             entry.Options, entry.Attributes, entry.Description);
     v.Visibility = entry.Visibility;
     this.SetVariableAtScope(v, "global", true, CommandOrigin.Internal);
 }
Example #7
0
 internal override void SetSessionStateItem(Path name, object value, bool writeItem)
 {
     PSVariable variable = null;
     if (value != null)
     {
         variable = value as PSVariable;
         if (variable == null)
         {
             variable = new PSVariable(name, value);
         }
         else if (String.Compare(name, variable.Name, true, System.Globalization.CultureInfo.CurrentCulture) != 0)
         {
             PSVariable var = new PSVariable(name, variable.Value, variable.Options, variable.Attributes);
             var.Description = variable.Description;
             variable = var;
         }
     }
     else
     {
         variable = new PSVariable(name, null);
     }
     // TODO: can be Force'ed
     PSVariable item = base.SessionState.SessionStateGlobal.SetVariable(variable) as PSVariable;
     if (writeItem && (item != null))
     {
         WriteItemObject(item, item.Name, false);
     }
 }
Example #8
0
 protected override void ProcessRecord()
 {
     if (this.Force == 0)
     {
         PSVariable atScope = null;
         if (string.IsNullOrEmpty(base.Scope))
         {
             atScope = base.SessionState.PSVariable.GetAtScope(this.name, "local");
         }
         else
         {
             atScope = base.SessionState.PSVariable.GetAtScope(this.name, base.Scope);
         }
         if (atScope != null)
         {
             SessionStateException replaceParentContainsErrorRecordException = new SessionStateException(this.name, SessionStateCategory.Variable, "VariableAlreadyExists", SessionStateStrings.VariableAlreadyExists, ErrorCategory.ResourceExists, new object[0]);
             base.WriteError(new ErrorRecord(replaceParentContainsErrorRecordException.ErrorRecord, replaceParentContainsErrorRecordException));
             return;
         }
     }
     string newVariableAction = VariableCommandStrings.NewVariableAction;
     string target = StringUtil.Format(VariableCommandStrings.NewVariableTarget, this.Name, this.Value);
     if (base.ShouldProcess(target, newVariableAction))
     {
         PSVariable variable = new PSVariable(this.name, this._value, this.options);
         if (this._visibility.HasValue)
         {
             variable.Visibility = this._visibility.Value;
         }
         if (this.description != null)
         {
             variable.Description = this.description;
         }
         try
         {
             if (string.IsNullOrEmpty(base.Scope))
             {
                 base.SessionState.Internal.NewVariable(variable, (bool) this.Force);
             }
             else
             {
                 base.SessionState.Internal.NewVariableAtScope(variable, base.Scope, (bool) this.Force);
             }
         }
         catch (SessionStateException exception2)
         {
             base.WriteError(new ErrorRecord(exception2.ErrorRecord, exception2));
             return;
         }
         catch (PSArgumentException exception3)
         {
             base.WriteError(new ErrorRecord(exception3.ErrorRecord, exception3));
             return;
         }
         if (this.passThru)
         {
             base.WriteObject(variable);
         }
     }
 }
Example #9
0
        protected override void ProcessRecord()
        {
            // TODO: deal with scope
            // TODO: deal with Force
            // TODO: deal with ShouldProcess

            PSVariable variable = new PSVariable(Name, Value, Option);
            if (Description != null)
            {
                variable.Description = Description;
            }
            try
            {
                SessionState.SessionStateGlobal.NewVariable(variable, (bool)this.Force);
            }
            catch (Exception ex)
            {
                WriteError(new ErrorRecord(ex, "", ErrorCategory.InvalidOperation, variable));
                return;
            }
            if (PassThru.ToBool())
            {
                WriteObject(variable);
            }
        }
Example #10
0
 protected internal void CheckVariableCanBeChanged(PSVariable variable, bool force)
 {
     if ((variable.ItemOptions.HasFlag(ScopedItemOptions.ReadOnly) && !force) ||
         variable.ItemOptions.HasFlag(ScopedItemOptions.Constant))
     {
         throw SessionStateUnauthorizedAccessException.CreateVariableNotWritableError(variable);
     }
 }
 private void CheckVariableCanBeRemoved(PSVariable variable)
 {
     if ((variable.ItemOptions.HasFlag(ScopedItemOptions.ReadOnly) && !Force) ||
         variable.ItemOptions.HasFlag(ScopedItemOptions.Constant))
     {
         throw SessionStateUnauthorizedAccessException.CreateVariableNotRemovableError(variable);
     }
 }
Example #12
0
 public PSVariableProperty(PSVariable variable) : base((variable != null) ? variable.Name : null, null)
 {
     if (variable == null)
     {
         throw PSTraceSource.NewArgumentException("variable");
     }
     this._variable = variable;
 }
Example #13
0
 public void Remove(PSVariable variable)
 {
     //no scope specified when passing an object: we only care about the local scope
     if (variable == null)
     {
         throw new ArgumentNullException("The variable is null.");
     }
     //add the local scope specifier to make sure we don't screw up with other variables
     Remove("local:" + variable.Name);
 }
Example #14
0
 private PSVariable ClearValue(PSVariable matchingVariable)
 {
     PSVariable variable = matchingVariable;
     if (base.Scope != null)
     {
         matchingVariable.Value = null;
         return variable;
     }
     base.SessionState.PSVariable.Set(matchingVariable.Name, null);
     return base.SessionState.PSVariable.Get(matchingVariable.Name);
 }
Example #15
0
        public static void startrunspace()
        {
            newrunspace = RunspaceFactory.CreateRunspace();
            newrunspace.Open();
            var cmd = new System.Management.Automation.PSVariable("c");

            newrunspace.SessionStateProxy.PSVariable.Set(cmd);
            var output = new System.Management.Automation.PSVariable("o");

            newrunspace.SessionStateProxy.PSVariable.Set(output);
        }
Example #16
0
 internal History(System.Management.Automation.ExecutionContext context)
 {
     Collection<Attribute> attributes = new Collection<Attribute> {
         new ValidateRangeAttribute(1, 0x7fff)
     };
     PSVariable variable = new PSVariable("MaximumHistoryCount", 0x1000, ScopedItemOptions.None, attributes) {
         Description = SessionStateStrings.MaxHistoryCountDescription
     };
     context.EngineSessionState.SetVariable(variable, false, CommandOrigin.Internal);
     this._capacity = 0x1000;
     this._buffer = new HistoryInfo[this._capacity];
 }
Example #17
0
 internal bool TryGetLocalVariable(string name, bool fromNewOrSet, out PSVariable result)
 {
     int index;
     name = VariableAnalysis.GetUnaliasedVariableName(name);
     if (_nameToIndexMap.TryGetValue(name, out index) && (fromNewOrSet || IsValueSet(index)))
     {
         result = new LocalVariable(name, this, index);
         return true;
     }
     result = null;
     return false;
 }
Example #18
0
      /// <summary>
      /// Invoke a <see cref="ScriptBlock"/>, binding it to the module, if possible.
      /// </summary>
      /// <param name="sb">The <see cref="ScriptBlock"/></param>
      /// <param name="variables">Variables to set before invoking</param>
      /// <param name="args">Arguments to the <see cref="ScriptBlock"/></param>
      /// <returns>A collection of <see cref="PSObject"/></returns>
      internal static ICollection<PSObject> Invoke(ScriptBlock sb, PSVariable[] variables, params object[] args)
      {
         if (variables == null)
            throw new ArgumentNullException("variables");

         foreach (var v in variables) SetScriptVariable(v);

         if (_module != null)
         {
            sb = _module.NewBoundScriptBlock(sb);
         }

         return sb.Invoke(args);
      }
Example #19
0
 public void Set(PSVariable variable)
 {
     if (variable == null)
     {
         throw new ArgumentNullException("The variable is null.");
     }
     var original = _scope.GetLocal(variable.Name);
     if (original == null)
     {
         _scope.SetLocal(variable, true);
         return;
     }
     original.Value = variable.Value;
     original.Description = variable.Description;
     original.Options = variable.Options;
     _scope.SetLocal(original, true);
 }
Example #20
0
 internal override void BindParameter(string name, object value)
 {
     if ((value == AutomationNull.Value) || (value == UnboundParameter.Value))
     {
         value = null;
     }
     VariablePath variablePath = new VariablePath(name, VariablePathFlags.Variable);
     if (((this.LocalScope == null) || !variablePath.IsAnyLocal()) || !this.LocalScope.TrySetLocalParameterValue(variablePath.UnqualifiedPath, this.CopyMutableValues(value)))
     {
         RuntimeDefinedParameter parameter;
         PSVariable newValue = new PSVariable(variablePath.UnqualifiedPath, value, variablePath.IsPrivate ? ScopedItemOptions.Private : ScopedItemOptions.None);
         base.Context.EngineSessionState.SetVariable(variablePath, newValue, false, CommandOrigin.Internal);
         if (this.Script.RuntimeDefinedParameters.TryGetValue(name, out parameter))
         {
             newValue.AddParameterAttributesNoChecks(parameter.Attributes);
         }
     }
 }
        /// <summary>	A SessionState extension method that adds a service connection. </summary>
        /// <exception cref="ArgumentNullException">Thrown when one or more required arguments are null. </exception>
        /// <param name="sessionState">  	. </param>
        /// <param name="connectionName">	The connection Name. </param>
        /// <param name="connection">	 	The connection. </param>
        /// <returns>	A St2ClientConnection. </returns>
        public static St2ClientConnection AddServiceConnection(this SessionState sessionState,
			string connectionName, St2ClientConnection connection)
        {
            if (sessionState == null)
                throw new ArgumentNullException("sessionState");

            if (connection == null)
                throw new ArgumentNullException("connection");

            if (string.IsNullOrEmpty(connectionName))
                throw new ArgumentNullException("connectionName");

            Dictionary<string, St2ClientConnection> connections;
            PSVariable connectionsVariable = sessionState.PSVariable.Get(VariableNames.ServiceSessions);
            if (connectionsVariable == null)
            {
                connectionsVariable = new PSVariable(
                    VariableNames.ServiceSessions, connections = new Dictionary<string, St2ClientConnection>(),
                    ScopedItemOptions.AllScope
                    );
                sessionState.PSVariable.Set(connectionsVariable);
            }
            else
            {
                connections = (Dictionary<string, St2ClientConnection>)connectionsVariable.Value;
                if (connections == null)
                {
                    connectionsVariable.Value = connections = new Dictionary<string, St2ClientConnection>();
                    sessionState.PSVariable.Set(connectionsVariable);
                }
            }

            if (!connections.ContainsKey(connectionName))
                connections.Add(connectionName, connection);
            else
                connections[connectionName] = connection;

            if (string.IsNullOrEmpty(_defaultComputeServiceConnectionName) || connections.Count().Equals(1))
                _defaultComputeServiceConnectionName = connectionName;

            return connection;
        }
Example #22
0
        protected override void EndProcessing()
        {
            foreach (string name in Name)
            {
                foreach (object value in _values)
                {
                    PSVariable variable = SessionState.PSVariable.Get(name);

                    if (variable == null)
                    {
                        variable = new PSVariable(name, value);
                    }
                    else
                    {
                        variable.Value = value;
                    }

                    SessionState.PSVariable.Set(variable);
                }
            }
        }
        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;
        }
Example #24
0
        protected override void ProcessRecord()
        {
            // TODO: deal with ShouldProcess

            var variable = new PSVariable(Name, Value, Option);
            variable.Visibility = Visibility;
            if (Description != null)
            {
                variable.Description = Description;
            }

            try
            {
                if (!Force && VariableAlreadyExists(variable))
                {
                    WriteVariableAlreadyExistsError(variable);
                    return;
                }
                SessionState.PSVariable.SetAtScope(variable, Scope, Force);
            }
            catch (SessionStateUnauthorizedAccessException ex)
            {
                WriteError(ex.ErrorRecord);
                return;
            }
            catch (Exception ex)
            {
                WriteError(new ErrorRecord(ex, "", ErrorCategory.InvalidOperation, variable));
                return;
            }

            if (PassThru.ToBool())
            {
                WriteObject(variable);
            }
        }
Example #25
0
        private PSVariable SetVariable(string name, object value)
        {
            PSVariable variable = SessionState.PSVariable.GetAtScope(name, Scope);

            if (variable == null)
            {
                variable = new PSVariable(name, value, Option);
                variable.Visibility = Visibility;
            }
            else
            {
                CheckVariableCanBeChanged(variable, Force);
                variable.Value = value;
                SetVariableOptions(variable);
            }

            variable.Description = Description ?? String.Empty;

            SessionState.PSVariable.SetAtScope(variable, Scope, Force);

            return variable;
        }
Example #26
0
        private void CheckVariableOptionCanBeChanged(PSVariable variable)
        {
            CheckVariableCanBeChanged(variable, Force);

            if (_option == ScopedItemOptions.Constant)
            {
                throw SessionStateUnauthorizedAccessException.CreateVariableCannotBeMadeConstantError(variable);
            }
        }
Example #27
0
 internal void RemoveVariable(PSVariable variable)
 {
     RemoveVariable(variable.Name);
 }
Example #28
0
        internal object SetVariable(string name, object value)
        {
            PSVariable variable = GetVariable(name);

            if (variable != null)
                RemoveVariable(variable);

            variable = new PSVariable(name, value);

            _variables.Add(variable.Name, variable);

            return variable;
        }
 public void Remove(PSVariable variable)
 {
     _sessionState.RemoveVariable(variable);
 }
Example #30
0
        public static bool ImportVariables(
            SettingsCmdletBase cmdlet,
            IEnumerable<XElement> variablesCollection)
        {
            bool result = false;

            foreach (XElement element in variablesCollection) {

                string variableName = string.Empty;

                try {

                    variableName =
                            element.Attribute((XName)"name").Value;

                    cmdlet.WriteVerbose(cmdlet, "importing the '" + variableName + "' variable");

                    string variableValue =
                        string.Empty;
                    try {
                        variableValue =
                            element.Attribute((XName)"value").Value;
                    }
                    catch {
                        // nothing to do
                    }

                    //ScopedItemOptions.AllScope
                    //ScopedItemOptions.Constant
                    //ScopedItemOptions.None
                    //ScopedItemOptions.Private
                    //ScopedItemOptions.ReadOnly
                    //ScopedItemOptions.Unspecified

                    PSVariable variable =
                        new PSVariable(
                            variableName,
                            variableValue);
                    cmdlet.SessionState.PSVariable.Set(variable);
                }
                catch (Exception eLoadingVariable) {
                    cmdlet.WriteError(
                        cmdlet,
                        "Unable to load variable '" +
                        variableName +
                        "'. " +
                        eLoadingVariable.Message,
                        "FailedToLoadVariable",
                        ErrorCategory.InvalidData,
                        false);
                }
            }

            return result;
        }
        internal static Exception CreateVariableCannotBeMadeConstantError(PSVariable variable)
        {
            string message = String.Format("Existing variable {0} cannot be made constant. Variables can be made constant only at creation time.", variable.Name);

            return(CreateError(variable, message, "VariableCannotBeMadeConstant"));
        }
        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)
            {
                var.Attributes.Clear();
                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);
                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);
        }
        internal static SessionStateUnauthorizedAccessException CreateVariableNotRemovableError(PSVariable variable)
        {
            string message = String.Format("Cannot remove variable {0} because it is constant or read-only. If the variable is read-only, try the operation again specifying the Force option.", variable.Name);

            return(CreateError(variable, message, "VariableNotRemovable"));
        }
        internal static SessionStateUnauthorizedAccessException CreateVariableNotWritableError(PSVariable variable)
        {
            string message = String.Format("Cannot overwrite variable {0} because it is read-only or constant.", variable.Name);

            return(CreateError(variable, message, "VariableNotWritable"));
        }
 public void Set(PSVariable variable)
 {
     _sessionState.SetVariable(variable);
 }
Example #36
0
 private void SetVariableOptions(PSVariable variable)
 {
     if (_option.HasValue && variable.Options != _option.Value)
     {
         CheckVariableOptionCanBeChanged(variable);
         variable.Options = _option.Value;
     }
 }
Example #37
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);
        }
 internal void RemoveAtScope(PSVariable variable, string scope)
 {
     this.sessionState.RemoveVariableAtScope(variable, scope);
 }
 public void Set(PSVariable variable)
 {
     this.sessionState.SetVariable(variable, false, CommandOrigin.Internal);
 }
Example #40
0
 internal void NewVariable(PSVariable variable, bool force)
 {
     throw new NotImplementedException();
 }
Example #41
0
        /// <summary>
        /// Add the variables that must always be present in a SessionState instance...
        /// </summary>
        internal void InitializeFixedVariables()
        {
            //
            // BUGBUG
            //
            // String resources for aliases are currently associated with Runspace init
            //

            // $Host
            PSVariable v = new PSVariable(
                SpecialVariables.Host,
                ExecutionContext.EngineHostInterface,
                ScopedItemOptions.Constant | ScopedItemOptions.AllScope,
                RunspaceInit.PSHostDescription);

            this.GlobalScope.SetVariable(v.Name, v, false, true, this, CommandOrigin.Internal, fastPath: true);

            // $HOME - indicate where a user's home directory is located in the file system.
            //    -- %USERPROFILE% on windows
            //    -- %HOME% on unix
            string home = Environment.GetEnvironmentVariable(Platform.CommonEnvVariableNames.Home) ?? string.Empty;

            v = new PSVariable(SpecialVariables.Home,
                               home,
                               ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope,
                               RunspaceInit.HOMEDescription);
            this.GlobalScope.SetVariable(v.Name, v, false, true, this, CommandOrigin.Internal, fastPath: true);

            // $ExecutionContext
            v = new PSVariable(SpecialVariables.ExecutionContext,
                               ExecutionContext.EngineIntrinsics,
                               ScopedItemOptions.Constant | ScopedItemOptions.AllScope,
                               RunspaceInit.ExecutionContextDescription);
            this.GlobalScope.SetVariable(v.Name, v, false, true, this, CommandOrigin.Internal, fastPath: true);

            // $PSVersionTable
            v = new PSVariable(SpecialVariables.PSVersionTable,
                               PSVersionInfo.GetPSVersionTable(),
                               ScopedItemOptions.Constant | ScopedItemOptions.AllScope,
                               RunspaceInit.PSVersionTableDescription);
            this.GlobalScope.SetVariable(v.Name, v, false, true, this, CommandOrigin.Internal, fastPath: true);

            // $PSEdition
            v = new PSVariable(SpecialVariables.PSEdition,
                               PSVersionInfo.PSEditionValue,
                               ScopedItemOptions.Constant | ScopedItemOptions.AllScope,
                               RunspaceInit.PSEditionDescription);
            this.GlobalScope.SetVariable(v.Name, v, false, true, this, CommandOrigin.Internal, fastPath: true);

            // $PID
            Process currentProcess = Process.GetCurrentProcess();

            v = new PSVariable(
                SpecialVariables.PID,
                currentProcess.Id,
                ScopedItemOptions.Constant | ScopedItemOptions.AllScope,
                RunspaceInit.PIDDescription);
            this.GlobalScope.SetVariable(v.Name, v, false, true, this, CommandOrigin.Internal, fastPath: true);

            // $PSCulture
            v = new PSCultureVariable();
            this.GlobalScope.SetVariable(v.Name, v, false, true, this, CommandOrigin.Internal, fastPath: true);

            // $PSUICulture
            v = new PSUICultureVariable();
            this.GlobalScope.SetVariable(v.Name, v, false, true, this, CommandOrigin.Internal, fastPath: true);

            // $?
            v = new QuestionMarkVariable(this.ExecutionContext);
            this.GlobalScope.SetVariableForce(v, this);

            // $ShellId - if there is no runspace config, use the default string
            string shellId = ExecutionContext.ShellID;

            v = new PSVariable(SpecialVariables.ShellId, shellId,
                               ScopedItemOptions.Constant | ScopedItemOptions.AllScope,
                               RunspaceInit.MshShellIdDescription);
            this.GlobalScope.SetVariable(v.Name, v, false, true, this, CommandOrigin.Internal, fastPath: true);

            // $PSHOME
            // This depends on the shellId. If we cannot read the application base
            // registry key, set the variable to empty string
            string applicationBase = "";

            try
            {
                applicationBase = Utils.GetApplicationBase(shellId);
            }
            catch (SecurityException)
            {
            }
            v = new PSVariable(SpecialVariables.PSHome, applicationBase,
                               ScopedItemOptions.Constant | ScopedItemOptions.AllScope,
                               RunspaceInit.PSHOMEDescription);

            this.GlobalScope.SetVariable(v.Name, v, false, true, this, CommandOrigin.Internal, fastPath: true);
        }
Example #42
0
        internal object SetVariable(PSVariable variable)
        {
            // TODO: deal with scopes

            RemoveVariable(variable);

            _variables.Add(variable.Name, variable);

            return variable;
        }
Example #43
0
        /// <summary>
        /// Utility to check the visibility of an object based on the current
        /// command origin. If the object implements IHasSessionStateEntryVisibility
        /// then the check will be made. If the check fails, then an exception will be thrown...
        /// </summary>
        /// <param name="origin">The command origin value to check against...</param>
        /// <param name="valueToCheck">The object to check.</param>
        public static void ThrowIfNotVisible(CommandOrigin origin, object valueToCheck)
        {
            SessionStateException exception;

            if (!IsVisible(origin, valueToCheck))
            {
                PSVariable sv = valueToCheck as PSVariable;
                if (sv != null)
                {
                    exception =
                        new SessionStateException(
                            sv.Name,
                            SessionStateCategory.Variable,
                            "VariableIsPrivate",
                            SessionStateStrings.VariableIsPrivate,
                            ErrorCategory.PermissionDenied);

                    throw exception;
                }

                CommandInfo cinfo = valueToCheck as CommandInfo;
                if (cinfo != null)
                {
                    string commandName = cinfo.Name;
                    if (commandName != null)
                    {
                        // If we have a name, use it in the error message
                        exception =
                            new SessionStateException(
                                commandName,
                                SessionStateCategory.Command,
                                "NamedCommandIsPrivate",
                                SessionStateStrings.NamedCommandIsPrivate,
                                ErrorCategory.PermissionDenied);
                    }
                    else
                    {
                        exception =
                            new SessionStateException(
                                string.Empty,
                                SessionStateCategory.Command,
                                "CommandIsPrivate",
                                SessionStateStrings.CommandIsPrivate,
                                ErrorCategory.PermissionDenied);
                    }

                    throw exception;
                }

                // Catch all error for other types of resources...
                exception =
                    new SessionStateException(
                        null,
                        SessionStateCategory.Resource,
                        "ResourceIsPrivate",
                        SessionStateStrings.ResourceIsPrivate,
                        ErrorCategory.PermissionDenied);

                throw exception;
            }
        }
Example #44
0
 public PSVariableProperty(PSVariable variable)
     : base(variable?.Name, (object)null)
     => this._variable = variable != null ? variable : throw PSVariableProperty.tracer.NewArgumentException(nameof(variable));
 internal PSVariableAttributeCollection(PSVariable variable) => this.variable = variable != null ? variable : throw PSVariableAttributeCollection.tracer.NewArgumentNullException(nameof(variable));