コード例 #1
0
        private bool AstAssignsToSameVariable(Ast ast)
        {
            ParameterAst ast2 = ast as ParameterAst;

            if (ast2 != null)
            {
                return(this.VariablePath.IsUnscopedVariable && ast2.Name.VariablePath.UnqualifiedPath.Equals(this.VariablePath.UnqualifiedPath, StringComparison.OrdinalIgnoreCase));
            }
            ForEachStatementAst ast3 = ast as ForEachStatementAst;

            if (ast3 != null)
            {
                return(this.VariablePath.IsUnscopedVariable && ast3.Variable.VariablePath.UnqualifiedPath.Equals(this.VariablePath.UnqualifiedPath, StringComparison.OrdinalIgnoreCase));
            }
            AssignmentStatementAst ast4 = (AssignmentStatementAst)ast;
            ExpressionAst          left = ast4.Left;
            ConvertExpressionAst   ast6 = left as ConvertExpressionAst;

            if (ast6 != null)
            {
                left = ast6.Child;
            }
            VariableExpressionAst ast7 = left as VariableExpressionAst;

            if (ast7 == null)
            {
                return(false);
            }
            System.Management.Automation.VariablePath variablePath = ast7.VariablePath;
            return(variablePath.UserPath.Equals(this.VariablePath.UserPath, StringComparison.OrdinalIgnoreCase) || (this.VariablePath.IsScript && this.VariablePath.UnqualifiedPath.Equals(variablePath.UnqualifiedPath, StringComparison.OrdinalIgnoreCase)));
        }
コード例 #2
0
        /// <summary>
        /// Derived classes override this method to return their
        /// particular type of scoped item.
        /// </summary>
        /// <param name="scope">
        /// The scope to look the item up in.
        /// </param>
        /// <param name="name">
        /// The name of the item to retrieve.
        /// </param>
        /// <param name="alias">
        /// The scope item that the derived class should return.
        /// </param>
        /// <returns>
        /// True if the scope item was found or false otherwise.
        /// </returns>
        protected override bool GetScopeItem(
            SessionStateScope scope,
            VariablePath name,
            out AliasInfo alias)
        {
            Diagnostics.Assert(!(name is FunctionLookupPath),
                               "name was scanned incorrect if we get here and it is a FunctionLookupPath");

            bool result = true;

            alias = scope.GetAlias(name.QualifiedName);

            // If the alias is private and the lookup scope
            // isn't the current scope, claim that the alias
            // doesn't exist so that the lookup continues.

            if (alias == null ||
                ((alias.Options & ScopedItemOptions.Private) != 0 &&
                 scope != sessionState.CurrentScope))
            {
                result = false;
            }

            return(result);
        }
コード例 #3
0
        protected override bool GetScopeItem(SessionStateScope scope, VariablePath name, out PSVariable variable)
        {
            bool flag = true;

            variable = scope.GetVariable(name.QualifiedName, this._origin);
            return(((variable != null) && (!variable.IsPrivate || (scope == base.sessionState.CurrentScope))) && flag);
        }
コード例 #4
0
        internal object GetVariableValue(VariablePath path, object defaultValue)
        {
            CmdletProviderContext context;
            SessionStateScope     scope;

            return(this._engineSessionState.GetVariableValue(path, out context, out scope) ?? defaultValue);
        }
コード例 #5
0
ファイル: VariableOps.cs プロジェクト: rsumner31/powershell
        internal static PSReference GetVariableAsRef(VariablePath variablePath, ExecutionContext executionContext, Type staticType)
        {
            Diagnostics.Assert(variablePath.IsVariable, "calller to verify varpath is a variable.");

            SessionStateInternal sessionState = executionContext.EngineSessionState;
            CommandOrigin        origin       = sessionState.CurrentScope.ScopeOrigin;

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

            if (var == null)
            {
                throw InterpreterError.NewInterpreterException(variablePath, typeof(RuntimeException), null,
                                                               "NonExistingVariableReference",
                                                               ParserStrings.NonExistingVariableReference);
            }

            object value = var.Value;

            if (staticType == null && value != null)
            {
                value = PSObject.Base(value);
                if (value != null)
                {
                    staticType = value.GetType();
                }
            }
            if (staticType == null)
            {
                var declaredType = var.Attributes.OfType <ArgumentTypeConverterAttribute>().FirstOrDefault();
                staticType = declaredType != null ? declaredType.TargetType : typeof(LanguagePrimitives.Null);
            }

            return(PSReference.CreateInstance(var, staticType));
        }
コード例 #6
0
        protected override bool GetScopeItem(SessionStateScope scope, VariablePath name, out AliasInfo alias)
        {
            bool flag = true;

            alias = scope.GetAlias(name.QualifiedName);
            return(((alias != null) && (((alias.Options & ScopedItemOptions.Private) == ScopedItemOptions.None) || (scope == base.sessionState.CurrentScope))) && flag);
        }
コード例 #7
0
ファイル: VariableOps.cs プロジェクト: nickchal/pash
 private static PSReference GetVariableAsRef(VariablePath variablePath, ExecutionContext executionContext, Type staticType)
 {
     SessionStateScope scope;
     SessionStateInternal engineSessionState = executionContext.EngineSessionState;
     CommandOrigin scopeOrigin = engineSessionState.CurrentScope.ScopeOrigin;
     PSVariable variable = engineSessionState.GetVariableItem(variablePath, out scope, scopeOrigin);
     if (variable == null)
     {
         throw InterpreterError.NewInterpreterException(variablePath, typeof(RuntimeException), null, "NonExistingVariableReference", ParserStrings.NonExistingVariableReference, new object[0]);
     }
     object obj2 = variable.Value;
     if ((staticType == null) && (obj2 != null))
     {
         obj2 = PSObject.Base(obj2);
         if (obj2 != null)
         {
             staticType = obj2.GetType();
         }
     }
     if (staticType == null)
     {
         ArgumentTypeConverterAttribute attribute = variable.Attributes.OfType<ArgumentTypeConverterAttribute>().FirstOrDefault<ArgumentTypeConverterAttribute>();
         staticType = (attribute != null) ? attribute.TargetType : typeof(LanguagePrimitives.Null);
     }
     return PSReference.CreateInstance(variable, staticType);
 }
