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);
        }
        /// <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);
        }
Example #3
0
        private static object GetUsingValue(MutableTuple tuple, int index, ExecutionContext context)
        {
            UsingResult usingValueFromTuple = GetUsingValueFromTuple(tuple, index);

            if (usingValueFromTuple != null)
            {
                return(usingValueFromTuple.Value);
            }
            for (SessionStateScope scope = context.EngineSessionState.CurrentScope; scope != null; scope = scope.Parent)
            {
                usingValueFromTuple = GetUsingValueFromTuple(scope.LocalsTuple, index);
                if (usingValueFromTuple != null)
                {
                    return(usingValueFromTuple.Value);
                }
                foreach (MutableTuple tuple2 in scope.DottedScopes)
                {
                    usingValueFromTuple = GetUsingValueFromTuple(tuple2, index);
                    if (usingValueFromTuple != null)
                    {
                        return(usingValueFromTuple.Value);
                    }
                }
            }
            throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "UsingWithoutInvokeCommand", ParserStrings.UsingWithoutInvokeCommand, new object[0]);
        }
        public bool MoveNext()
        {
            bool flag = true;

            if (!this.isInitialized)
            {
                this.InitializeScopeEnumerator();
            }
            while (this.scopeEnumerable.MoveNext())
            {
                T newCurrentItem = default(T);
                if (this.TryGetNewScopeItem(((IEnumerator <SessionStateScope>) this.scopeEnumerable).Current, out newCurrentItem))
                {
                    this.currentScope = ((IEnumerator <SessionStateScope>) this.scopeEnumerable).Current;
                    this.current      = newCurrentItem;
                    flag = true;
                    break;
                }
                flag = false;
                if (this.isSingleScopeLookup)
                {
                    flag = false;
                    break;
                }
            }
            return(flag);
        }
Example #5
0
 public void Set(string name, ScriptBlock function, string description = "")
 {
     var qualName = new SessionStateScope<FunctionInfo>.QualifiedName(name);
     var info = new FunctionInfo(qualName.UnqualifiedName, function);
     info.Description = description;
     _scope.Set(name, info, true, true);
 }
Example #6
0
        /// <summary>
        /// Removes a function from the function table.
        /// </summary>
        /// <param name="name">
        /// The name of the function to remove.
        /// </param>
        /// <param name="origin">
        /// THe origin of the caller of this API
        /// </param>
        /// <param name="force">
        /// If true, the function is removed even if it is ReadOnly.
        /// </param>
        /// <exception cref="ArgumentException">
        /// If <paramref name="name"/> is null or empty.
        /// </exception>
        /// <exception cref="SessionStateUnauthorizedAccessException">
        /// If the function is constant.
        /// </exception>
        internal void RemoveFunction(string name, bool force, CommandOrigin origin)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw PSTraceSource.NewArgumentException("name");
            }

            // Use the scope enumerator to find an existing function

            SessionStateScope scope = _currentScope;

            FunctionLookupPath path = new FunctionLookupPath(name);

            FunctionScopeItemSearcher searcher =
                new FunctionScopeItemSearcher(
                    this,
                    path,
                    origin);

            if (searcher.MoveNext())
            {
                scope = searcher.CurrentLookupScope;
            }

            scope.RemoveFunction(name, force);
        }
        /// <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);
        }
Example #8
0
        //actual constructor work, but hidden to not be used accidently in a stupid way
        private SessionState(SessionStateGlobal sessionStateGlobal, SessionState parent)
        {
            SessionStateGlobal = sessionStateGlobal;

            var parentAliasScope    = parent == null ? null : parent._aliasScope;
            var parentFunctionScope = parent == null ? null : parent._functionScope;
            var parentVariableScope = parent == null ? null : parent._variableScope;
            var parentDriveScope    = parent == null ? null : parent._driveScope;
            var parentModuleScope   = parent == null ? null : parent._moduleScope;
            var parentCmdletScope   = parent == null ? null : parent._cmdletScope;

            _aliasScope    = new SessionStateScope <AliasInfo>(this, parentAliasScope, SessionStateCategory.Alias);
            _functionScope = new SessionStateScope <FunctionInfo>(this, parentFunctionScope, SessionStateCategory.Function);
            _variableScope = new SessionStateScope <PSVariable>(this, parentVariableScope, SessionStateCategory.Variable);
            _driveScope    = new SessionStateScope <PSDriveInfo>(this, parentDriveScope, SessionStateCategory.Drive);
            _moduleScope   = new SessionStateScope <PSModuleInfo>(this, parentModuleScope, SessionStateCategory.Module);
            _cmdletScope   = new SessionStateScope <CmdletInfo>(this, parentCmdletScope, SessionStateCategory.Cmdlet);

            IsScriptScope = false;
            Function      = new FunctionIntrinsics(_functionScope);
            Alias         = new AliasIntrinsics(_aliasScope);

            Drive         = new DriveManagementIntrinsics(_driveScope);
            Path          = new PathIntrinsics(this);
            PSVariable    = new PSVariableIntrinsics(_variableScope);
            LoadedModules = new ModuleIntrinsics(_moduleScope);
            Cmdlet        = new CmdletIntrinsics(_cmdletScope);
        }
Example #9
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);
        }
        /// <summary>
        /// Gets an IEnumerable for the cmdlet table for a given scope.
        /// </summary>
        /// <param name="scopeID">
        /// A scope identifier that is either one of the "special" scopes like
        /// "global", "script", "local", or "private, or a numeric ID of a relative scope
        /// to the current scope.
        /// </param>
        /// <exception cref="ArgumentException">
        /// If <paramref name="scopeID"/> is less than zero, or not
        /// a number and not "script", "global", "local", or "private"
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        /// If <paramref name="scopeID"/> is less than zero or greater than the number of currently
        /// active scopes.
        /// </exception>
        internal IDictionary <string, List <CmdletInfo> > GetCmdletTableAtScope(string scopeID)
        {
            Dictionary <string, List <CmdletInfo> > result =
                new Dictionary <string, List <CmdletInfo> >(StringComparer.OrdinalIgnoreCase);

            SessionStateScope scope = GetScopeByID(scopeID);

            foreach (KeyValuePair <string, List <CmdletInfo> > entry in scope.CmdletTable)
            {
                // Make sure the alias isn't private or if it is that the current
                // scope is the same scope the alias was retrieved from.
                List <CmdletInfo> toBeAdded = new List <CmdletInfo>();
                foreach (CmdletInfo cmdletInfo in entry.Value)
                {
                    if ((cmdletInfo.Options & ScopedItemOptions.Private) == 0 ||
                        scope == _currentScope)
                    {
                        toBeAdded.Add(cmdletInfo);
                    }
                }

                result.Add(entry.Key, toBeAdded);
            }

            return(result);
        }
        internal PSVariable GetVariable(ExecutionContext context)
        {
            if (this._useConstantValue)
            {
                return((PSVariable)null);
            }
            SessionStateInternal engineSessionState = context.EngineSessionState;
            CommandOrigin        scopeOrigin        = engineSessionState.currentScope.ScopeOrigin;

            if (!this._variablePath.IsScopedItem)
            {
                SessionStateScope scope = (SessionStateScope)null;
                return(engineSessionState.GetVariableItem(this._variablePath, out scope, scopeOrigin));
            }
            PSVariable variable = engineSessionState.CurrentActivationRecord.GetVariable(this._activationRecordSlot, scopeOrigin);

            if (variable == null)
            {
                SessionStateScope scope;
                variable = engineSessionState.GetVariableItem(this._variablePath, out scope, scopeOrigin);
                if (variable != null)
                {
                    engineSessionState.CurrentActivationRecord.SetVariable(variable, scope, this._activationRecordSlot);
                }
                else if ((context.IsStrictVersion(2) || !this._inExpandableString && context.IsStrictVersion(1)) && !this.IsInternalCode)
                {
                    throw InterpreterError.NewInterpreterException((object)this.NodeToken, typeof(RuntimeException), this.NodeToken, "VariableIsUndefined", (object)this.NodeToken);
                }
            }
            return(variable);
        }
        /// <summary>
        /// Gets the value of the specified cmdlet from the cmdlet table.
        /// </summary>
        /// <param name="cmdletName">
        /// The name of the cmdlet value to retrieve.
        /// </param>
        /// <param name="scopeID">
        /// A scope identifier that is either one of the "special" scopes like
        /// "global", "script", "local", or "private, or a numeric ID of a relative scope
        /// to the current scope.
        /// </param>
        /// <returns>
        /// The CmdletInfo representing the cmdlet.
        /// </returns>
        /// <exception cref="ArgumentException">
        /// If <paramref name="scopeID"/> is less than zero, or not
        /// a number and not "script", "global", "local", or "private"
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        /// If <paramref name="scopeID"/> is less than zero or greater than the number of currently
        /// active scopes.
        /// </exception>
        internal CmdletInfo GetCmdletAtScope(string cmdletName, string scopeID)
        {
            CmdletInfo result = null;

            if (string.IsNullOrEmpty(cmdletName))
            {
                return(null);
            }

            SessionStateScope scope = GetScopeByID(scopeID);

            result = scope.GetCmdlet(cmdletName);

            // Make sure the alias isn't private or if it is that the current
            // scope is the same scope the alias was retrieved from.

            if (result != null &&
                (result.Options & ScopedItemOptions.Private) != 0 &&
                scope != _currentScope)
            {
                result = null;
            }

            return(result);
        }
        public bool MoveNext()
        {
            bool flag = true;

            if (!this.isInitialized)
            {
                this.InitializeScopeEnumerator();
            }
            while (this.scopeEnumerable.MoveNext())
            {
                T local;
                if (this.TryGetNewScopeItem(this.scopeEnumerable.Current, out local))
                {
                    this.currentScope = this.scopeEnumerable.Current;
                    this.current      = local;
                    return(true);
                }
                flag = false;
                if (this.isSingleScopeLookup)
                {
                    return(flag);
                }
            }
            return(flag);
        }
        private void InitializeScopeEnumerator()
        {
            // Define the lookup scope and if we have to do single
            // level or dynamic lookup based on the lookup variable

            _initialScope = sessionState.CurrentScope;

            if (_lookupPath.IsGlobal)
            {
                _initialScope        = sessionState.GlobalScope;
                _isSingleScopeLookup = true;
            }
            else if (_lookupPath.IsLocal ||
                     _lookupPath.IsPrivate)
            {
                _initialScope        = sessionState.CurrentScope;
                _isSingleScopeLookup = true;
            }
            else if (_lookupPath.IsScript)
            {
                _initialScope        = sessionState.ScriptScope;
                _isSingleScopeLookup = true;
            }

            _scopeEnumerable =
                new SessionStateScopeEnumerator(_initialScope);

            _isInitialized = true;
        }
        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);
        }