コード例 #8
0
        private static PSReference GetVariableAsRef(VariablePath variablePath, ExecutionContext executionContext, Type staticType)
        {
            SessionStateScope    scope;
            SessionStateInternal engineSessionState = executionContext.EngineSessionState;
            CommandOrigin        scopeOrigin        = engineSessionState.CurrentScope.ScopeOrigin;
            PSVariable           variable           = engineSessionState.GetVariableItem(variablePath, out scope, scopeOrigin);

            if (variable == null)
            {
                throw InterpreterError.NewInterpreterException(variablePath, typeof(RuntimeException), null, "NonExistingVariableReference", ParserStrings.NonExistingVariableReference, new object[0]);
            }
            object obj2 = variable.Value;

            if ((staticType == null) && (obj2 != null))
            {
                obj2 = PSObject.Base(obj2);
                if (obj2 != null)
                {
                    staticType = obj2.GetType();
                }
            }
            if (staticType == null)
            {
                ArgumentTypeConverterAttribute attribute = variable.Attributes.OfType <ArgumentTypeConverterAttribute>().FirstOrDefault <ArgumentTypeConverterAttribute>();
                staticType = (attribute != null) ? attribute.TargetType : typeof(LanguagePrimitives.Null);
            }
            return(PSReference.CreateInstance(variable, staticType));
        }
コード例 #9
0
ファイル: VariableOps.cs プロジェクト: rsumner31/powershell
        internal static object GetVariableValue(VariablePath variablePath, ExecutionContext executionContext, VariableExpressionAst varAst)
        {
            if (!variablePath.IsVariable)
            {
                CmdletProviderContext contextOut;
                SessionStateScope     scopeOut;
                SessionStateInternal  ss = executionContext.EngineSessionState;
                return(ss.GetVariableValueFromProvider(variablePath, out contextOut, out scopeOut, ss.CurrentScope.ScopeOrigin));
            }

            SessionStateInternal sessionState = executionContext.EngineSessionState;
            CommandOrigin        origin       = sessionState.CurrentScope.ScopeOrigin;

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

            if (var != null)
            {
                return(var.Value);
            }

            if (sessionState.ExecutionContext._debuggingMode > 0)
            {
                sessionState.ExecutionContext.Debugger.CheckVariableRead(variablePath.UnqualifiedPath);
            }

            if (ThrowStrictModeUndefinedVariable(executionContext, varAst))
            {
                throw InterpreterError.NewInterpreterException(variablePath.UserPath, typeof(RuntimeException),
                                                               varAst.Extent, "VariableIsUndefined", ParserStrings.VariableIsUndefined, variablePath.UserPath);
            }

            return(null);
        }
コード例 #10
0
        protected override bool GetScopeItem(SessionStateScope scope, VariablePath path, out FunctionInfo script)
        {
            bool flag = true;

            this.name = path.IsFunction ? path.UnqualifiedPath : path.QualifiedName;
            script    = scope.GetFunction(this.name);
            if (script != null)
            {
                bool       flag2;
                FilterInfo info = script as FilterInfo;
                if (info != null)
                {
                    flag2 = (info.Options & ScopedItemOptions.Private) != ScopedItemOptions.None;
                }
                else
                {
                    flag2 = (script.Options & ScopedItemOptions.Private) != ScopedItemOptions.None;
                }
                if (flag2 && (scope != base.sessionState.CurrentScope))
                {
                    return(false);
                }
                SessionState.ThrowIfNotVisible(this._origin, script);
                return(flag);
            }
            return(false);
        }
コード例 #11
0
 public FunctionScopeItemSearcher(
     SessionStateInternal sessionState,
     VariablePath lookupPath,
     CommandOrigin origin) : base(sessionState, lookupPath)
 {
     _origin = origin;
 }
コード例 #12
0
        /// <summary>
        /// Derived classes override this method to return their
        /// particular type of scoped item.
        /// </summary>
        /// <param name="scope">
        /// The scope to look the item up in.
        /// </param>
        /// <param name="name">
        /// The name of the item to retrieve.
        /// </param>
        /// <param name="variable">
        /// The scope item that the derived class should return.
        /// </param>
        /// <returns>
        /// True if the scope item was found or false otherwise.
        /// </returns>
        protected override bool GetScopeItem(
            SessionStateScope scope,
            VariablePath name,
            out PSVariable variable)
        {
            Diagnostics.Assert(!(name is FunctionLookupPath),
                               "name was scanned incorrect if we get here and it is a FunctionLookupPath");

            bool result = true;

            variable = scope.GetVariable(name.QualifiedName, _origin);

            // If the variable is private and the lookup scope
            // isn't the current scope, claim that the variable
            // doesn't exist so that the lookup continues.

            if (variable == null ||
                (variable.IsPrivate &&
                 scope != sessionState.CurrentScope))
            {
                result = false;
            }

            return(result);
        }
コード例 #13
0
 public VariableExpressionAst(IScriptExtent extent, System.Management.Automation.VariablePath variablePath, bool splatted) : base(extent)
 {
     this._tupleIndex = -1;
     if (variablePath == null)
     {
         throw PSTraceSource.NewArgumentNullException("variablePath");
     }
     this.VariablePath = variablePath;
     this.Splatted     = splatted;
 }
コード例 #14
0
 private SessionStateProviderBase GetSessionStateProvider(VariablePath variablePath)
 {
     PSDriveInfo driveInfo;
     if (!ExecutionContext.SessionState.Drive.TryGet(variablePath.DriveName, out driveInfo))
     {
         return null;
     }
     return ExecutionContext.SessionState.Provider.GetInstance(driveInfo.Provider.Name)
         as SessionStateProviderBase;
 }
コード例 #15
0
        protected override bool GetScopeItem(SessionStateScope scope, VariablePath name, out PSDriveInfo drive)
        {
            bool flag = true;

            drive = scope.GetDrive(name.DriveName);
            if (drive == null)
            {
                flag = false;
            }
            return(flag);
        }
コード例 #16
0
        internal VariablePath CloneAndSetLocal()
        {
            Debug.Assert(IsUnscopedVariable, "Special method to clone, input must be unqualified");

            VariablePath result = new VariablePath();

            result._userPath        = _userPath;
            result._unqualifiedPath = _unqualifiedPath;
            result._flags           = VariablePathFlags.Local | VariablePathFlags.Variable;
            return(result);
        }