Example #16
0
 public void PrepareForBinding(SessionStateScope scope, CommandLineParameters commandLineParameters)
 {
     if (this._useLocalScope && (scope.LocalsTuple == null))
     {
         scope.LocalsTuple = this._localsTuple;
     }
     this._localsTuple.SetAutomaticVariable(AutomaticVariable.PSBoundParameters, commandLineParameters.GetValueToBindToPSBoundParameters(), base.Context);
     this._localsTuple.SetAutomaticVariable(AutomaticVariable.MyInvocation, base.MyInvocation, base.Context);
 }
Example #17
0
        private static CommandCompletion CompleteInputImpl(Ast ast, Token[] tokens, IScriptPosition positionOfCursor, Hashtable options)
        {
            PowerShell powershell        = PowerShell.Create(RunspaceMode.CurrentRunspace);
            int        replacementIndex  = -1;
            int        replacementLength = -1;
            List <CompletionResult> list = null;

            if (NeedToInvokeLegacyTabExpansion(powershell))
            {
                Tuple <string, int, int> inputAndCursorFromAst = GetInputAndCursorFromAst(positionOfCursor);
                list              = InvokeLegacyTabExpansion(powershell, inputAndCursorFromAst.Item1, inputAndCursorFromAst.Item2, false, out replacementIndex, out replacementLength);
                replacementIndex += inputAndCursorFromAst.Item3;
            }
            if ((list == null) || (list.Count == 0))
            {
                ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();
                MutableTuple     tuple2 = null;
                foreach (CallStackFrame frame in executionContextFromTLS.Debugger.GetCallStack())
                {
                    dynamic obj2  = PSObject.AsPSObject(frame);
                    var     site1 = CallSite <Func <CallSite, object, bool> > .Create(Binder.UnaryOperation(CSharpBinderFlags.None, ExpressionType.IsTrue, typeof(CommandCompletion), new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }));

                    if (site1.Target(site1, obj2.Command.Equals("TabExpansion2", StringComparison.OrdinalIgnoreCase)))
                    {
                        tuple2 = frame.FunctionContext._localsTuple;
                        break;
                    }
                }
                SessionStateScope currentScope = null;
                if (tuple2 != null)
                {
                    currentScope = executionContextFromTLS.EngineSessionState.CurrentScope;
                    SessionStateScope parent = executionContextFromTLS.EngineSessionState.CurrentScope;
                    while ((parent != null) && (parent.LocalsTuple != tuple2))
                    {
                        parent = parent.Parent;
                    }
                    if (parent != null)
                    {
                        executionContextFromTLS.EngineSessionState.CurrentScope = parent.Parent;
                    }
                }
                try
                {
                    list = new CompletionAnalysis(ast, tokens, positionOfCursor, options).GetResults(powershell, out replacementIndex, out replacementLength);
                }
                finally
                {
                    if (currentScope != null)
                    {
                        executionContextFromTLS.EngineSessionState.CurrentScope = currentScope;
                    }
                }
            }
            return(new CommandCompletion(new Collection <CompletionResult>(list ?? EmptyCompletionResult), -1, replacementIndex, replacementLength));
        }
        private bool TryGetNewScopeItem(
            SessionStateScope lookupScope,
            out T newCurrentItem)
        {
            bool result = GetScopeItem(
                lookupScope,
                _lookupPath,
                out newCurrentItem);

            return(result);
        }
Example #19
0
        internal SessionStateInternal(SessionStateInternal parent, bool linkToGlobal, ExecutionContext context)
        {
            if (context == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(context));
            }

            ExecutionContext = context;

            // Create the working directory stack. This
            // is used for the pushd and popd commands

            _workingLocationStack = new Dictionary <string, Stack <PathInfo> >(StringComparer.OrdinalIgnoreCase);

            // Conservative choice to limit the Set-Location history in order to limit memory impact in case of a regression.
            const int locationHistoryLimit = 20;

            _setLocationHistory = new HistoryStack <PathInfo>(locationHistoryLimit);

            GlobalScope   = new SessionStateScope(null);
            ModuleScope   = GlobalScope;
            _currentScope = GlobalScope;

            InitializeSessionStateInternalSpecialVariables(false);

            // Create the push the global scope on as
            // the starting script scope.  That way, if you dot-source a script
            // that uses variables qualified by script: it works.
            GlobalScope.ScriptScope = GlobalScope;

            if (parent != null)
            {
                GlobalScope.Parent = parent.GlobalScope;

                // Copy the drives and providers from the parent...
                CopyProviders(parent);
                // During loading of core modules, providers are not populated.
                // We set the drive information later
                if (Providers != null && Providers.Count > 0)
                {
                    CurrentDrive = parent.CurrentDrive;
                }

                // Link it to the global scope...
                if (linkToGlobal)
                {
                    GlobalScope = parent.GlobalScope;
                }
            }
            else
            {
                _currentScope.LocalsTuple = MutableTuple.MakeTuple(Compiler.DottedLocalsTupleType, Compiler.DottedLocalsNameIndexMap);
            }
        }
Example #20
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);
        }
Example #21
0
        /// <summary>
        /// Constructs a ScriptParameterBinder with the specified context
        /// </summary>
        /// 
        /// <param name="script">
        /// The script block representing the code being run
        /// </param>
        /// 
        /// <param name="invocationInfo">
        /// The invocation information about the code that is being run.
        /// </param>
        /// 
        /// <param name="context">
        /// The context under which the shell function is executing.
        /// </param>
        /// 
        /// <param name="command">
        /// The command instance that represents the script in a pipeline. May be null.
        /// </param>
        /// 
        /// <param name="localScope">
        /// If binding in a new local scope, the scope to set variables in.  If dotting, the value is null.
        /// </param>
        internal ScriptParameterBinder(
            ScriptBlock script,
            InvocationInfo invocationInfo,
            ExecutionContext context,
            InternalCommand command,
            SessionStateScope localScope) : base(invocationInfo, context, command)
        {
            Diagnostics.Assert(script != null, "caller to verify script is not null.");

            this.Script = script;
            this.LocalScope = localScope;
        }