コード例 #17
0
        private static object SetVariableValue(VariablePath variablePath, object value, ExecutionContext executionContext, AttributeBaseAst[] attributeAsts)
        {
            SessionStateScope    scope;
            SessionStateInternal engineSessionState = executionContext.EngineSessionState;
            CommandOrigin        scopeOrigin        = engineSessionState.CurrentScope.ScopeOrigin;

            if (!variablePath.IsVariable)
            {
                engineSessionState.SetVariable(variablePath, value, true, scopeOrigin);
                return(value);
            }
            if (executionContext.PSDebugTraceLevel > 0)
            {
                executionContext.Debugger.TraceVariableSet(variablePath.UnqualifiedPath, value);
            }
            if (variablePath.IsUnscopedVariable)
            {
                variablePath = variablePath.CloneAndSetLocal();
            }
            PSVariable newValue = engineSessionState.GetVariableItem(variablePath, out scope, scopeOrigin);

            if (newValue == null)
            {
                Collection <Attribute> attributes = (attributeAsts == null) ? new Collection <Attribute>() : GetAttributeCollection(attributeAsts);
                newValue = new PSVariable(variablePath.UnqualifiedPath, value, ScopedItemOptions.None, attributes);
                engineSessionState.SetVariable(variablePath, newValue, false, scopeOrigin);
                if (executionContext._debuggingMode > 0)
                {
                    executionContext.Debugger.CheckVariableWrite(variablePath.UnqualifiedPath);
                }
                return(value);
            }
            if (attributeAsts != null)
            {
                newValue.Attributes.Clear();
                Collection <Attribute> attributeCollection = GetAttributeCollection(attributeAsts);
                value = PSVariable.TransformValue(attributeCollection, value);
                if (!PSVariable.IsValidValue(attributeCollection, value))
                {
                    ValidationMetadataException exception = new ValidationMetadataException("ValidateSetFailure", null, Metadata.InvalidValueFailure, new object[] { newValue.Name, (value != null) ? value.ToString() : "" });
                    throw exception;
                }
                newValue.SetValueRaw(value, true);
                newValue.AddParameterAttributesNoChecks(attributeCollection);
                if (executionContext._debuggingMode > 0)
                {
                    executionContext.Debugger.CheckVariableWrite(variablePath.UnqualifiedPath);
                }
                return(value);
            }
            newValue.Value = value;
            return(value);
        }
コード例 #18
0
 internal ScopedItemSearcher(SessionStateInternal sessionState, VariablePath lookupPath)
 {
     if (sessionState == null)
     {
         throw PSTraceSource.NewArgumentNullException("sessionState");
     }
     if (lookupPath == null)
     {
         throw PSTraceSource.NewArgumentNullException("lookupPath");
     }
     this.sessionState = sessionState;
     this.lookupPath   = lookupPath;
     this.InitializeScopeEnumerator();
 }
コード例 #19
0
        /// <summary>
        /// Get a variable out of session state. This interface supports
        /// the scope specifiers like "global:foobar" 
        /// </summary>
        /// 
        /// <param name="name">
        /// name of variable to look up
        /// </param>
        /// 
        /// <param name="origin">
        /// Origin of the command making this request.
        /// </param>
        /// 
        /// <returns>
        /// The specified variable.
        /// </returns>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="name"/> is null.
        /// </exception>
        /// 
        internal PSVariable GetVariable(string name, CommandOrigin origin)
        {
            if (name == null)
            {
                throw PSTraceSource.NewArgumentNullException("name");
            }

            VariablePath variablePath = new VariablePath(name, VariablePathFlags.Variable | VariablePathFlags.Unqualified);
            SessionStateScope scope = null;

            PSVariable resultItem = GetVariableItem(variablePath, out scope, origin);

            return resultItem;
        } // GetVariable
コード例 #20
0
        /// <summary>
        /// Derived classes override this method to return their
        /// particular type of scoped item.
        /// </summary>
        /// <param name="scope">
        /// The scope to look the item up in.
        /// </param>
        /// <param name="path">
        /// The name of the item to retrieve.
        /// </param>
        /// <param name="script">
        /// The scope item that the derived class should return.
        /// </param>
        /// <returns>
        /// True if the scope item was found or false otherwise.
        /// </returns>
        protected override bool GetScopeItem(
            SessionStateScope scope,
            VariablePath path,
            out FunctionInfo script)
        {
            Diagnostics.Assert(path is FunctionLookupPath,
                               "name was scanned incorrect if we get here and it is not a FunctionLookupPath");

            bool result = true;

            _name = path.IsFunction ? path.UnqualifiedPath : path.QualifiedName;

            script = scope.GetFunction(_name);

            if (script != null)
            {
                bool       isPrivate;
                FilterInfo filterInfo = script as FilterInfo;
                if (filterInfo != null)
                {
                    isPrivate = (filterInfo.Options & ScopedItemOptions.Private) != 0;
                }
                else
                {
                    isPrivate = (script.Options & ScopedItemOptions.Private) != 0;
                }

                // If the function is private and the lookup scope
                // isn't the current scope, claim that the function
                // doesn't exist so that the lookup continues.

                if (isPrivate &&
                    scope != sessionState.CurrentScope)
                {
                    result = false;
                }
                else
                {
                    // Now check the visibility of the variable...
                    SessionState.ThrowIfNotVisible(_origin, script);
                }
            }
            else
            {
                result = false;
            }

            return(result);
        }
コード例 #21
0
        internal T GetEnumPreference <T>(VariablePath preferenceVariablePath, T defaultPref, out bool defaultUsed)
        {
            CmdletProviderContext context = null;
            SessionStateScope     scope   = null;
            object obj2 = this.EngineSessionState.GetVariableValue(preferenceVariablePath, out context, out scope);

            if (obj2 is T)
            {
                if (obj2 is ActionPreference)
                {
                    ActionPreference o = (ActionPreference)obj2;
                    if (o == ActionPreference.Ignore)
                    {
                        this.EngineSessionState.SetVariableValue(preferenceVariablePath.UserPath, defaultPref);
                        throw new NotSupportedException(StringUtil.Format(ErrorPackage.UnsupportedPreferenceError, o));
                    }
                }
                T local = (T)obj2;
                defaultUsed = false;
                return(local);
            }
            defaultUsed = true;
            T local2 = defaultPref;

            if (obj2 != null)
            {
                try
                {
                    string str2 = obj2 as string;
                    if (str2 != null)
                    {
                        local2      = (T)Enum.Parse(typeof(T), str2, true);
                        defaultUsed = false;
                        return(local2);
                    }
                    local2      = (T)obj2;
                    defaultUsed = false;
                }
                catch (InvalidCastException)
                {
                }
                catch (ArgumentException)
                {
                }
            }
            return(local2);
        }
コード例 #22
0
        /// <summary>
        /// Constructs a scoped item searcher.
        /// </summary>
        /// <param name="sessionState">
        /// The state of the engine instance to enumerate through the scopes.
        /// </param>
        /// <param name="lookupPath">
        /// The parsed name of the item to lookup.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="sessionState"/> or <paramref name="lookupPath"/>
        /// is null.
        /// </exception>
        internal ScopedItemSearcher(
            SessionStateInternal sessionState,
            VariablePath lookupPath)
        {
            if (sessionState is null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(sessionState));
            }

            if (lookupPath is null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(lookupPath));
            }

            this.sessionState = sessionState;
            _lookupPath       = lookupPath;
            InitializeScopeEnumerator();
        }
コード例 #23
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);
         }
     }
 }