Example #22
0
 internal void SetCurrentScopeToExecutionScope()
 {
     if (this._commandSessionState == null)
     {
         this._commandSessionState = this.Context.EngineSessionState;
     }
     this._previousScope = this._commandSessionState.CurrentScope;
     this._previousCommandSessionState      = this.Context.EngineSessionState;
     this.Context.EngineSessionState        = this._commandSessionState;
     this._commandSessionState.CurrentScope = this.CommandScope;
     this.OnSetCurrentScope();
 }
        /// <summary>
        /// Constructs a ScriptParameterBinder with the specified context.
        /// </summary>
        /// <param name="script">
        /// The script block representing the code being run
        /// </param>
        /// <param name="invocationInfo">
        /// The invocation information about the code that is being run.
        /// </param>
        /// <param name="context">
        /// The context under which the shell function is executing.
        /// </param>
        /// <param name="command">
        /// The command instance that represents the script in a pipeline. May be null.
        /// </param>
        /// <param name="localScope">
        /// If binding in a new local scope, the scope to set variables in.  If dotting, the value is null.
        /// </param>
        internal ScriptParameterBinder(
            ScriptBlock script,
            InvocationInfo invocationInfo,
            ExecutionContext context,
            InternalCommand command,
            SessionStateScope localScope) : base(invocationInfo, context, command)
        {
            Diagnostics.Assert(script != null, "caller to verify script is not null.");

            this.Script     = script;
            this.LocalScope = localScope;
        }
 internal ScriptParameterBinderController(ScriptBlock script, InvocationInfo invocationInfo, ExecutionContext context, InternalCommand command, SessionStateScope localScope) : base(invocationInfo, context, new ScriptParameterBinder(script, invocationInfo, context, command, localScope))
 {
     this.DollarArgs = new List<object>();
     if (script.HasDynamicParameters)
     {
         base.UnboundParameters = base.BindableParameters.ReplaceMetadata(script.ParameterMetadata);
     }
     else
     {
         base._bindableParameters = script.ParameterMetadata;
         base.UnboundParameters = new List<MergedCompiledCommandParameter>(base._bindableParameters.BindableParameters.Values);
     }
 }
Example #25
0
 internal SessionStateScope(SessionStateScope parentScope)
 {
     this.ScopeOrigin = CommandOrigin.Internal;
     this.Parent      = parentScope;
     if (parentScope != null)
     {
         this._scriptScope = parentScope.ScriptScope;
     }
     else
     {
         this._scriptScope = this;
     }
 }
Example #26
0
 internal SessionStateScope(SessionStateScope parentScope)
 {
     this.ScopeOrigin = CommandOrigin.Internal;
     this.Parent = parentScope;
     if (parentScope != null)
     {
         this._scriptScope = parentScope.ScriptScope;
     }
     else
     {
         this._scriptScope = this;
     }
 }
Example #27
0
        internal SessionStateInternal(SessionStateInternal parent, bool linkToGlobal, ExecutionContext context)
        {
            if (context == null)
            {
                throw PSTraceSource.NewArgumentNullException("context");
            }
            ExecutionContext = context;

            // Create the working directory stack. This
            // is used for the pushd and popd commands

            _workingLocationStack = new Dictionary<String, Stack<PathInfo>>(StringComparer.OrdinalIgnoreCase);

            GlobalScope = new SessionStateScope(null);
            ModuleScope = GlobalScope;
            _currentScope = GlobalScope;

            InitializeSessionStateInternalSpecialVariables(false);

            // Create the push the global scope on as
            // the starting script scope.  That way, if you dot-source a script
            // that uses variables qualified by script: it works.
            GlobalScope.ScriptScope = GlobalScope;


            if (parent != null)
            {
                GlobalScope.Parent = parent.GlobalScope;

                // Copy the drives and providers from the parent...
                CopyProviders(parent);
                // During loading of core modules, providers are not populated.
                // We set the drive information later
                if (Providers != null && Providers.Count > 0)
                {
                    CurrentDrive = parent.CurrentDrive;
                }

                // Link it to the global scope...
                if (linkToGlobal)
                {
                    GlobalScope = parent.GlobalScope;
                }
            }
            else
            {
                _currentScope.LocalsTuple = MutableTuple.MakeTuple(Compiler.DottedLocalsTupleType, Compiler.DottedLocalsNameIndexMap);
            }
        }
        /// <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);
        }
Example #29
0
        /// <summary>
        /// Constructor for a session state scope.
        /// </summary>
        /// 
        /// <param name="parentScope">
        /// The parent of this scope.  It can be null for the global scope.
        /// </param>
        /// 
        internal SessionStateScope(SessionStateScope parentScope)
        {
            ScopeOrigin = CommandOrigin.Internal;
            Parent = parentScope;

            if (parentScope != null)
            {
                // Now copy the script: scope stack from the parent
                _scriptScope = parentScope.ScriptScope;
            }
            else
            {
                _scriptScope = this;
            }
        } // SessionStateScope constructor
Example #30
0
 internal bool IsStrictVersion(int majorVersion)
 {
     for (SessionStateScope scope = this.EngineSessionState.CurrentScope; scope != null; scope = scope.Parent)
     {
         if (scope.StrictModeVersion != null)
         {
             return(scope.StrictModeVersion.Major >= majorVersion);
         }
         if (scope == this.EngineSessionState.ModuleScope)
         {
             break;
         }
     }
     return(false);
 }
Example #31
0
 internal SessionStateScope(SessionStateScope parentScope)
 {
     using (SessionStateScope.tracer.TraceConstructor((object)this))
     {
         this.parent = parentScope;
         if (parentScope != null)
         {
             parentScope.Children.Add(this);
             this.scriptScope = parentScope.ScriptScope;
         }
         else
         {
             this.scriptScope = this;
         }
     }
 }
Example #32
0
        /// <summary>
        /// Creates a new scope in the scope tree and assigns the parent
        /// and child scopes appropriately.
        /// </summary>
        /// <param name="isScriptScope">
        /// If true, the new scope is pushed on to the script scope stack and
        /// can be referenced using $script:
        /// </param>
        /// <returns>
        /// A new SessionStateScope which is a child of the current scope.
        /// </returns>
        internal SessionStateScope NewScope(bool isScriptScope)
        {
            Diagnostics.Assert(
                _currentScope != null,
                "The currentScope should always be set.");

            // Create the new child scope.

            SessionStateScope newScope = new SessionStateScope(_currentScope);

            if (isScriptScope)
            {
                newScope.ScriptScope = newScope;
            }
            return(newScope);
        } // NewScope
Example #33
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);
        }
        /// <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);
        }
Example #35
0
 internal SessionStateInternal(SessionStateInternal parent, bool linkToGlobal, System.Management.Automation.ExecutionContext context)
 {
     this.ModuleTableKeys = new List<string>();
     this._moduleTable = new Dictionary<string, PSModuleInfo>(StringComparer.OrdinalIgnoreCase);
     this._scripts = new List<string>(new string[] { "*" });
     this._applications = new List<string>(new string[] { "*" });
     this._exportedCmdlets = new List<CmdletInfo>();
     this._exportedAliases = new List<AliasInfo>();
     this._exportedFunctions = new List<FunctionInfo>();
     this._exportedWorkflows = new List<WorkflowInfo>();
     this.defaultStackName = "default";
     this._providers = new Dictionary<string, List<ProviderInfo>>(100, StringComparer.OrdinalIgnoreCase);
     this._providersCurrentWorkingDrive = new Dictionary<ProviderInfo, PSDriveInfo>();
     this._exportedVariables = new List<PSVariable>();
     if (context == null)
     {
         throw PSTraceSource.NewArgumentNullException("context");
     }
     this._context = context;
     this.workingLocationStack = new Dictionary<string, Stack<PathInfo>>(StringComparer.OrdinalIgnoreCase);
     this._globalScope = new SessionStateScope(null);
     this._moduleScope = this._globalScope;
     this.currentScope = this._globalScope;
     this.InitializeSessionStateInternalSpecialVariables(false);
     this._globalScope.ScriptScope = this._globalScope;
     if (parent != null)
     {
         this._globalScope.Parent = parent.GlobalScope;
         this.CopyProviders(parent);
         if ((this.Providers != null) && (this.Providers.Count > 0))
         {
             this.CurrentDrive = parent.CurrentDrive;
         }
         if (linkToGlobal)
         {
             this._globalScope = parent.GlobalScope;
         }
     }
     else
     {
         this.currentScope.LocalsTuple = MutableTuple.MakeTuple(Compiler.DottedLocalsTupleType, Compiler.DottedLocalsNameIndexMap);
     }
 }
Example #36
0
        public void Set(string name, object value)
        {
            var qualName = new SessionStateScope <PSVariable> .QualifiedName(name);

            // check for existing one. if it's not a scope qualified name, make sure to check only local scope
            // because we won't override a parent scope variable with the same name
            var variable = qualName.ScopeSpecifier.Length == 0 ? _intrinsics.Scope.GetLocal(name)
                                                               : _intrinsics.Scope.Get(name, true);

            if (variable == null) // doesn't exist, yet. create
            {
                _intrinsics.Scope.Set(name, new PSVariable(qualName.UnqualifiedName, value), true, true);
                return;
            }
            // make sure it's not read only
            CheckVariableCanBeChanged(variable);
            // only modify the value of the old one
            variable.Value = value;
        }
Example #37
0
        //actual constructor work, but hidden to not be used accidently in a stupid way
        private SessionState(SessionStateGlobal sessionStateGlobal, SessionStateScope <FunctionInfo> functions,
                             SessionStateScope <PSVariable> variables, SessionStateScope <PSDriveInfo> drives,
                             SessionStateScope <AliasInfo> aliases)
        {
            SessionStateGlobal = sessionStateGlobal;

            _aliasScope    = new SessionStateScope <AliasInfo>(aliases, SessionStateCategory.Alias);
            _functionScope = new SessionStateScope <FunctionInfo>(functions, SessionStateCategory.Function);
            _variableScope = new SessionStateScope <PSVariable>(variables, SessionStateCategory.Variable);
            _driveScope    = new SessionStateScope <PSDriveInfo>(drives, SessionStateCategory.Drive);

            IsScriptScope = false;
            Function      = new FunctionIntrinsics(this, _functionScope);
            Alias         = new AliasIntrinsics(this, _aliasScope);

            Drive      = new DriveManagementIntrinsics(this, _driveScope);
            Path       = new PathIntrinsics(SessionStateGlobal);
            Provider   = new CmdletProviderManagementIntrinsics(SessionStateGlobal);
            PSVariable = new PSVariableIntrinsics(this, _variableScope);
        }