コード例 #24
0
        /// <summary>
        /// Derived classes override this method to return their
        /// particular type of scoped item.
        /// </summary>
        ///
        /// <param name="scope">
        /// The scope to look the item up in.
        /// </param>
        ///
        /// <param name="name">
        /// The name of the item to retrieve.
        /// </param>
        ///
        /// <param name="drive">
        /// The scope item that the derived class should return.
        /// </param>
        ///
        /// <returns>
        /// True if the scope item was found or false otherwise.
        /// </returns>
        ///
        protected override bool GetScopeItem(
            SessionStateScope scope,
            VariablePath name,
            out PSDriveInfo drive)
        {
            Diagnostics.Assert(!(name is FunctionLookupPath),
                               "name was scanned incorrect if we get here and it is a FunctionLookupPath");

            bool result = true;

            drive = scope.GetDrive(name.DriveName);

            if (drive == null)
            {
                result = false;
            }
            return(result);
        }
コード例 #25
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);
                }
            }
        }
コード例 #26
0
        internal bool GetBooleanPreference(VariablePath preferenceVariablePath, bool defaultPref, out bool defaultUsed)
        {
            CmdletProviderContext context = null;
            SessionStateScope     scope   = null;
            object valueToConvert         = this.EngineSessionState.GetVariableValue(preferenceVariablePath, out context, out scope);

            if (valueToConvert == null)
            {
                defaultUsed = true;
                return(defaultPref);
            }
            bool result = defaultPref;

            defaultUsed = !LanguagePrimitives.TryConvertTo <bool>(valueToConvert, out result);
            if (!defaultUsed)
            {
                return(result);
            }
            return(defaultPref);
        }
コード例 #27
0
        /// <summary>
        /// Binds the parameters to local variables in the function scope.
        /// </summary>
        /// <param name="name">
        ///     The name of the parameter to bind the value to.
        /// </param>
        /// <param name="value">
        ///     The value to bind to the parameter. It should be assumed by
        ///     derived classes that the proper type coercion has already taken
        ///     place and that any prerequisite metadata has been satisfied.
        /// </param>
        /// <param name="parameterMetadata"></param>
        internal override void BindParameter(string name, object value, CompiledCommandParameter parameterMetadata)
        {
            if (value == AutomationNull.Value || value == UnboundParameter.Value)
            {
                value = null;
            }

            Diagnostics.Assert(name != null, "The caller should verify that name is not null");

            var varPath = new VariablePath(name, VariablePathFlags.Variable);

            // If the parameter was allocated in the LocalsTuple, we can avoid creating a PSVariable,
            if (LocalScope != null &&
                varPath.IsAnyLocal() &&
                LocalScope.TrySetLocalParameterValue(varPath.UnqualifiedPath, CopyMutableValues(value)))
            {
                return;
            }

            // Otherwise we'll fall through and enter a new PSVariable in the current scope.  This
            // is what normally happens when dotting (though the above may succeed if a parameter name
            // was an automatic variable like $PSBoundParameters.

            // First we need to make a variable instance and apply
            // any attributes from the script.

            PSVariable variable = new PSVariable(varPath.UnqualifiedPath, value,
                                                 varPath.IsPrivate ? ScopedItemOptions.Private : ScopedItemOptions.None);

            Context.EngineSessionState.SetVariable(varPath, variable, false, CommandOrigin.Internal);
            RuntimeDefinedParameter runtimeDefinedParameter;

            if (Script.RuntimeDefinedParameters.TryGetValue(name, out runtimeDefinedParameter))
            {
                // The attributes have already been checked and conversions run, so it is wrong
                // to do so again.
                variable.AddParameterAttributesNoChecks(runtimeDefinedParameter.Attributes);
            }
        }
コード例 #28
0
 public DriveScopeItemSearcher(
     SessionStateInternal sessionState,
     VariablePath lookupPath) : base(sessionState, lookupPath)
 {
 }
コード例 #29
0
ファイル: CommandDiscovery.cs プロジェクト: nickchal/pash
 internal static PSModuleAutoLoadingPreference GetCommandDiscoveryPreference(ExecutionContext context, VariablePath variablePath, string environmentVariable)
 {
     if (context == null)
     {
         throw PSTraceSource.NewArgumentNullException("context");
     }
     object variableValue = context.GetVariableValue(variablePath);
     if (variableValue != null)
     {
         return LanguagePrimitives.ConvertTo<PSModuleAutoLoadingPreference>(variableValue);
     }
     string str = Environment.GetEnvironmentVariable(environmentVariable);
     if (!string.IsNullOrEmpty(str))
     {
         return LanguagePrimitives.ConvertTo<PSModuleAutoLoadingPreference>(str);
     }
     return PSModuleAutoLoadingPreference.All;
 }
コード例 #30
0
ファイル: SpecialVariables.cs プロジェクト: 40a/PowerShell
 internal static bool IsImplicitVariableAccessibleInClassMethod(VariablePath variablePath)
 {
     return s_classMethodsAccessibleVariables.Contains(variablePath.UserPath);
 }
コード例 #31
0
ファイル: VariableOps.cs プロジェクト: 40a/PowerShell
        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;
        }
コード例 #32
0
ファイル: VariableOps.cs プロジェクト: nickchal/pash
 private static object SetVariableValue(VariablePath variablePath, object value, ExecutionContext executionContext, AttributeBaseAst[] attributeAsts)
 {
     SessionStateScope scope;
     SessionStateInternal engineSessionState = executionContext.EngineSessionState;
     CommandOrigin scopeOrigin = engineSessionState.CurrentScope.ScopeOrigin;
     if (!variablePath.IsVariable)
     {
         engineSessionState.SetVariable(variablePath, value, true, scopeOrigin);
         return value;
     }
     if (executionContext.PSDebugTraceLevel > 0)
     {
         executionContext.Debugger.TraceVariableSet(variablePath.UnqualifiedPath, value);
     }
     if (variablePath.IsUnscopedVariable)
     {
         variablePath = variablePath.CloneAndSetLocal();
     }
     PSVariable newValue = engineSessionState.GetVariableItem(variablePath, out scope, scopeOrigin);
     if (newValue == null)
     {
         Collection<Attribute> attributes = (attributeAsts == null) ? new Collection<Attribute>() : GetAttributeCollection(attributeAsts);
         newValue = new PSVariable(variablePath.UnqualifiedPath, value, ScopedItemOptions.None, attributes);
         engineSessionState.SetVariable(variablePath, newValue, false, scopeOrigin);
         if (executionContext._debuggingMode > 0)
         {
             executionContext.Debugger.CheckVariableWrite(variablePath.UnqualifiedPath);
         }
         return value;
     }
     if (attributeAsts != null)
     {
         newValue.Attributes.Clear();
         Collection<Attribute> attributeCollection = GetAttributeCollection(attributeAsts);
         value = PSVariable.TransformValue(attributeCollection, value);
         if (!PSVariable.IsValidValue(attributeCollection, value))
         {
             ValidationMetadataException exception = new ValidationMetadataException("ValidateSetFailure", null, Metadata.InvalidValueFailure, new object[] { newValue.Name, (value != null) ? value.ToString() : "" });
             throw exception;
         }
         newValue.SetValueRaw(value, true);
         newValue.AddParameterAttributesNoChecks(attributeCollection);
         if (executionContext._debuggingMode > 0)
         {
             executionContext.Debugger.CheckVariableWrite(variablePath.UnqualifiedPath);
         }
         return value;
     }
     newValue.Value = value;
     return value;
 }