Example #38
0
        //actual constructor work, but hidden to not be used accidently in a stupid way
        private SessionState(SessionStateGlobal sessionStateGlobal, SessionStateScope<FunctionInfo> functions,
                             SessionStateScope<PSVariable> variables, SessionStateScope<PSDriveInfo> drives,
                             SessionStateScope<AliasInfo> aliases)
        {
            SessionStateGlobal = sessionStateGlobal;

            _aliasScope = new SessionStateScope<AliasInfo>(aliases, SessionStateCategory.Alias);
            _functionScope = new SessionStateScope<FunctionInfo>(functions, SessionStateCategory.Function);
            _variableScope = new SessionStateScope<PSVariable>(variables, SessionStateCategory.Variable);
            _driveScope = new SessionStateScope<PSDriveInfo>(drives, SessionStateCategory.Drive);

            IsScriptScope = false;
            Function = new FunctionIntrinsics(this, _functionScope);
            Alias = new AliasIntrinsics(this, _aliasScope);

            Drive = new DriveManagementIntrinsics(this, _driveScope);
            Path = new PathIntrinsics(SessionStateGlobal);
            Provider = new CmdletProviderManagementIntrinsics(SessionStateGlobal);
            PSVariable = new PSVariableIntrinsics(this, _variableScope);
        }
        /// <summary>
        /// Initializes the cmdlet parameter binder controller for
        /// the specified cmdlet and engine context
        /// </summary>
        /// 
        /// <param name="script">
        /// The script that contains the parameter metadata.
        /// </param>
        /// <param name="invocationInfo">
        /// The invocation information about the code being run.
        /// </param>
        /// <param name="context">
        /// The engine context the cmdlet is run in.
        /// </param>
        /// <param name="command">
        /// The command that the parameters will be bound to.
        /// </param>
        /// <param name="localScope">
        /// The scope that the parameter binder will use to set parameters.
        /// </param>
        internal ScriptParameterBinderController(
            ScriptBlock script,
            InvocationInfo invocationInfo,
            ExecutionContext context,
            InternalCommand command,
            SessionStateScope localScope)
            : base(invocationInfo, context, new ScriptParameterBinder(script, invocationInfo, context, command, localScope))
        {
            this.DollarArgs = new List<object>();

            // Add the script parameter metadata to the bindable parameters
            // And add them to the unbound parameters list

            if (script.HasDynamicParameters)
            {
                UnboundParameters = this.BindableParameters.ReplaceMetadata(script.ParameterMetadata);
            }
            else
            {
                _bindableParameters = script.ParameterMetadata;
                UnboundParameters = new List<MergedCompiledCommandParameter>(_bindableParameters.BindableParameters.Values);
            }
        }
Example #40
0
 internal void NewDrive(PSDriveInfo drive, string scopeID, CmdletProviderContext context)
 {
     if (drive == null)
     {
         throw PSTraceSource.NewArgumentNullException("drive");
     }
     if (context == null)
     {
         throw PSTraceSource.NewArgumentNullException("context");
     }
     if (!IsValidDriveName(drive.Name))
     {
         throw PSTraceSource.NewArgumentException("drive.Name", "SessionStateStrings", "DriveNameIllegalCharacters", new object[0]);
     }
     PSDriveInfo newDrive = this.ValidateDriveWithProvider(drive, context, true);
     if (newDrive != null)
     {
         if (string.Compare(newDrive.Name, drive.Name, true, Thread.CurrentThread.CurrentCulture) != 0)
         {
             throw this.NewProviderInvocationException("NewDriveProviderFailed", SessionStateStrings.NewDriveProviderFailed, drive.Provider, drive.Root, PSTraceSource.NewArgumentException("root"));
         }
         try
         {
             SessionStateScope currentScope = this.currentScope;
             if (!string.IsNullOrEmpty(scopeID))
             {
                 currentScope = this.GetScopeByID(scopeID);
             }
             currentScope.NewDrive(newDrive);
         }
         catch (ArgumentException exception2)
         {
             context.WriteError(new ErrorRecord(exception2, "NewDriveError", ErrorCategory.InvalidArgument, newDrive));
             return;
         }
         catch (SessionStateException)
         {
             throw;
         }
         if (this.ProvidersCurrentWorkingDrive[drive.Provider] == null)
         {
             this.ProvidersCurrentWorkingDrive[drive.Provider] = drive;
         }
         context.WriteObject(newDrive);
     }
 }
Example #41
0
 internal SessionStateScope NewScope(bool isScriptScope)
 {
     SessionStateScope scope = new SessionStateScope(this.currentScope);
     if (isScriptScope)
     {
         scope.ScriptScope = scope;
     }
     return scope;
 }
Example #42
0
        } // NewScope

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

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

                throw e;
            }

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

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

                CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);

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

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

            scope.RemoveAllDrives();

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

            if (scope == _currentScope && _currentScope.Parent != null)
            {
                _currentScope = _currentScope.Parent;
            }
            scope.Parent = null;
        } // RemoveScope
Example #43
0
 public void QualifiedNameTest(string name, string specifier, string unqualifiedName)
 {
     var qualName = new SessionStateScope<PSVariable>.QualifiedName(name);
     Assert.AreEqual(specifier, qualName.ScopeSpecifier);
     Assert.AreEqual(unqualifiedName, qualName.UnqualifiedName);
 }
Example #44
0
 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;
 }