コード例 #33
0
 public VariableExpressionAst(IScriptExtent extent, VariablePath variablePath, bool splatted)
     : base(extent)
 {
     this.VariablePath = variablePath;
 }
コード例 #34
0
ファイル: SessionStateInternal.cs プロジェクト: nickchal/pash
 internal object GetVariableValueAtScope(string name, string scopeID)
 {
     if (name == null)
     {
         throw PSTraceSource.NewArgumentNullException("name");
     }
     VariablePath path = new VariablePath(name);
     SessionStateScope scopeByID = null;
     scopeByID = this.GetScopeByID(scopeID);
     object obj2 = null;
     if (path.IsVariable)
     {
         obj2 = scopeByID.GetVariable(path.QualifiedName);
     }
     else
     {
         PSDriveInfo drive = scopeByID.GetDrive(path.DriveName);
         if (drive != null)
         {
             CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext) {
                 Drive = drive
             };
             Collection<IContentReader> contentReader = null;
             try
             {
                 contentReader = this.GetContentReader(new string[] { path.QualifiedName }, context);
             }
             catch (ItemNotFoundException)
             {
                 return null;
             }
             catch (System.Management.Automation.DriveNotFoundException)
             {
                 return null;
             }
             catch (ProviderNotFoundException)
             {
                 return null;
             }
             catch (NotImplementedException exception)
             {
                 ProviderInfo provider = null;
                 this.Globber.GetProviderPath(path.QualifiedName, out provider);
                 throw this.NewProviderInvocationException("ProviderCannotBeUsedAsVariable", SessionStateStrings.ProviderCannotBeUsedAsVariable, provider, path.QualifiedName, exception, false);
             }
             catch (NotSupportedException exception2)
             {
                 ProviderInfo info3 = null;
                 this.Globber.GetProviderPath(path.QualifiedName, out info3);
                 throw this.NewProviderInvocationException("ProviderCannotBeUsedAsVariable", SessionStateStrings.ProviderCannotBeUsedAsVariable, info3, path.QualifiedName, exception2, false);
             }
             if ((contentReader == null) || (contentReader.Count == 0))
             {
                 return null;
             }
             if (contentReader.Count > 1)
             {
                 foreach (IContentReader reader in contentReader)
                 {
                     reader.Close();
                 }
                 PSArgumentException e = PSTraceSource.NewArgumentException("path", "SessionStateStrings", "VariablePathResolvedToMultiple", new object[] { name });
                 ProviderInfo info4 = null;
                 this.Globber.GetProviderPath(path.QualifiedName, out info4);
                 throw this.NewProviderInvocationException("ProviderVariableSyntaxInvalid", SessionStateStrings.ProviderVariableSyntaxInvalid, info4, path.QualifiedName, e);
             }
             IContentReader reader2 = contentReader[0];
             try
             {
                 IList list = reader2.Read(-1L);
                 if (list != null)
                 {
                     if (list.Count == 0)
                     {
                         obj2 = null;
                     }
                     else if (list.Count == 1)
                     {
                         obj2 = list[0];
                     }
                     else
                     {
                         obj2 = list;
                     }
                 }
             }
             catch (Exception exception4)
             {
                 ProviderInfo info5 = null;
                 this.Globber.GetProviderPath(path.QualifiedName, out info5);
                 CommandProcessorBase.CheckForSevereException(exception4);
                 ProviderInvocationException exception5 = new ProviderInvocationException("ProviderContentReadError", SessionStateStrings.ProviderContentReadError, info5, path.QualifiedName, exception4);
                 throw exception5;
             }
             finally
             {
                 reader2.Close();
             }
         }
     }
     if (obj2 != null)
     {
         PSVariable variable = obj2 as PSVariable;
         if (variable != null)
         {
             return variable.Value;
         }
         try
         {
             DictionaryEntry entry = (DictionaryEntry) obj2;
             obj2 = entry.Value;
         }
         catch (InvalidCastException)
         {
         }
     }
     return obj2;
 }
コード例 #35
0
ファイル: SessionStateInternal.cs プロジェクト: nickchal/pash
 internal PSVariable GetVariableAtScope(string name, string scopeID)
 {
     if (name == null)
     {
         throw PSTraceSource.NewArgumentNullException("name");
     }
     VariablePath path = new VariablePath(name);
     SessionStateScope scopeByID = null;
     scopeByID = this.GetScopeByID(scopeID);
     PSVariable variable = null;
     if (path.IsVariable)
     {
         variable = scopeByID.GetVariable(path.QualifiedName);
     }
     return variable;
 }
コード例 #36
0
ファイル: SessionStateInternal.cs プロジェクト: nickchal/pash
 internal object SetVariable(VariablePath variablePath, object newValue, bool asValue, bool force, CommandOrigin origin)
 {
     if (variablePath == null)
     {
         throw PSTraceSource.NewArgumentNullException("variablePath");
     }
     CmdletProviderContext context = null;
     SessionStateScope currentScope = null;
     if (variablePath.IsVariable)
     {
         if (variablePath.IsLocal || variablePath.IsUnscopedVariable)
         {
             currentScope = this.currentScope;
         }
         else if (variablePath.IsScript)
         {
             currentScope = this.currentScope.ScriptScope;
         }
         else if (variablePath.IsGlobal)
         {
             currentScope = this._globalScope;
         }
         else if (variablePath.IsPrivate)
         {
             currentScope = this.currentScope;
         }
         PSVariable variable = currentScope.SetVariable(variablePath.QualifiedName, newValue, asValue, force, this, origin, false);
         if (variablePath.IsPrivate && (variable != null))
         {
             variable.Options |= ScopedItemOptions.Private;
         }
         return variable;
     }
     this.GetVariableValue(variablePath, out context, out currentScope);
     Collection<IContentWriter> contentWriter = null;
     try
     {
         if (context != null)
         {
             try
             {
                 CmdletProviderContext context2 = new CmdletProviderContext(context);
                 this.ClearContent(new string[] { variablePath.QualifiedName }, context2);
             }
             catch (NotSupportedException)
             {
             }
             catch (ItemNotFoundException)
             {
             }
             contentWriter = this.GetContentWriter(new string[] { variablePath.QualifiedName }, context);
             context.ThrowFirstErrorOrDoNothing(true);
         }
         else
         {
             try
             {
                 this.ClearContent(new string[] { variablePath.QualifiedName }, false, false);
             }
             catch (NotSupportedException)
             {
             }
             catch (ItemNotFoundException)
             {
             }
             contentWriter = this.GetContentWriter(new string[] { variablePath.QualifiedName }, false, false);
         }
     }
     catch (NotImplementedException exception)
     {
         ProviderInfo provider = null;
         this.Globber.GetProviderPath(variablePath.QualifiedName, out provider);
         throw this.NewProviderInvocationException("ProviderCannotBeUsedAsVariable", SessionStateStrings.ProviderCannotBeUsedAsVariable, provider, variablePath.QualifiedName, exception, false);
     }
     catch (NotSupportedException exception2)
     {
         ProviderInfo info2 = null;
         this.Globber.GetProviderPath(variablePath.QualifiedName, out info2);
         throw this.NewProviderInvocationException("ProviderCannotBeUsedAsVariable", SessionStateStrings.ProviderCannotBeUsedAsVariable, info2, variablePath.QualifiedName, exception2, false);
     }
     if ((contentWriter == null) || (contentWriter.Count == 0))
     {
         ItemNotFoundException exception3 = new ItemNotFoundException(variablePath.QualifiedName, "PathNotFound", SessionStateStrings.PathNotFound);
         throw exception3;
     }
     if (contentWriter.Count > 1)
     {
         foreach (IContentWriter writer in contentWriter)
         {
             writer.Close();
         }
         PSArgumentException e = PSTraceSource.NewArgumentException("path", "SessionStateStrings", "VariablePathResolvedToMultiple", new object[] { variablePath.QualifiedName });
         ProviderInfo info3 = null;
         this.Globber.GetProviderPath(variablePath.QualifiedName, out info3);
         throw this.NewProviderInvocationException("ProviderVariableSyntaxInvalid", SessionStateStrings.ProviderVariableSyntaxInvalid, info3, variablePath.QualifiedName, e);
     }
     IContentWriter writer2 = contentWriter[0];
     IList content = newValue as IList;
     if (content == null)
     {
         content = new object[] { newValue };
     }
     try
     {
         writer2.Write(content);
     }
     catch (Exception exception5)
     {
         ProviderInfo info4 = null;
         this.Globber.GetProviderPath(variablePath.QualifiedName, out info4);
         CommandProcessorBase.CheckForSevereException(exception5);
         ProviderInvocationException exception6 = new ProviderInvocationException("ProviderContentWriteError", SessionStateStrings.ProviderContentWriteError, info4, variablePath.QualifiedName, exception5);
         throw exception6;
     }
     finally
     {
         writer2.Close();
     }
     return null;
 }
コード例 #37
0
ファイル: SessionStateInternal.cs プロジェクト: nickchal/pash
 internal void SetVariableValue(string name, object newValue, CommandOrigin origin)
 {
     if (name == null)
     {
         throw PSTraceSource.NewArgumentNullException("name");
     }
     VariablePath variablePath = new VariablePath(name);
     this.SetVariable(variablePath, newValue, true, origin);
 }
コード例 #38
0
ファイル: SessionStateInternal.cs プロジェクト: nickchal/pash
 internal object SetVariable(VariablePath variablePath, object newValue, bool asValue, CommandOrigin origin)
 {
     return this.SetVariable(variablePath, newValue, asValue, false, origin);
 }
コード例 #39
0
ファイル: SessionStateInternal.cs プロジェクト: nickchal/pash
 internal object GetVariableValueFromProvider(VariablePath variablePath, out CmdletProviderContext context, out SessionStateScope scope, CommandOrigin origin)
 {
     scope = null;
     if (variablePath == null)
     {
         throw PSTraceSource.NewArgumentNullException("variablePath");
     }
     context = null;
     DriveScopeItemSearcher searcher = new DriveScopeItemSearcher(this, variablePath);
     object obj2 = null;
     if (searcher.MoveNext())
     {
         PSDriveInfo current = (PSDriveInfo)searcher.Current;
         if (current == null)
         {
             return obj2;
         }
         context = new CmdletProviderContext(this.ExecutionContext, origin);
         context.Drive = current;
         Collection<IContentReader> contentReader = null;
         try
         {
             contentReader = this.GetContentReader(new string[] { variablePath.QualifiedName }, context);
         }
         catch (ItemNotFoundException)
         {
             return obj2;
         }
         catch (System.Management.Automation.DriveNotFoundException)
         {
             return obj2;
         }
         catch (ProviderNotFoundException)
         {
             return obj2;
         }
         catch (NotImplementedException exception)
         {
             ProviderInfo provider = null;
             this.Globber.GetProviderPath(variablePath.QualifiedName, out provider);
             throw this.NewProviderInvocationException("ProviderCannotBeUsedAsVariable", SessionStateStrings.ProviderCannotBeUsedAsVariable, provider, variablePath.QualifiedName, exception, false);
         }
         catch (NotSupportedException exception2)
         {
             ProviderInfo info3 = null;
             this.Globber.GetProviderPath(variablePath.QualifiedName, out info3);
             throw this.NewProviderInvocationException("ProviderCannotBeUsedAsVariable", SessionStateStrings.ProviderCannotBeUsedAsVariable, info3, variablePath.QualifiedName, exception2, false);
         }
         if ((contentReader == null) || (contentReader.Count == 0))
         {
             return obj2;
         }
         if (contentReader.Count > 1)
         {
             foreach (IContentReader reader in contentReader)
             {
                 reader.Close();
             }
             PSArgumentException e = PSTraceSource.NewArgumentException("path", "SessionStateStrings", "VariablePathResolvedToMultiple", new object[] { variablePath.QualifiedName });
             ProviderInfo info4 = null;
             this.Globber.GetProviderPath(variablePath.QualifiedName, out info4);
             throw this.NewProviderInvocationException("ProviderVariableSyntaxInvalid", SessionStateStrings.ProviderVariableSyntaxInvalid, info4, variablePath.QualifiedName, e);
         }
         IContentReader reader2 = contentReader[0];
         try
         {
             IList list = reader2.Read(-1L);
             if (list == null)
             {
                 return obj2;
             }
             if (list.Count == 0)
             {
                 return null;
             }
             if (list.Count == 1)
             {
                 return list[0];
             }
             return list;
         }
         catch (Exception exception4)
         {
             ProviderInfo info5 = null;
             this.Globber.GetProviderPath(variablePath.QualifiedName, out info5);
             CommandProcessorBase.CheckForSevereException(exception4);
             ProviderInvocationException exception5 = new ProviderInvocationException("ProviderContentReadError", SessionStateStrings.ProviderContentReadError, info5, variablePath.QualifiedName, exception4);
             throw exception5;
         }
         finally
         {
             reader2.Close();
         }
     }
     return obj2;
 }
コード例 #40
0
ファイル: SessionStateInternal.cs プロジェクト: nickchal/pash
 internal void RemoveVariable(PSVariable variable, bool force)
 {
     if (variable == null)
     {
         throw PSTraceSource.NewArgumentNullException("variable");
     }
     VariablePath variablePath = new VariablePath(variable.Name);
     SessionStateScope scope = null;
     if (this.GetVariableItem(variablePath, out scope) != null)
     {
         scope.RemoveVariable(variablePath.QualifiedName, force);
     }
 }