Example #45
0
 private void GetScopeVariableTable(SessionStateScope scope, Dictionary<string, PSVariable> result, bool includePrivate)
 {
     foreach (KeyValuePair<string, PSVariable> pair in scope.Variables)
     {
         if (!result.ContainsKey(pair.Key))
         {
             PSVariable variable = pair.Value;
             if (!variable.IsPrivate || includePrivate)
             {
                 result.Add(pair.Key, variable);
             }
         }
     }
     foreach (MutableTuple tuple in scope.DottedScopes)
     {
         tuple.GetVariableTable(result, includePrivate);
     }
     if (scope.LocalsTuple != null)
     {
         scope.LocalsTuple.GetVariableTable(result, includePrivate);
     }
 }
Example #46
0
 internal void SetCurrentScopeToExecutionScope()
 {
     if (this._commandSessionState == null)
     {
         this._commandSessionState = this.Context.EngineSessionState;
     }
     this._previousScope = this._commandSessionState.CurrentScope;
     this._previousCommandSessionState = this.Context.EngineSessionState;
     this.Context.EngineSessionState = this._commandSessionState;
     this._commandSessionState.CurrentScope = this.CommandScope;
     this.OnSetCurrentScope();
 }
Example #47
0
 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;
 }
Example #48
0
 internal bool IsShellVirtualDrive(string driveName, out SessionStateScope scope)
 {
     if (driveName == null)
     {
         throw PSTraceSource.NewArgumentNullException("driveName");
     }
     bool flag = false;
     if (string.Compare(driveName, "GLOBAL", StringComparison.OrdinalIgnoreCase) == 0)
     {
         tracer.WriteLine("match found: {0}", new object[] { "GLOBAL" });
         flag = true;
         scope = this.sessionState.Internal.GlobalScope;
     }
     else if (string.Compare(driveName, "LOCAL", StringComparison.OrdinalIgnoreCase) == 0)
     {
         tracer.WriteLine("match found: {0}", new object[] { driveName });
         flag = true;
         scope = this.sessionState.Internal.CurrentScope;
     }
     else
     {
         scope = null;
     }
     tracer.WriteLine("result = {0}", new object[] { flag });
     return flag;
 }
Example #49
0
 private bool ValidateOrRemoveAutoMountedDrive(PSDriveInfo drive, SessionStateScope scope)
 {
     bool flag = true;
     try
     {
         DriveInfo info = new DriveInfo(drive.Name);
         flag = info.DriveType != DriveType.NoRootDirectory;
     }
     catch (LoopFlowException)
     {
         throw;
     }
     catch (PipelineStoppedException)
     {
         throw;
     }
     catch (ActionPreferenceStopException)
     {
         throw;
     }
     catch (Exception exception)
     {
         CommandProcessorBase.CheckForSevereException(exception);
         flag = false;
     }
     if (!flag)
     {
         DriveCmdletProvider driveProviderInstance = null;
         try
         {
             driveProviderInstance = this.GetDriveProviderInstance(this.ExecutionContext.ProviderNames.FileSystem);
         }
         catch (NotSupportedException)
         {
         }
         catch (ProviderNotFoundException)
         {
         }
         if (driveProviderInstance == null)
         {
             return flag;
         }
         CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
         try
         {
             driveProviderInstance.RemoveDrive(drive, context);
         }
         catch (Exception exception2)
         {
             CommandProcessorBase.CheckForSevereException(exception2);
         }
         scope.RemoveDrive(drive);
     }
     return flag;
 }
Example #50
0
 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;
 }
Example #51
0
 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);
 }
Example #52
0
 internal SessionStateScope GetScopeByID(int scopeID)
 {
     SessionStateScope currentScope = this.currentScope;
     int actualValue = scopeID;
     while ((scopeID > 0) && (currentScope != null))
     {
         currentScope = currentScope.Parent;
         scopeID--;
     }
     if ((currentScope == null) && (scopeID >= 0))
     {
         throw PSTraceSource.NewArgumentOutOfRangeException("scopeID", actualValue, "SessionStateStrings", "ScopeIDExceedsAvailableScopes", new object[] { actualValue });
     }
     return currentScope;
 }
Example #53
0
 internal PSVariable GetVariableItem(VariablePath variablePath, out SessionStateScope scope)
 {
     return this.GetVariableItem(variablePath, out scope, CommandOrigin.Internal);
 }
Example #54
0
        /// <summary>
        /// Creates a new scope in the scope tree and assigns the parent
        /// and child scopes appropriately.
        /// </summary>
        /// 
        /// <param name="isScriptScope">
        /// If true, the new scope is pushed on to the script scope stack and
        /// can be referenced using $script:
        /// </param>
        /// 
        /// <returns>
        /// A new SessionStateScope which is a child of the current scope.
        /// </returns>
        /// 
        internal SessionStateScope NewScope(bool isScriptScope)
        {
            Diagnostics.Assert(
                _currentScope != null,
                "The currentScope should always be set.");

            // Create the new child scope.

            SessionStateScope newScope = new SessionStateScope(_currentScope);

            if (isScriptScope)
            {
                newScope.ScriptScope = newScope;
            }
            return newScope;
        } // NewScope