コード例 #41
0
ファイル: SessionStateInternal.cs プロジェクト: nickchal/pash
 internal void RemoveVariableAtScope(PSVariable variable, string scopeID, bool force)
 {
     if (variable == null)
     {
         throw PSTraceSource.NewArgumentNullException("variable");
     }
     VariablePath path = new VariablePath(variable.Name);
     this.GetScopeByID(scopeID).RemoveVariable(path.QualifiedName, force);
 }
コード例 #42
0
ファイル: SessionStateInternal.cs プロジェクト: nickchal/pash
 internal object GetVariableValue(VariablePath variablePath, out CmdletProviderContext context, out SessionStateScope scope)
 {
     context = null;
     scope = null;
     object obj2 = null;
     if (variablePath.IsVariable)
     {
         PSVariable variableItem = this.GetVariableItem(variablePath, out scope);
         if (variableItem != null)
         {
             obj2 = variableItem.Value;
         }
         return obj2;
     }
     return this.GetVariableValueFromProvider(variablePath, out context, out scope, this.currentScope.ScopeOrigin);
 }
コード例 #43
0
ファイル: SessionStateInternal.cs プロジェクト: nickchal/pash
 internal PSVariable GetVariableItem(VariablePath variablePath, out SessionStateScope scope)
 {
     return this.GetVariableItem(variablePath, out scope, CommandOrigin.Internal);
 }
コード例 #44
0
ファイル: SessionStateInternal.cs プロジェクト: nickchal/pash
 internal object GetVariableValue(string name)
 {
     if (name == null)
     {
         throw PSTraceSource.NewArgumentNullException("name");
     }
     VariablePath variablePath = new VariablePath(name);
     CmdletProviderContext context = null;
     SessionStateScope scope = null;
     return this.GetVariableValue(variablePath, out context, out scope);
 }
コード例 #45
0
ファイル: VariableOps.cs プロジェクト: rsumner31/powershell
        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);
        }
コード例 #46
0
ファイル: VariableAnalysis.cs プロジェクト: nickchal/pash
 internal static string GetUnaliasedVariableName(VariablePath varPath)
 {
     return GetUnaliasedVariableName(varPath.UnqualifiedPath);
 }
コード例 #47
0
ファイル: VariableOps.cs プロジェクト: nickchal/pash
 internal static object GetVariableValue(VariablePath variablePath, ExecutionContext executionContext, VariableExpressionAst varAst)
 {
     SessionStateScope scope2;
     if (!variablePath.IsVariable)
     {
         CmdletProviderContext context;
         SessionStateScope scope;
         SessionStateInternal internal2 = executionContext.EngineSessionState;
         return internal2.GetVariableValueFromProvider(variablePath, out context, out scope, internal2.CurrentScope.ScopeOrigin);
     }
     SessionStateInternal engineSessionState = executionContext.EngineSessionState;
     CommandOrigin scopeOrigin = engineSessionState.CurrentScope.ScopeOrigin;
     PSVariable variable = engineSessionState.GetVariableItem(variablePath, out scope2, scopeOrigin);
     if (variable != null)
     {
         return variable.Value;
     }
     if (engineSessionState.ExecutionContext._debuggingMode > 0)
     {
         engineSessionState.ExecutionContext.Debugger.CheckVariableRead(variablePath.UnqualifiedPath);
     }
     if (ThrowStrictModeUndefinedVariable(executionContext, varAst))
     {
         throw InterpreterError.NewInterpreterException(variablePath.UserPath, typeof(RuntimeException), varAst.Extent, "VariableIsUndefined", ParserStrings.VariableIsUndefined, new object[] { variablePath.UserPath });
     }
     return null;
 }
コード例 #48
0
        /// <summary>
        /// The main processing loop of the command.
        /// </summary>
        /// 
        protected override void ProcessRecord()
        {
            string path = GetFilePath();

            if (path == null)
            {
                return;
            }

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

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

            string script = GetScript(path);
            if (script == null)
            {
                return;
            }

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

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

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

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

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

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

                throw ioe;
            }

            return;
        } // ProcessRecord
コード例 #49
0
 /// <summary>
 /// Derived classes override this method to return their
 /// particular type of scoped item.
 /// </summary>
 /// <param name="scope">
 /// The scope to look the item up in.
 /// </param>
 /// <param name="name">
 /// The name of the item to retrieve.
 /// </param>
 /// <param name="newCurrentItem">
 /// The scope item that the derived class should return.
 /// </param>
 /// <returns>
 /// True if the scope item was found or false otherwise.
 /// </returns>
 protected abstract bool GetScopeItem(
     SessionStateScope scope,
     VariablePath name,
     out T newCurrentItem);
コード例 #50
0
        internal static string GetUnaliasedVariableName(VariablePath varPath)
        {
            VariablePathFlags knownFlags = VariablePathFlags.None;
            string path = varPath.ToString();
            int currentCharIndex = 0;
            int lastScannedColon = -1;
            string candidateScope = null;
            string candidateScopeUpper = null;
            string unqualifiedPath;
            VariablePathFlags _flags = VariablePathFlags.None;
            VariablePathFlags candidateFlags = VariablePathFlags.Unqualified;

            if (varPath.IsDriveQualified)
            {
                knownFlags = VariablePathFlags.DriveQualified;
            }

        scanScope:
            switch (path[0])
            {
                case 'g':
                case 'G':
                    candidateScope = "lobal";
                    candidateScopeUpper = "LOBAL";
                    candidateFlags = VariablePathFlags.Global;
                    break;
                case 'l':
                case 'L':
                    candidateScope = "ocal";
                    candidateScopeUpper = "OCAL";
                    candidateFlags = VariablePathFlags.Local;
                    break;
                case 'p':
                case 'P':
                    candidateScope = "rivate";
                    candidateScopeUpper = "RIVATE";
                    candidateFlags = VariablePathFlags.Private;
                    break;
                case 's':
                case 'S':
                    candidateScope = "cript";
                    candidateScopeUpper = "CRIPT";
                    candidateFlags = VariablePathFlags.Script;
                    break;
                case 'v':
                case 'V':
                    if (knownFlags == VariablePathFlags.None)
                    {
                        // If we see 'variable:', our namespaceId will be empty, and                      
                        // we'll also need to scan for the scope again.                      
                        candidateScope = "ariable";
                        candidateScopeUpper = "ARIABLE";
                        candidateFlags = VariablePathFlags.Variable;
                    }
                    break;
            }

            if (candidateScope != null)
            {
                currentCharIndex += 1; // First character already matched.                  
                int j;
                for (j = 0; currentCharIndex < path.Length && j < candidateScope.Length; ++j, ++currentCharIndex)
                {
                    if (path[currentCharIndex] != candidateScope[j] && path[currentCharIndex] != candidateScopeUpper[j])
                    {
                        break;
                    }
                }

                if (j == candidateScope.Length &&
                    currentCharIndex < path.Length &&
                    path[currentCharIndex] == ':')
                {
                    if (_flags == VariablePathFlags.None)
                    {
                        _flags = VariablePathFlags.Variable;
                    }
                    _flags |= candidateFlags;
                    lastScannedColon = currentCharIndex;
                    currentCharIndex += 1;

                    // If saw 'variable:', we need to look for a scope after 'variable:'.                      
                    if (candidateFlags == VariablePathFlags.Variable)
                    {
                        knownFlags = VariablePathFlags.Variable;
                        candidateScope = candidateScopeUpper = null;
                        candidateFlags = VariablePathFlags.None;
                        goto scanScope;
                    }
                }
            }

            if (_flags == VariablePathFlags.None)
            {
                lastScannedColon = path.IndexOf(':', currentCharIndex);
                // No colon, or a colon as the first character means we have                  
                // a simple variable, otherwise it's a drive.                  
                if (lastScannedColon > 0)
                {
                    _flags = VariablePathFlags.DriveQualified;
                }
            }

            if (lastScannedColon == -1)
            {
                unqualifiedPath = path;
            }
            else
            {
                unqualifiedPath = path.Substring(lastScannedColon + 1);
            }

            if (_flags == VariablePathFlags.None)
            {
                _flags = VariablePathFlags.Unqualified | VariablePathFlags.Variable;
            }

            return GetUnaliasedVariableName(unqualifiedPath);
        }
コード例 #51
0
ファイル: VariableOps.cs プロジェクト: 40a/PowerShell
        internal static PSReference GetVariableAsRef(VariablePath variablePath, ExecutionContext executionContext, Type staticType)
        {
            Diagnostics.Assert(variablePath.IsVariable, "calller to verify varpath is a variable.");

            SessionStateInternal sessionState = executionContext.EngineSessionState;
            CommandOrigin origin = sessionState.CurrentScope.ScopeOrigin;

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

            if (var == null)
            {
                throw InterpreterError.NewInterpreterException(variablePath, typeof(RuntimeException), null,
                                                               "NonExistingVariableReference",
                                                               ParserStrings.NonExistingVariableReference);
            }

            object value = var.Value;
            if (staticType == null && value != null)
            {
                value = PSObject.Base(value);
                if (value != null)
                {
                    staticType = value.GetType();
                }
            }
            if (staticType == null)
            {
                var declaredType = var.Attributes.OfType<ArgumentTypeConverterAttribute>().FirstOrDefault();
                staticType = declaredType != null ? declaredType.TargetType : typeof(LanguagePrimitives.Null);
            }

            return PSReference.CreateInstance(var, staticType);
        }
コード例 #52
0
 public FunctionScopeItemSearcher(SessionStateInternal sessionState, VariablePath lookupPath, CommandOrigin origin) : base(sessionState, lookupPath)
 {
     this.name    = string.Empty;
     this._origin = origin;
 }
コード例 #53
0
 internal void SetVariable(VariablePath path, object newValue)
 {
     this._engineSessionState.SetVariable(path, newValue, true, CommandOrigin.Internal);
 }
コード例 #54
0
ファイル: SessionStateInternal.cs プロジェクト: nickchal/pash
 internal PSVariable GetVariableItem(VariablePath variablePath, out SessionStateScope scope, CommandOrigin origin)
 {
     scope = null;
     if (variablePath == null)
     {
         throw PSTraceSource.NewArgumentNullException("variablePath");
     }
     VariableScopeItemSearcher searcher = new VariableScopeItemSearcher(this, variablePath, origin);
     PSVariable current = null;
     if (searcher.MoveNext())
     {
         current = (PSVariable)searcher.Current;
         scope = searcher.CurrentLookupScope;
     }
     return current;
 }
コード例 #55
0
ファイル: VariablePath.cs プロジェクト: 40a/PowerShell
        internal VariablePath CloneAndSetLocal()
        {
            Debug.Assert(IsUnscopedVariable, "Special method to clone, input must be unqualified");

            VariablePath result = new VariablePath();
            result._userPath = _userPath;
            result._unqualifiedPath = _unqualifiedPath;
            result._flags = VariablePathFlags.Local | VariablePathFlags.Variable;
            return result;
        }
コード例 #56
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)
            {
                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);
        }
コード例 #57
0
ファイル: SessionStateInternal.cs プロジェクト: nickchal/pash
 internal void RemoveVariableAtScope(string name, string scopeID, bool force)
 {
     if (string.IsNullOrEmpty(name))
     {
         throw PSTraceSource.NewArgumentException("name");
     }
     VariablePath path = new VariablePath(name);
     SessionStateScope scopeByID = null;
     scopeByID = this.GetScopeByID(scopeID);
     if (path.IsVariable)
     {
         scopeByID.RemoveVariable(path.QualifiedName, force);
     }
     else
     {
         PSDriveInfo drive = scopeByID.GetDrive(path.DriveName);
         if (drive != null)
         {
             CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext) {
                 Drive = drive,
                 Force = force
             };
             this.RemoveItem(new string[] { path.QualifiedName }, false, context);
             context.ThrowFirstErrorOrDoNothing();
         }
     }
 }
コード例 #58
0
ファイル: SessionStateInternal.cs プロジェクト: nickchal/pash
 internal void RemoveVariable(string name, bool force)
 {
     if (name == null)
     {
         throw PSTraceSource.NewArgumentNullException("name");
     }
     VariablePath variablePath = new VariablePath(name);
     SessionStateScope scope = null;
     if (variablePath.IsVariable)
     {
         if (this.GetVariableItem(variablePath, out scope) != null)
         {
             scope.RemoveVariable(variablePath.QualifiedName, force);
         }
     }
     else
     {
         CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext) {
             Force = force
         };
         this.RemoveItem(new string[] { variablePath.QualifiedName }, false, context);
         context.ThrowFirstErrorOrDoNothing();
     }
 }
コード例 #59
0
ファイル: SpecialVariables.cs プロジェクト: yra40/PowerShell
 internal static bool IsImplicitVariableAccessibleInClassMethod(VariablePath variablePath)
 {
     return(s_classMethodsAccessibleVariables.Contains(variablePath.UserPath));
 }
コード例 #60
0
ファイル: SessionStateInternal.cs プロジェクト: nickchal/pash
 internal object SetVariable(PSVariable variable, bool force, CommandOrigin origin)
 {
     if ((variable == null) || string.IsNullOrEmpty(variable.Name))
     {
         throw PSTraceSource.NewArgumentException("variable");
     }
     VariablePath variablePath = new VariablePath(variable.Name, VariablePathFlags.Unqualified | VariablePathFlags.Variable);
     return this.SetVariable(variablePath, variable, false, force, origin);
 }