Example #55
0
 internal SessionStateScope GetScopeByID(string scopeID)
 {
     SessionStateScope currentScope = this.currentScope;
     if (!string.IsNullOrEmpty(scopeID))
     {
         if (string.Equals(scopeID, "GLOBAL", StringComparison.OrdinalIgnoreCase))
         {
             return this._globalScope;
         }
         if (string.Equals(scopeID, "LOCAL", StringComparison.OrdinalIgnoreCase))
         {
             return this.currentScope;
         }
         if (string.Equals(scopeID, "PRIVATE", StringComparison.OrdinalIgnoreCase))
         {
             return this.currentScope;
         }
         if (string.Equals(scopeID, "SCRIPT", StringComparison.OrdinalIgnoreCase))
         {
             return this.currentScope.ScriptScope;
         }
         try
         {
             int num = int.Parse(scopeID, Thread.CurrentThread.CurrentCulture);
             if (num < 0)
             {
                 throw PSTraceSource.NewArgumentOutOfRangeException("scopeID", scopeID);
             }
             currentScope = this.GetScopeByID(num) ?? this.currentScope;
         }
         catch (FormatException)
         {
             throw PSTraceSource.NewArgumentException("scopeID");
         }
         catch (OverflowException)
         {
             throw PSTraceSource.NewArgumentOutOfRangeException("scopeID", scopeID);
         }
     }
     return currentScope;
 }
Example #56
0
 internal void RemoveScope(SessionStateScope scope)
 {
     if (scope == this._globalScope)
     {
         SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException("GLOBAL", SessionStateCategory.Scope, "GlobalScopeCannotRemove", SessionStateStrings.GlobalScopeCannotRemove);
         throw exception;
     }
     foreach (PSDriveInfo info in scope.Drives)
     {
         if (info != null)
         {
             CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
             try
             {
                 this.CanRemoveDrive(info, context);
             }
             catch (LoopFlowException)
             {
                 throw;
             }
             catch (PipelineStoppedException)
             {
                 throw;
             }
             catch (ActionPreferenceStopException)
             {
                 throw;
             }
             catch (Exception exception2)
             {
                 CommandProcessorBase.CheckForSevereException(exception2);
             }
         }
     }
     scope.RemoveAllDrives();
     if ((scope == this.currentScope) && (this.currentScope.Parent != null))
     {
         this.currentScope = this.currentScope.Parent;
     }
     scope.Parent = null;
 }
Example #57
0
 internal void RemoveFunction(string name, bool force, CommandOrigin origin)
 {
     if (string.IsNullOrEmpty(name))
     {
         throw PSTraceSource.NewArgumentException("name");
     }
     SessionStateScope currentScope = this.currentScope;
     FunctionLookupPath lookupPath = new FunctionLookupPath(name);
     FunctionScopeItemSearcher searcher = new FunctionScopeItemSearcher(this, lookupPath, origin);
     if (searcher.MoveNext())
     {
         currentScope = searcher.CurrentLookupScope;
     }
     currentScope.RemoveFunction(name, force);
 }
Example #58
0
 public void PrepareForBinding(SessionStateScope scope, CommandLineParameters commandLineParameters)
 {
     if (_useLocalScope && scope.LocalsTuple == null)
     {
         scope.LocalsTuple = _localsTuple;
     }
     _localsTuple.SetAutomaticVariable(AutomaticVariable.PSBoundParameters,
                                       commandLineParameters.GetValueToBindToPSBoundParameters(), this.Context);
     _localsTuple.SetAutomaticVariable(AutomaticVariable.MyInvocation, MyInvocation, this.Context);
 }
Example #59
0
        } // RemoveGlobEscaping

        #region Path manipulation methods


        /// <summary>
        /// Determines if the given drive name is a "special" name defined
        /// by the shell. For instance, "default", "current", "global", and "scope[##]" are scopes
        /// for variables and are considered shell virtual drives.
        /// </summary>
        /// 
        /// <param name="driveName">
        /// The name of the drive to check to see if it is a shell virtual drive.
        /// </param>
        /// 
        /// <param name="scope">
        /// This out parameter is filled with the scope that the drive name represents.
        /// It will be null if the driveName does not represent a scope.
        /// </param>
        /// 
        /// <returns>
        /// true, if the drive name is a shell virtual drive like "Default" or "global",
        /// false otherwise.
        /// </returns>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="driveName" /> is null.
        /// </exception>
        /// 
        /// <remarks>
        /// The comparison is done using a case-insensitive comparison using the
        /// Invariant culture.
        /// 
        /// This is internal so that it is accessible to SessionState.
        /// </remarks>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="driveName"/> is null.
        /// </exception>
        /// 
        internal bool IsShellVirtualDrive(string driveName, out SessionStateScope scope)
        {
            if (driveName == null)
            {
                throw PSTraceSource.NewArgumentNullException("driveName");
            }

            bool result = false;

            // Is it the global scope?

            if (String.Compare(
                    driveName,
                    StringLiterals.Global,
                    StringComparison.OrdinalIgnoreCase) == 0)
            {
                s_tracer.WriteLine("match found: {0}", StringLiterals.Global);
                result = true;
                scope = _sessionState.Internal.GlobalScope;
            } // globalScope

            // Is it the local scope?

            else if (String.Compare(
                        driveName,
                        StringLiterals.Local,
                        StringComparison.OrdinalIgnoreCase) == 0)
            {
                s_tracer.WriteLine("match found: {0}", driveName);
                result = true;
                scope = _sessionState.Internal.CurrentScope;
            } // currentScope
            else
            {
                scope = null;
            }

            return result;
        } // IsShellVirtualDrive
Example #60
0
 internal ScriptParameterBinder(ScriptBlock script, InvocationInfo invocationInfo, ExecutionContext context, InternalCommand command, SessionStateScope localScope) : base(invocationInfo, context, command)
 {
     this._copyMutableValueSite = CallSite<Func<CallSite, object, object>>.Create(PSVariableAssignmentBinder.Get());
     this.Script = script;
     this.LocalScope = localScope;
 }