/// <summary>
        /// Executes a command that can only be executed once the whole selection is known.
        /// </summary>
        /// <param name="cmdGroup">Unique identifier of the command group</param>
        /// <param name="cmdId">The command to be executed.</param>
        /// <param name="cmdExecOpt">Values describe how the object should execute the command.</param>
        /// <param name="vaIn">Pointer to a VARIANTARG structure containing input arguments. Can be NULL</param>
        /// <param name="vaOut">VARIANTARG structure to receive command output. Can be NULL.</param>
        /// <param name="commandOrigin">The origin of the command. From IOleCommandTarget or hierarchy.</param>
        /// <param name="selectedNodes">The list of the selected nodes.</param>
        /// <param name="handled">An out parameter specifying that the command was handled.</param>
        /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
        protected virtual int ExecCommandThatDependsOnSelectedNodes(Guid cmdGroup, uint cmdId, uint cmdExecOpt, IntPtr vaIn, IntPtr vaOut, CommandOrigin commandOrigin, IList<HierarchyNode> selectedNodes, out bool handled) {
            handled = false;
            if (cmdGroup == VsMenus.guidVsUIHierarchyWindowCmds) {
                switch (cmdId) {
                    case (uint)VSConstants.VsUIHierarchyWindowCmdIds.UIHWCMDID_RightClick:
                        // The UIHWCMDID_RightClick is what tells an IVsUIHierarchy in a UIHierarchyWindow 
                        // to put up the context menu.  Since the mouse may have moved between the 
                        // mouse down and the mouse up, GetCursorPos won't tell you the right place 
                        // to put the context menu (especially if it came through the keyboard).  
                        // So we pack the proper menu position into pvaIn by
                        // memcpy'ing a POINTS struct into the VT_UI4 part of the pvaIn variant.  The
                        // code to unpack it looks like this:
                        //			ULONG ulPts = V_UI4(pvaIn);
                        //			POINTS pts;
                        //			memcpy((void*)&pts, &ulPts, sizeof(POINTS));
                        // You then pass that POINTS into DisplayContextMenu.
                        handled = true;
                        return this.DisplayContextMenu(selectedNodes, vaIn);
                    default:
                        break;
                }
            } else if (cmdGroup == VsMenus.guidStandardCommandSet2K) {
                switch ((VsCommands2K)cmdId) {
                    case VsCommands2K.ViewInClassDiagram:
                        handled = true;
                        return this.ShowInDesigner(selectedNodes);
                }
            }

            return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED;
        }
示例#2
0
 internal CmdletProviderContext(CmdletProviderContext contextToCopyFrom)
 {
     this.credentials = PSCredential.Empty;
     this._origin = CommandOrigin.Internal;
     this.accumulatedObjects = new Collection<PSObject>();
     this.accumulatedErrorObjects = new Collection<ErrorRecord>();
     this.stopReferrals = new Collection<CmdletProviderContext>();
     if (contextToCopyFrom == null)
     {
         throw PSTraceSource.NewArgumentNullException("contextToCopyFrom");
     }
     this.executionContext = contextToCopyFrom.ExecutionContext;
     this.command = contextToCopyFrom.command;
     if (contextToCopyFrom.Credential != null)
     {
         this.credentials = contextToCopyFrom.Credential;
     }
     this.drive = contextToCopyFrom.Drive;
     this.force = (bool) contextToCopyFrom.Force;
     this.CopyFilters(contextToCopyFrom);
     this.suppressWildcardExpansion = contextToCopyFrom.SuppressWildcardExpansion;
     this.dynamicParameters = contextToCopyFrom.DynamicParameters;
     this._origin = contextToCopyFrom._origin;
     this.stopping = contextToCopyFrom.Stopping;
     contextToCopyFrom.StopReferrals.Add(this);
     this.copiedContext = contextToCopyFrom;
 }
 protected ScriptCommandProcessorBase(ScriptBlock scriptBlock, ExecutionContext context, bool useLocalScope, CommandOrigin origin, SessionStateInternal sessionState)
 {
     this._dontUseScopeCommandOrigin = false;
     base.CommandInfo = new ScriptInfo(string.Empty, scriptBlock, context);
     base._fromScriptFile = false;
     this.CommonInitialization(scriptBlock, context, useLocalScope, sessionState);
     base.Command.CommandOriginInternal = origin;
 }
示例#4
0
 // --------------------------------------------------------------------------------------------
 /// <summary>
 /// Initializes a new instance of the <see cref="HierarchyCommandContext"/> class.
 /// </summary>
 /// <param name="package">The package owning this context.</param>
 /// <param name="selection">The list of selected nodes belonging to this context.</param>
 /// <param name="origin">The command origin.</param>
 // --------------------------------------------------------------------------------------------
 public HierarchyCommandContext(PackageBase package, IList<HierarchyNode> selection,
     CommandOrigin origin)
     : base(package)
 {
     _Nodes = new ReadOnlyCollection<HierarchyNode>(selection);
       _Origin = origin;
       Handled = true;
       _ExplicitStatusSet = false;
       _Supported = false;
       _Disabled = false;
       _Invisible = false;
 }
示例#5
0
 public static bool IsVisible(CommandOrigin origin, object valueToCheck)
 {
     if (origin != CommandOrigin.Internal)
     {
         IHasSessionStateEntryVisibility visibility = valueToCheck as IHasSessionStateEntryVisibility;
         if (visibility != null)
         {
             return (visibility.Visibility == SessionStateEntryVisibility.Public);
         }
     }
     return true;
 }
示例#6
0
 public static bool IsVisible(CommandOrigin origin, System.Management.Automation.PSVariable variable)
 {
     if (origin == CommandOrigin.Internal)
     {
         return true;
     }
     if (variable == null)
     {
         throw PSTraceSource.NewArgumentNullException("variable");
     }
     return (variable.Visibility == SessionStateEntryVisibility.Public);
 }
示例#7
0
 public static bool IsVisible(CommandOrigin origin, CommandInfo commandInfo)
 {
     if (origin == CommandOrigin.Internal)
     {
         return true;
     }
     if (commandInfo == null)
     {
         throw PSTraceSource.NewArgumentNullException("commandInfo");
     }
     return (commandInfo.Visibility == SessionStateEntryVisibility.Public);
 }
示例#8
0
 private CommandProcessorBase _CreateCommand(string commandName, CommandOrigin commandOrigin, bool? useLocalScope)
 {
     if (this.context == null)
     {
         throw PSTraceSource.NewInvalidOperationException("DiscoveryExceptions", "ExecutionContextNotSet", new object[0]);
     }
     CommandDiscovery commandDiscovery = this.context.CommandDiscovery;
     if (commandDiscovery == null)
     {
         throw PSTraceSource.NewInvalidOperationException("DiscoveryExceptions", "CommandDiscoveryMissing", new object[0]);
     }
     return commandDiscovery.LookupCommandProcessor(commandName, commandOrigin, useLocalScope);
 }
        /// <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
示例#10
0
        internal PSVariable GetVariable(int slot, CommandOrigin origin)
        {
            PSVariable psVariable = this.variables[slot];

            if (psVariable != null)
            {
                if (psVariable.WasRemoved)
                {
                    this.variables[slot] = (PSVariable)null;
                    psVariable           = (PSVariable)null;
                }
                SessionState.ThrowIfNotVisible(origin, (object)psVariable);
            }
            return(psVariable);
        }
示例#11
0
        /// <summary>
        /// Checks the visibility of an object based on the command origin argument.
        /// </summary>
        /// <param name="origin">The origin to check against.</param>
        /// <param name="valueToCheck">The object to check.</param>
        /// <returns>Returns true if the object is visible, false otherwise.</returns>
        public static bool IsVisible(CommandOrigin origin, object valueToCheck)
        {
            if (origin == CommandOrigin.Internal)
            {
                return(true);
            }
            IHasSessionStateEntryVisibility obj = valueToCheck as IHasSessionStateEntryVisibility;

            if (obj != null)
            {
                return(obj.Visibility == SessionStateEntryVisibility.Public);
            }

            return(true);
        }
 internal CmdletProviderContext(PSCmdlet command, PSCredential credentials)
 {
     this.command = command != null ? (Cmdlet)command : throw CmdletProviderContext.tracer.NewArgumentNullException(nameof(command));
     this._origin = command.CommandOrigin;
     if (credentials != null)
     {
         this.credentials = credentials;
     }
     if (command.Host == null)
     {
         throw CmdletProviderContext.tracer.NewArgumentException("command.Host");
     }
     this.executionContext = command.Context != null ? command.Context : throw CmdletProviderContext.tracer.NewArgumentException("command.Context");
     this.streamObjects    = true;
     this.streamErrors     = true;
 }
        public static void Verify(this BinaryReader reader, CommandOrigin expectedCommandOrigin, CommandType expectedCommandType)
        {
            var expected = (byte)(((int)expectedCommandOrigin) | ((byte)expectedCommandType << 2));

            var actual = reader.ReadByte();

            if (actual != expected)
            {
                var actualCommandOrigin = (CommandOrigin)(actual & 0x3);
                var actualCommandId     = (CommandType)(actual >> 2);
                throw new ProtocolException(string.Format("Expected command type/id {0}/{1} actual {2}/{3} at offset {4:x}({4})",
                                                          expectedCommandOrigin, expectedCommandType,
                                                          actualCommandOrigin, actualCommandId,
                                                          reader.BaseStream.Position - 1));
            }
        }
示例#14
0
        } // GetAliasAtScope

        /// <summary>
        /// Sets the alias with specified name to the specified value in the current scope.
        /// </summary>
        ///
        /// <param name="aliasName">
        /// The name of the alias to set.
        /// </param>
        ///
        /// <param name="value">
        /// The value to set the alias to.
        /// </param>
        ///
        /// <param name="force">
        /// If true, the value will be set even if the alias is ReadOnly.
        /// </param>
        ///
        /// <param name="origin">
        /// THe origin of the caller of this API
        /// </param>
        ///
        /// <returns>
        /// The resulting AliasInfo for the alias that was set.
        /// </returns>
        ///
        /// <exception cref="ArgumentException">
        /// If <paramref name="aliasName"/> or <paramref name="value"/> is null or empty.
        /// </exception>
        ///
        /// <exception cref="SessionStateUnauthorizedAccessException">
        /// If the alias is read-only or constant.
        /// </exception>
        ///
        internal AliasInfo SetAliasValue(string aliasName, string value, bool force, CommandOrigin origin)
        {
            if (String.IsNullOrEmpty(aliasName))
            {
                throw PSTraceSource.NewArgumentException("aliasName");
            }

            if (String.IsNullOrEmpty(value))
            {
                throw PSTraceSource.NewArgumentException("value");
            }

            AliasInfo info = _currentScope.SetAliasValue(aliasName, value, this.ExecutionContext, force, origin);

            return(info);
        } // SetAliasValue
示例#15
0
        protected internal override bool ShouldRun(
            CommandInfo commandInfo,
            CommandOrigin origin,
            PSHost host,
            out Exception reason)
        {
            bool flag = false;

            reason = (Exception)null;
            Utils.CheckArgForNull(PSAuthorizationManager.tracer, (object)commandInfo, nameof(commandInfo));
            Utils.CheckArgForNullOrEmpty(PSAuthorizationManager.tracer, commandInfo.Name, "commandInfo.Name");
            switch (commandInfo.CommandType)
            {
            case CommandTypes.Alias:
                flag = true;
                break;

            case CommandTypes.Function:
            case CommandTypes.Filter:
                flag = true;
                break;

            case CommandTypes.Cmdlet:
                flag = true;
                break;

            case CommandTypes.ExternalScript:
                if (!(commandInfo is ExternalScriptInfo script))
                {
                    reason = (Exception)PSAuthorizationManager.tracer.NewArgumentException("scriptInfo");
                    break;
                }
                flag = this.CheckPolicy(script, host, out reason);
                break;

            case CommandTypes.Application:
                flag = true;
                break;

            case CommandTypes.Script:
                flag = true;
                break;
            }
            return(flag);
        }
 internal CmdletProviderContext(CmdletProviderContext contextToCopyFrom)
 {
     this.executionContext = contextToCopyFrom != null ? contextToCopyFrom.ExecutionContext : throw CmdletProviderContext.tracer.NewArgumentNullException(nameof(contextToCopyFrom));
     this.command          = contextToCopyFrom.command;
     if (contextToCopyFrom.Credential != null)
     {
         this.credentials = contextToCopyFrom.Credential;
     }
     this.drive = contextToCopyFrom.Drive;
     this.force = (bool)contextToCopyFrom.Force;
     this.CopyFilters(contextToCopyFrom);
     this.suppressWildcardExpansion = contextToCopyFrom.SuppressWildcardExpansion;
     this.dynamicParameters         = contextToCopyFrom.DynamicParameters;
     this._origin  = contextToCopyFrom._origin;
     this.stopping = contextToCopyFrom.Stopping;
     contextToCopyFrom.StopReferrals.Add(this);
     this.copiedContext = contextToCopyFrom;
 }
        public CommandInfo GetCommand(string commandName, CommandTypes type)
        {
            CommandInfo info = null;

            try
            {
                CommandOrigin runspace = CommandOrigin.Runspace;
                if (this._cmdlet != null)
                {
                    runspace = this._cmdlet.CommandOrigin;
                }
                info = CommandDiscovery.LookupCommandInfo(commandName, type, SearchResolutionOptions.None, runspace, this._context);
            }
            catch (CommandNotFoundException)
            {
            }
            return(info);
        }
示例#18
0
 internal CmdletProviderContext(System.Management.Automation.ExecutionContext executionContext)
 {
     this.credentials = PSCredential.Empty;
     this._origin = CommandOrigin.Internal;
     this.accumulatedObjects = new Collection<PSObject>();
     this.accumulatedErrorObjects = new Collection<ErrorRecord>();
     this.stopReferrals = new Collection<CmdletProviderContext>();
     if (executionContext == null)
     {
         throw PSTraceSource.NewArgumentNullException("executionContext");
     }
     this.executionContext = executionContext;
     this._origin = CommandOrigin.Internal;
     this.drive = executionContext.EngineSessionState.CurrentDrive;
     if ((executionContext.CurrentCommandProcessor != null) && (executionContext.CurrentCommandProcessor.Command is Cmdlet))
     {
         this.command = (Cmdlet) executionContext.CurrentCommandProcessor.Command;
     }
 }
示例#19
0
 internal CmdletProviderContext(System.Management.Automation.ExecutionContext executionContext)
 {
     this.credentials             = PSCredential.Empty;
     this._origin                 = CommandOrigin.Internal;
     this.accumulatedObjects      = new Collection <PSObject>();
     this.accumulatedErrorObjects = new Collection <ErrorRecord>();
     this.stopReferrals           = new Collection <CmdletProviderContext>();
     if (executionContext == null)
     {
         throw PSTraceSource.NewArgumentNullException("executionContext");
     }
     this.executionContext = executionContext;
     this._origin          = CommandOrigin.Internal;
     this.drive            = executionContext.EngineSessionState.CurrentDrive;
     if ((executionContext.CurrentCommandProcessor != null) && (executionContext.CurrentCommandProcessor.Command is Cmdlet))
     {
         this.command = (Cmdlet)executionContext.CurrentCommandProcessor.Command;
     }
 }
        /// <summary>
        /// Gets the value of the specified alias from the alias table.
        /// </summary>
        ///
        /// <param name="aliasName">
        /// The name of the alias value to retrieve.
        /// </param>
        ///
        /// <param name="origin">
        /// The origin of the command calling this API.
        /// </param>
        /// <returns>
        /// The AliasInfo representing the alias.
        /// </returns>
        ///
        internal AliasInfo GetAlias(string aliasName, CommandOrigin origin)
        {
            AliasInfo result = null;

            if (String.IsNullOrEmpty(aliasName))
            {
                return(null);
            }


            // Use the scope enumerator to find the alias using the
            // appropriate scoping rules

            SessionStateScopeEnumerator scopeEnumerator =
                new SessionStateScopeEnumerator(_currentScope);

            foreach (SessionStateScope scope in scopeEnumerator)
            {
                result = scope.GetAlias(aliasName);

                if (result != null)
                {
                    // Now check the visibility of the variable...
                    SessionState.ThrowIfNotVisible(origin, result);

                    // 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.Options & ScopedItemOptions.Private) != 0 &&
                        scope != _currentScope)
                    {
                        result = null;
                    }
                    else
                    {
                        break;
                    }
                }
            }

            return(result);
        } // GetAlias
示例#21
0
        /// <summary>
        /// Get a functions out of session state.
        /// </summary>
        ///
        /// <param name="name">
        /// name of function to look up
        /// </param>
        ///
        /// <param name="origin">
        /// Origin of the command that called this API...
        /// </param>
        ///
        /// <returns>
        /// The value of the specified function.
        /// </returns>
        ///
        /// <exception cref="ArgumentException">
        /// If <paramref name="name"/> is null or empty.
        /// </exception>
        ///
        internal FunctionInfo GetFunction(string name, CommandOrigin origin)
        {
            if (String.IsNullOrEmpty(name))
            {
                throw PSTraceSource.NewArgumentException("name");
            }

            FunctionInfo result = null;

            FunctionLookupPath lookupPath = new FunctionLookupPath(name);

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

            if (searcher.MoveNext())
            {
                result = ((IEnumerator <FunctionInfo>)searcher).Current;
            }
            return(result);
        } // GetFunction
示例#22
0
 internal CmdletProviderContext(Cmdlet command)
 {
     this.credentials             = PSCredential.Empty;
     this._origin                 = CommandOrigin.Internal;
     this.accumulatedObjects      = new Collection <PSObject>();
     this.accumulatedErrorObjects = new Collection <ErrorRecord>();
     this.stopReferrals           = new Collection <CmdletProviderContext>();
     if (command == null)
     {
         throw PSTraceSource.NewArgumentNullException("command");
     }
     this.command = command;
     this._origin = command.CommandOrigin;
     if (command.Context == null)
     {
         throw PSTraceSource.NewArgumentException("command.Context");
     }
     this.executionContext = command.Context;
     this.streamObjects    = true;
     this.streamErrors     = true;
 }
示例#23
0
 internal CmdletProviderContext(Cmdlet command)
 {
     this.credentials = PSCredential.Empty;
     this._origin = CommandOrigin.Internal;
     this.accumulatedObjects = new Collection<PSObject>();
     this.accumulatedErrorObjects = new Collection<ErrorRecord>();
     this.stopReferrals = new Collection<CmdletProviderContext>();
     if (command == null)
     {
         throw PSTraceSource.NewArgumentNullException("command");
     }
     this.command = command;
     this._origin = command.CommandOrigin;
     if (command.Context == null)
     {
         throw PSTraceSource.NewArgumentException("command.Context");
     }
     this.executionContext = command.Context;
     this.streamObjects = true;
     this.streamErrors = true;
 }
示例#24
0
        private CommandProcessorBase _CreateCommand(string commandName,
                                                    CommandOrigin commandOrigin, bool?useLocalScope)
        {
            if (_context == null)
            {
                throw PSTraceSource.NewInvalidOperationException(DiscoveryExceptions.ExecutionContextNotSet);
            }

            // Look for a cmdlet...
            CommandDiscovery discovery = _context.CommandDiscovery;

            if (discovery == null)
            {
                throw PSTraceSource.NewInvalidOperationException(DiscoveryExceptions.CommandDiscoveryMissing);
            }

            // Look for the command using command discovery mechanisms.  This will resolve
            // aliases, functions, filters, cmdlets, scripts, and applications.

            return(discovery.LookupCommandProcessor(commandName, commandOrigin, useLocalScope));
        }
示例#25
0
        /// <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="origin">
        /// The origin of hte command trying to retrieve this cmdlet.
        /// </param>
        /// 
        /// <returns>
        /// The CmdletInfo representing the cmdlet.
        /// </returns>
        /// 
        internal CmdletInfo GetCmdlet(string cmdletName, CommandOrigin origin)
        {
            CmdletInfo result = null;
            if (String.IsNullOrEmpty(cmdletName))
            {
                return null;
            }

            // Use the scope enumerator to find the alias using the
            // appropriate scoping rules

            SessionStateScopeEnumerator scopeEnumerator =
                new SessionStateScopeEnumerator(_currentScope);

            foreach (SessionStateScope scope in scopeEnumerator)
            {
                result = scope.GetCmdlet(cmdletName);

                if (result != null)
                {
                    // Now check the visibility of the cmdlet...
                    SessionState.ThrowIfNotVisible(origin, result);

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

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

            return result;
        } // GetCmdlet
        private void PrivateSetValue(object value, ExecutionContext context)
        {
            SessionStateInternal engineSessionState = context.EngineSessionState;
            CommandOrigin        scopeOrigin        = engineSessionState.currentScope.ScopeOrigin;

            if (!this._variablePath.IsScopedItem)
            {
                engineSessionState.SetVariable(this._variablePath, value, true, scopeOrigin);
            }
            else
            {
                PSVariable variable1 = engineSessionState.CurrentActivationRecord.GetVariable(this._activationRecordSlot, scopeOrigin);
                if (variable1 != null)
                {
                    this.UpdateVariable(variable1, value);
                }
                else
                {
                    ScopedItemLookupPath variablePath = !this._variablePath.IsUnqualified ? this._variablePath : new ScopedItemLookupPath(this._variablePath, true);
                    SessionStateScope    scope;
                    PSVariable           variable2 = engineSessionState.GetVariableItem(variablePath, out scope, scopeOrigin);
                    if (variable2 == null)
                    {
                        if (string.IsNullOrEmpty(variablePath.LookupPath.NamespaceSpecificString))
                        {
                            throw InterpreterError.NewInterpreterException((object)this._varName, typeof(RuntimeException), this.NodeToken, "InvalidVariableReference");
                        }
                        variable2 = new PSVariable(variablePath.LookupPath.NamespaceSpecificString, (object)null, ScopedItemOptions.None, new Collection <Attribute>());
                        engineSessionState.SetVariable(variablePath, (object)variable2, false, scopeOrigin);
                        if (variablePath.IsLocal)
                        {
                            scope = context.EngineSessionState.CurrentScope;
                        }
                    }
                    engineSessionState.CurrentActivationRecord.SetVariable(variable2, scope, this._activationRecordSlot);
                    this.UpdateVariable(variable2, value);
                }
            }
        }
示例#27
0
        internal void ShouldRunInternal(CommandInfo commandInfo, CommandOrigin origin, PSHost host)
        {
            bool      flag   = false;
            bool      flag2  = false;
            Exception reason = null;

            try
            {
                lock (this.policyCheckLock)
                {
                    flag = this.ShouldRun(commandInfo, origin, host, out reason);
                }
            }
            catch (Exception exception2)
            {
                CommandProcessorBase.CheckForSevereException(exception2);
                reason = exception2;
                flag2  = true;
                flag   = false;
            }
            if (!flag)
            {
                if (reason == null)
                {
                    throw new PSSecurityException(AuthorizationManagerBase.AuthorizationManagerDefaultFailureReason);
                }
                if (reason is PSSecurityException)
                {
                    throw reason;
                }
                string message = reason.Message;
                if (flag2)
                {
                    message = AuthorizationManagerBase.AuthorizationManagerDefaultFailureReason;
                }
                PSSecurityException exception3 = new PSSecurityException(message, reason);
                throw exception3;
            }
        }
示例#28
0
        internal ScriptCommandProcessor(
            string script,
            ExecutionContext context,
            bool isFilter,
            bool useLocalScope,
            bool interactiveCommand,
            CommandOrigin origin)
        {
            this.Context                    = context;
            this._interactiveCommand        = interactiveCommand;
            this._dontUseScopeCommandOrigin = false;
            this._rethrowExitException      = this.Context.ScriptCommandProcessorShouldRethrowExit;
            this.Context.ScriptCommandProcessorShouldRethrowExit = false;
            if (origin == CommandOrigin.Runspace && this.Context.LanguageMode == PSLanguageMode.NoLanguage)
            {
                throw InterpreterError.NewInterpreterException((object)script, typeof(ParseException), (Token)null, "ScriptsNotAllowed");
            }
            this._scriptBlock = this.Context.Engine.ParseScriptBlock(script, interactiveCommand);
            if (origin == CommandOrigin.Runspace)
            {
                switch (this.Context.LanguageMode)
                {
                case PSLanguageMode.FullLanguage:
                    break;

                case PSLanguageMode.RestrictedLanguage:
                    RestrictedLanguageModeChecker.Check(this.Context.Engine.EngineParser, this._scriptBlock, (IEnumerable <string>)null, false);
                    break;

                default:
                    throw new InvalidOperationException("Invalid langage mode was set when building a ScriptCommandProcessor");
                }
            }
            this.CommandInfo   = (CommandInfo) new ScriptInfo(string.Empty, this._scriptBlock, context);
            this._fromPipeline = true;
            this.SetupCommand();
            this.Command.CommandOriginInternal = origin;
            this.UseLocalScope = useLocalScope;
        }
示例#29
0
 internal void ShouldRunInternal(CommandInfo commandInfo, CommandOrigin origin, PSHost host)
 {
     bool flag = false;
     bool flag2 = false;
     Exception reason = null;
     try
     {
         lock (this.policyCheckLock)
         {
             flag = this.ShouldRun(commandInfo, origin, host, out reason);
         }
     }
     catch (Exception exception2)
     {
         CommandProcessorBase.CheckForSevereException(exception2);
         reason = exception2;
         flag2 = true;
         flag = false;
     }
     if (!flag)
     {
         if (reason == null)
         {
             throw new PSSecurityException(AuthorizationManagerBase.AuthorizationManagerDefaultFailureReason);
         }
         if (reason is PSSecurityException)
         {
             throw reason;
         }
         string message = reason.Message;
         if (flag2)
         {
             message = AuthorizationManagerBase.AuthorizationManagerDefaultFailureReason;
         }
         PSSecurityException exception3 = new PSSecurityException(message, reason);
         throw exception3;
     }
 }
示例#30
0
 internal static void ShouldRun(
     ExecutionContext context,
     PSHost host,
     CommandInfo commandInfo,
     CommandOrigin commandOrigin)
 {
     try
     {
         if (commandOrigin == CommandOrigin.Runspace && commandInfo.Visibility != SessionStateEntryVisibility.Public)
         {
             CommandNotFoundException notFoundException = new CommandNotFoundException(commandInfo.Name, (Exception)null, "CommandNotFoundException", new object[0]);
             CommandDiscovery.tracer.TraceException((Exception)notFoundException);
             throw notFoundException;
         }
         context.AuthorizationManager.ShouldRunInternal(commandInfo, commandOrigin, host);
     }
     catch (PSSecurityException ex)
     {
         CommandDiscovery.tracer.TraceException((Exception)ex);
         MshLog.LogCommandHealthEvent(context, (Exception)ex, Severity.Warning);
         MshLog.LogCommandLifecycleEvent(context, CommandState.Terminated, commandInfo.Name);
         throw;
     }
 }
示例#31
0
        /// <summary>
        /// Removes a cmdlet from the function table.
        /// </summary>
        ///
        /// <param name="name">
        /// The name of the cmdlet to remove.
        /// </param>
        ///
        /// <param name="index">
        /// The name of the cmdlet to remove.
        /// </param>
        ///
        /// <param name="origin">
        /// THe origin of the caller of this API
        /// </param>
        ///
        /// <param name="force">
        /// If true, the cmdlet 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 RemoveCmdlet(string name, int index, bool force, CommandOrigin origin)
        {
            if (String.IsNullOrEmpty(name))
            {
                throw PSTraceSource.NewArgumentException("name");
            }

            // Use the scope enumerator to find an existing function

            SessionStateScopeEnumerator scopeEnumerator =
                new SessionStateScopeEnumerator(_currentScope);

            foreach (SessionStateScope scope in scopeEnumerator)
            {
                CmdletInfo cmdletInfo =
                    scope.GetCmdlet(name);


                if (cmdletInfo != null)
                {
                    // Make sure the cmdlet isn't private or if it is that the current
                    // scope is the same scope the cmdlet was retrieved from.

                    if ((cmdletInfo.Options & ScopedItemOptions.Private) != 0 &&
                        scope != _currentScope)
                    {
                        cmdletInfo = null;
                    }
                    else
                    {
                        scope.RemoveCmdlet(name, index, force);
                        break;
                    }
                }
            }
        } // RemoveCmdlet
示例#32
0
        private void OutputResultsHelper(IEnumerable <CommandInfo> results)
        {
            CommandOrigin commandOrigin = base.MyInvocation.CommandOrigin;

            foreach (CommandInfo info in results)
            {
                if (SessionState.IsVisible(commandOrigin, info))
                {
                    if (this.Syntax != 0)
                    {
                        if (!string.IsNullOrEmpty(info.Syntax))
                        {
                            PSObject sendToPipeline = PSObject.AsPSObject(info.Syntax);
                            sendToPipeline.IsHelpObject = true;
                            base.WriteObject(sendToPipeline);
                        }
                    }
                    else
                    {
                        base.WriteObject(info);
                    }
                }
            }
        }
示例#33
0
        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));
        }
示例#34
0
 protected internal virtual bool ShouldRun(CommandInfo commandInfo, CommandOrigin origin, PSHost host, out Exception reason)
 {
     reason = null;
     return true;
 }
示例#35
0
        internal CommandProcessorBase LookupCommandProcessor(CommandInfo commandInfo, CommandOrigin commandOrigin, bool? useLocalScope, SessionStateInternal sessionState)
        {
            CommandProcessorBase base2 = null;
            FunctionInfo info3;
            CommandNotFoundException exception6;
            HashSet<string> set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            while (((commandInfo.CommandType == CommandTypes.Alias) && !set.Contains(commandInfo.Name)) && ((commandOrigin == CommandOrigin.Internal) || (commandInfo.Visibility == SessionStateEntryVisibility.Public)))
            {
                set.Add(commandInfo.Name);
                AliasInfo info = (AliasInfo) commandInfo;
                commandInfo = info.ResolvedCommand;
                if (commandInfo == null)
                {
                    commandInfo = LookupCommandInfo(info.Definition, commandOrigin, this._context);
                }
                if (commandInfo == null)
                {
                    CommandNotFoundException exception = new CommandNotFoundException(info.Name, null, "AliasNotResolvedException", DiscoveryExceptions.AliasNotResolvedException, new object[] { info.UnresolvedCommandName });
                    throw exception;
                }
                PSSQMAPI.IncrementData(CommandTypes.Alias);
            }
            ShouldRun(this._context, this._context.EngineHostInterface, commandInfo, commandOrigin);
            CommandTypes commandType = commandInfo.CommandType;
            if (commandType <= CommandTypes.ExternalScript)
            {
                switch (commandType)
                {
                    case CommandTypes.Function:
                    case CommandTypes.Filter:
                        goto Label_01E3;

                    case CommandTypes.Cmdlet:
                        base2 = new CommandProcessor((CmdletInfo) commandInfo, this._context);
                        goto Label_0260;

                    case CommandTypes.ExternalScript:
                    {
                        ExternalScriptInfo scriptInfo = (ExternalScriptInfo) commandInfo;
                        scriptInfo.SignatureChecked = true;
                        try
                        {
                            if (!this._context.IsSingleShell)
                            {
                                bool? nullable = useLocalScope;
                                base2 = this.CreateScriptProcessorForMiniShell(scriptInfo, nullable.HasValue ? nullable.GetValueOrDefault() : true, sessionState);
                            }
                            else
                            {
                                bool? nullable2 = useLocalScope;
                                base2 = this.CreateScriptProcessorForSingleShell(scriptInfo, this._context, nullable2.HasValue ? nullable2.GetValueOrDefault() : true, sessionState);
                            }
                            goto Label_0260;
                        }
                        catch (ScriptRequiresSyntaxException exception2)
                        {
                            CommandNotFoundException exception3 = new CommandNotFoundException(exception2.Message, exception2);
                            throw exception3;
                        }
                        catch (PSArgumentException exception4)
                        {
                            CommandNotFoundException exception5 = new CommandNotFoundException(commandInfo.Name, exception4, "ScriptRequiresInvalidFormat", DiscoveryExceptions.ScriptRequiresInvalidFormat, new object[0]);
                            throw exception5;
                        }
                        goto Label_01E3;
                    }
                }
                goto Label_023F;
            }
            if (commandType != CommandTypes.Application)
            {
                if (commandType == CommandTypes.Script)
                {
                    bool? nullable4 = useLocalScope;
                    base2 = CreateCommandProcessorForScript((ScriptInfo) commandInfo, this._context, nullable4.HasValue ? nullable4.GetValueOrDefault() : true, sessionState);
                    goto Label_0260;
                }
                if (commandType == CommandTypes.Workflow)
                {
                    goto Label_01E3;
                }
                goto Label_023F;
            }
            base2 = new NativeCommandProcessor((ApplicationInfo) commandInfo, this._context);
            goto Label_0260;
        Label_01E3:
            info3 = (FunctionInfo) commandInfo;
            bool? nullable3 = useLocalScope;
            base2 = CreateCommandProcessorForScript(info3, this._context, nullable3.HasValue ? nullable3.GetValueOrDefault() : true, sessionState);
            goto Label_0260;
        Label_023F:
            exception6 = new CommandNotFoundException(commandInfo.Name, null, "CommandNotFoundException", DiscoveryExceptions.CommandNotFoundException, new object[0]);
            throw exception6;
        Label_0260:
            PSSQMAPI.IncrementData(commandInfo.CommandType);
            base2.Command.CommandOriginInternal = commandOrigin;
            base2.Command.MyInvocation.InvocationName = commandInfo.Name;
            return base2;
        }
示例#36
0
        /// <summary>
        /// Determines if should run the specified command.  Please see the
        /// class summary for an overview of the semantics enforced by this
        /// authorization manager.
        /// </summary>
        ///
        /// <param name="commandInfo">
        /// The command to be run.
        /// </param>
        /// <param name="origin">
        /// The origin of the command.
        /// </param>
        /// <param name="host">
        /// The PSHost executing the command.
        /// </param>
        /// <param name="reason">
        /// If access is denied, this parameter provides a specialized
        /// Exception as the reason.
        /// </param>
        ///
        /// <returns>
        /// True if the command should be run.  False otherwise.
        /// </returns>
        ///
        /// <exception cref="System.ArgumentException">
        /// CommandInfo is invalid. This may occur if
        /// commandInfo.Name is null or empty.
        /// </exception>
        ///
        /// <exception cref="System.ArgumentNullException">
        /// CommandInfo is null.
        /// </exception>
        ///
        /// <exception cref="System.IO.FileNotFoundException">
        /// The file specified by commandInfo.Path is not found.
        /// </exception>
        protected internal override bool ShouldRun(CommandInfo commandInfo,
                                                   CommandOrigin origin,
                                                   PSHost host,
                                                   out Exception reason)
        {
            Dbg.Diagnostics.Assert(commandInfo != null, "caller should validate the parameter");

            bool allowRun = false;

            reason = null;
            Utils.CheckArgForNull(commandInfo, "commandInfo");
            Utils.CheckArgForNullOrEmpty(commandInfo.Name, "commandInfo.Name");

            switch (commandInfo.CommandType)
            {
            case CommandTypes.Cmdlet:
                // Always allow cmdlets to run
                allowRun = true;
                break;

            case CommandTypes.Alias:
                //
                // we do not care about verifying an alias as we will
                // get subsequent call(s) for commands/scripts
                // when the alias is expanded.
                //
                allowRun = true;
                break;

            case CommandTypes.Function:
            case CommandTypes.Filter:
            case CommandTypes.Workflow:
            case CommandTypes.Configuration:
                //
                // we do not check functions/filters.
                // we only perform script level check.
                //
                allowRun = true;
                break;

            case CommandTypes.Script:
                //
                // Allow scripts that are built into the
                // runspace configuration to run.
                //
                allowRun = true;
                break;

            case CommandTypes.ExternalScript:
                ExternalScriptInfo si = commandInfo as ExternalScriptInfo;
                if (si == null)
                {
                    reason = PSTraceSource.NewArgumentException("scriptInfo");
                }
                else
                {
                    bool etwEnabled = ParserEventSource.Log.IsEnabled();
                    if (etwEnabled)
                    {
                        ParserEventSource.Log.CheckSecurityStart(si.Path);
                    }
                    allowRun = CheckPolicy(si, host, out reason);
                    if (etwEnabled)
                    {
                        ParserEventSource.Log.CheckSecurityStop(si.Path);
                    }
                }
                break;

            case CommandTypes.Application:
                //
                // We do not check executables -- that is done by Windows
                //
                allowRun = true;
                break;
            }

            return(allowRun);
        }
示例#37
0
 private static CommandInfo TryModuleAutoLoading(string commandName, ExecutionContext context, string originalCommandName, CommandOrigin commandOrigin, CommandInfo result, ref Exception lastError)
 {
     int length = commandName.IndexOfAny(new char[] { ':', '\\' });
     if ((length == -1) || (commandName[length] == ':'))
     {
         return null;
     }
     string str = commandName.Substring(0, length);
     string str2 = commandName.Substring(length + 1, (commandName.Length - length) - 1);
     if ((string.IsNullOrEmpty(str) || string.IsNullOrEmpty(str2)) || str.EndsWith(".", StringComparison.Ordinal))
     {
         return null;
     }
     try
     {
         discoveryTracer.WriteLine("Executing module-qualified search: {0}", new object[] { commandName });
         context.CommandDiscovery.RegisterLookupCommandInfoAction("ActiveModuleSearch", commandName);
         CmdletInfo cmdlet = context.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Import-Module");
         if ((commandOrigin == CommandOrigin.Internal) || ((cmdlet != null) && (cmdlet.Visibility == SessionStateEntryVisibility.Public)))
         {
             List<PSModuleInfo> modules = context.Modules.GetModules(new string[] { str }, false);
             PSModuleInfo info2 = null;
             if ((modules == null) || (modules.Count == 0))
             {
                 CommandInfo commandInfo = new CmdletInfo("Import-Module", typeof(ImportModuleCommand), null, null, context) {
                     Visibility = cmdlet.Visibility
                 };
                 Command command = new Command(commandInfo);
                 Collection<PSModuleInfo> collection = null;
                 discoveryTracer.WriteLine("Attempting to load module: {0}", new object[] { str });
                 try
                 {
                     collection = PowerShell.Create(RunspaceMode.CurrentRunspace).AddCommand(command).AddParameter("Name", str).AddParameter("Scope", "GLOBAL").AddParameter("ErrorAction", ActionPreference.Ignore).AddParameter("PassThru").AddParameter("WarningAction", ActionPreference.Ignore).AddParameter("Verbose", false).AddParameter("Debug", false).Invoke<PSModuleInfo>();
                 }
                 catch (Exception exception)
                 {
                     discoveryTracer.WriteLine("Encountered error importing module: {0}", new object[] { exception.Message });
                     lastError = exception;
                     CommandProcessorBase.CheckForSevereException(exception);
                 }
                 if ((collection == null) || (collection.Count == 0))
                 {
                     string resourceStr = StringUtil.Format(DiscoveryExceptions.CouldNotAutoImportModule, str);
                     CommandNotFoundException exception2 = new CommandNotFoundException(originalCommandName, lastError, "CouldNotAutoLoadModule", resourceStr, new object[0]);
                     throw exception2;
                 }
                 info2 = collection[0];
             }
             else
             {
                 info2 = modules[0];
             }
             if (info2.ExportedCommands.ContainsKey(str2))
             {
                 result = info2.ExportedCommands[str2];
             }
         }
         return result;
     }
     catch (CommandNotFoundException)
     {
         throw;
     }
     catch (Exception exception3)
     {
         CommandProcessorBase.CheckForSevereException(exception3);
     }
     finally
     {
         context.CommandDiscovery.UnregisterLookupCommandInfoAction("ActiveModuleSearch", commandName);
     }
     return result;
 }
 internal DlrScriptCommandProcessor(ScriptBlock scriptBlock, ExecutionContext context, bool useNewScope, CommandOrigin origin, SessionStateInternal sessionState)
     : base(scriptBlock, context, useNewScope, origin, sessionState)
 {
     Init();
 }
示例#39
0
        CreateCommandProcessor
        (
            ExecutionContext executionContext,
            CommandFactory commandFactory,
            bool addToHistory,
            CommandOrigin origin
        )
        {
            Dbg.Assert(executionContext != null, "Caller should verify the parameters");
            Dbg.Assert(commandFactory != null, "Caller should verify the parameters");


            CommandProcessorBase commandProcessorBase;

            if (IsScript)
            {
                if ((executionContext.LanguageMode == PSLanguageMode.NoLanguage) &&
                    (origin == Automation.CommandOrigin.Runspace))
                {
                    throw InterpreterError.NewInterpreterException(CommandText, typeof(ParseException),
                                                                   null, "ScriptsNotAllowed", ParserStrings.ScriptsNotAllowed);
                }

                ScriptBlock scriptBlock = executionContext.Engine.ParseScriptBlock(CommandText, addToHistory);
                if (origin == Automation.CommandOrigin.Internal)
                {
                    scriptBlock.LanguageMode = PSLanguageMode.FullLanguage;
                }

                // If running in restricted language mode, verify that the parse tree represents on legitimate
                // constructions...
                switch (scriptBlock.LanguageMode)
                {
                case PSLanguageMode.RestrictedLanguage:
                    scriptBlock.CheckRestrictedLanguage(null, null, false);
                    break;

                case PSLanguageMode.FullLanguage:
                    // Interactive script commands are permitted in this mode.
                    break;

                case PSLanguageMode.ConstrainedLanguage:
                    // Constrained Language is checked at runtime.
                    break;

                default:
                    // This should never happen...
                    Diagnostics.Assert(false, "Invalid langage mode was set when building a ScriptCommandProcessor");
                    throw new InvalidOperationException("Invalid langage mode was set when building a ScriptCommandProcessor");
                }

                if (scriptBlock.UsesCmdletBinding)
                {
                    FunctionInfo functionInfo = new FunctionInfo("", scriptBlock, executionContext);
                    commandProcessorBase = new CommandProcessor(functionInfo, executionContext,
                                                                _useLocalScope ?? false, fromScriptFile: false, sessionState: executionContext.EngineSessionState);
                }
                else
                {
                    commandProcessorBase = new DlrScriptCommandProcessor(scriptBlock,
                                                                         executionContext, _useLocalScope ?? false,
                                                                         origin,
                                                                         executionContext.EngineSessionState);
                }
            }
            else
            {
                // RestrictedLanguage / NoLanguage do not support dot-sourcing when CommandOrigin is Runspace
                if ((_useLocalScope.HasValue) && (!_useLocalScope.Value))
                {
                    switch (executionContext.LanguageMode)
                    {
                    case PSLanguageMode.RestrictedLanguage:
                    case PSLanguageMode.NoLanguage:
                        string message = StringUtil.Format(RunspaceStrings.UseLocalScopeNotAllowed,
                                                           "UseLocalScope",
                                                           PSLanguageMode.RestrictedLanguage.ToString(),
                                                           PSLanguageMode.NoLanguage.ToString());
                        throw new RuntimeException(message);

                    case PSLanguageMode.FullLanguage:
                        // Interactive script commands are permitted in this mode...
                        break;
                    }
                }

                commandProcessorBase =
                    commandFactory.CreateCommand(CommandText, origin, _useLocalScope);
            }

            CommandParameterCollection parameters = Parameters;

            if (parameters != null)
            {
                bool isNativeCommand = commandProcessorBase is NativeCommandProcessor;
                foreach (CommandParameter publicParameter in parameters)
                {
                    CommandParameterInternal internalParameter = CommandParameter.ToCommandParameterInternal(publicParameter, isNativeCommand);
                    commandProcessorBase.AddParameter(internalParameter);
                }
            }

            string       helpTarget;
            HelpCategory helpCategory;

            if (commandProcessorBase.IsHelpRequested(out helpTarget, out helpCategory))
            {
                commandProcessorBase = CommandProcessorBase.CreateGetHelpCommandProcessor(
                    executionContext,
                    helpTarget,
                    helpCategory);
            }

            //Set the merge settings
            SetMergeSettingsOnCommandProcessor(commandProcessorBase);

            return(commandProcessorBase);
        }
示例#40
0
 internal FunctionInfo SetFunction(string name, ScriptBlock function, FunctionInfo originalFunction, ScopedItemOptions options, bool force, CommandOrigin origin, System.Management.Automation.ExecutionContext context)
 {
     return this.SetFunction(name, function, originalFunction, options, force, origin, context, null);
 }
示例#41
0
        protected override int ExecCommandThatDependsOnSelectedNodes(Guid cmdGroup, uint cmdId, uint cmdExecOpt, IntPtr vaIn, IntPtr vaOut, CommandOrigin commandOrigin, IList<HierarchyNode> selectedNodes, out bool handled) {
            if (cmdGroup == Guids.NodejsNpmCmdSet) {
                try {
                    NpmHelpers.GetPathToNpm(
                        Nodejs.GetAbsoluteNodeExePath(
                            ProjectHome,
                            Project.GetNodejsProject().GetProjectProperty(NodeProjectProperty.NodeExePath)
                    ));
                } catch (NpmNotFoundException) {
                    Nodejs.ShowNodejsNotInstalled();
                    handled = true;
                    return VSConstants.S_OK;
                }

                switch (cmdId) {
                    case PkgCmdId.cmdidNpmManageModules:
                        if (!ShowManageModulesCommandOnNode(selectedNodes)) {
                            ModulesNode.ManageModules();
                            handled = true;
                            return VSConstants.S_OK;
                        }

                        var node = selectedNodes[0] as AbstractNpmNode;
                        if (node != null) {
                            var abstractNpmNode = node;
                            abstractNpmNode.ManageNpmModules();
                            handled = true;
                            return VSConstants.S_OK;
                        }
                        break;
                }
            } else if (cmdGroup == Guids.NodejsCmdSet) {
                switch (cmdId) {
                    case PkgCmdId.cmdidSetAsNodejsStartupFile:
                        // Set the StartupFile project property to the Url of this node
                        SetProjectProperty(
                            CommonConstants.StartupFile,
                            CommonUtils.GetRelativeFilePath(ProjectHome, selectedNodes[0].Url)
                        );
                        handled = true;
                        return VSConstants.S_OK;

                    case PkgCmdId.cmdidAddFileCommand:
                        NewFileMenuGroup.NewFileUtilities.CreateNewFile(projectNode: this, containerId: selectedNodes[0].ID);
                        handled = true;
                        return VSConstants.S_OK;
                }
            }

            return base.ExecCommandThatDependsOnSelectedNodes(cmdGroup, cmdId, cmdExecOpt, vaIn, vaOut, commandOrigin, selectedNodes, out handled);
        }
示例#42
0
 internal CmdletInfo AddCmdletToCache(string name, CmdletInfo cmdlet, CommandOrigin origin, System.Management.Automation.ExecutionContext context)
 {
     bool flag = false;
     try
     {
         List<CmdletInfo> list;
         if (!this.GetCmdlets().TryGetValue(name, out list))
         {
             list = new List<CmdletInfo> {
                 cmdlet
             };
             this.GetCmdlets().Add(name, list);
             if ((cmdlet.Options & ScopedItemOptions.AllScope) != ScopedItemOptions.None)
             {
                 this.GetAllScopeCmdlets()[name].Insert(0, cmdlet);
             }
         }
         else
         {
             if (!string.IsNullOrEmpty(cmdlet.ModuleName))
             {
                 foreach (CmdletInfo info in list)
                 {
                     if (string.Equals(cmdlet.FullName, info.FullName, StringComparison.OrdinalIgnoreCase))
                     {
                         if (cmdlet.ImplementingType == info.ImplementingType)
                         {
                             return null;
                         }
                         flag = true;
                         break;
                     }
                 }
             }
             else
             {
                 foreach (CmdletInfo info2 in list)
                 {
                     if (cmdlet.ImplementingType == info2.ImplementingType)
                     {
                         return null;
                     }
                     flag = true;
                     break;
                 }
             }
             if (!flag)
             {
                 list.Insert(0, cmdlet);
             }
         }
     }
     catch (ArgumentException)
     {
         flag = true;
     }
     if (flag)
     {
         throw PSTraceSource.NewNotSupportedException("DiscoveryExceptions", "DuplicateCmdletName", new object[] { cmdlet.Name });
     }
     return this.GetCmdlets()[name][0];
 }
示例#43
0
 internal AliasInfo SetAliasValue(string name, string value, ScopedItemOptions options, System.Management.Automation.ExecutionContext context, bool force, CommandOrigin origin)
 {
     if (!this.GetAliases().ContainsKey(name))
     {
         if (this.GetAliases().Count > (this.AliasCapacity.FastValue - 1))
         {
             SessionStateOverflowException exception = new SessionStateOverflowException(name, SessionStateCategory.Alias, "AliasOverflow", SessionStateStrings.AliasOverflow, new object[] { this.AliasCapacity.FastValue });
             throw exception;
         }
         AliasInfo info = new AliasInfo(name, value, context, options);
         this.GetAliases()[name] = info;
     }
     else
     {
         AliasInfo valueToCheck = this.GetAliases()[name];
         if (((valueToCheck.Options & ScopedItemOptions.Constant) != ScopedItemOptions.None) || (!force && ((valueToCheck.Options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None)))
         {
             SessionStateUnauthorizedAccessException exception2 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Alias, "AliasNotWritable", SessionStateStrings.AliasNotWritable);
             throw exception2;
         }
         if ((options & ScopedItemOptions.Constant) != ScopedItemOptions.None)
         {
             SessionStateUnauthorizedAccessException exception3 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Alias, "AliasCannotBeMadeConstant", SessionStateStrings.AliasCannotBeMadeConstant);
             throw exception3;
         }
         if (((options & ScopedItemOptions.AllScope) == ScopedItemOptions.None) && ((valueToCheck.Options & ScopedItemOptions.AllScope) != ScopedItemOptions.None))
         {
             SessionStateUnauthorizedAccessException exception4 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Alias, "AliasAllScopeOptionCannotBeRemoved", SessionStateStrings.AliasAllScopeOptionCannotBeRemoved);
             throw exception4;
         }
         SessionState.ThrowIfNotVisible(origin, valueToCheck);
         this.RemoveAliasFromCache(valueToCheck.Name, valueToCheck.Definition);
         if (force)
         {
             this.GetAliases().Remove(name);
             valueToCheck = new AliasInfo(name, value, context, options);
             this.GetAliases()[name] = valueToCheck;
         }
         else
         {
             valueToCheck.Options = options;
             valueToCheck.SetDefinition(value, false);
         }
     }
     this.AddAliasToCache(name, value);
     return this.GetAliases()[name];
 }
示例#44
0
 internal AliasInfo SetAliasItem(AliasInfo aliasToSet, bool force, CommandOrigin origin = CommandOrigin.Internal)
 {
     if (!this.GetAliases().ContainsKey(aliasToSet.Name))
     {
         if (this.GetAliases().Count > (this.AliasCapacity.FastValue - 1))
         {
             SessionStateOverflowException exception = new SessionStateOverflowException(aliasToSet.Name, SessionStateCategory.Alias, "AliasOverflow", SessionStateStrings.AliasOverflow, new object[] { this.AliasCapacity.FastValue });
             throw exception;
         }
         this.GetAliases()[aliasToSet.Name] = aliasToSet;
     }
     else
     {
         AliasInfo valueToCheck = this.GetAliases()[aliasToSet.Name];
         SessionState.ThrowIfNotVisible(origin, valueToCheck);
         if (((valueToCheck.Options & ScopedItemOptions.Constant) != ScopedItemOptions.None) || (((valueToCheck.Options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None) && !force))
         {
             SessionStateUnauthorizedAccessException exception2 = new SessionStateUnauthorizedAccessException(aliasToSet.Name, SessionStateCategory.Alias, "AliasNotWritable", SessionStateStrings.AliasNotWritable);
             throw exception2;
         }
         if (((aliasToSet.Options & ScopedItemOptions.AllScope) == ScopedItemOptions.None) && ((valueToCheck.Options & ScopedItemOptions.AllScope) != ScopedItemOptions.None))
         {
             SessionStateUnauthorizedAccessException exception3 = new SessionStateUnauthorizedAccessException(aliasToSet.Name, SessionStateCategory.Alias, "AliasAllScopeOptionCannotBeRemoved", SessionStateStrings.AliasAllScopeOptionCannotBeRemoved);
             throw exception3;
         }
         this.RemoveAliasFromCache(valueToCheck.Name, valueToCheck.Definition);
         this.GetAliases()[aliasToSet.Name] = aliasToSet;
     }
     this.AddAliasToCache(aliasToSet.Name, aliasToSet.Definition);
     return this.GetAliases()[aliasToSet.Name];
 }
示例#45
0
 internal PSVariable GetVariable(string name, CommandOrigin origin)
 {
     PSVariable variable;
     this.TryGetVariable(name, origin, false, out variable);
     return variable;
 }
示例#46
0
 private static CommandInfo TryNormalSearch(string commandName, ExecutionContext context, CommandOrigin commandOrigin, SearchResolutionOptions searchResolutionOptions, CommandTypes commandTypes, ref Exception lastError)
 {
     CommandInfo current = null;
     CommandSearcher searcher = new CommandSearcher(commandName, searchResolutionOptions, commandTypes, context) {
         CommandOrigin = commandOrigin
     };
     try
     {
         if (!searcher.MoveNext())
         {
             if (!commandName.Contains("-") && !commandName.Contains(@"\"))
             {
                 discoveryTracer.WriteLine("The command [{0}] was not found, trying again with get- prepended", new object[] { commandName });
                 commandName = "get" + '-' + commandName;
                 try
                 {
                     current = LookupCommandInfo(commandName, commandTypes, searchResolutionOptions, commandOrigin, context);
                 }
                 catch (CommandNotFoundException)
                 {
                 }
             }
             return current;
         }
         current = searcher.Current;
     }
     catch (ArgumentException exception)
     {
         lastError = exception;
     }
     catch (PathTooLongException exception2)
     {
         lastError = exception2;
     }
     catch (FileLoadException exception3)
     {
         lastError = exception3;
     }
     catch (FormatException exception4)
     {
         lastError = exception4;
     }
     catch (MetadataException exception5)
     {
         lastError = exception5;
     }
     return current;
 }
示例#47
0
        /// <summary>
        /// Sets the variables of the given names to the specified value.
        /// </summary>
        /// <param name="varNames">
        /// The name(s) of the variables to set.
        /// </param>
        /// <param name="varValue">
        /// The value to set the variable to.
        /// </param>
        private void SetVariable(string[] varNames, object varValue)
        {
            CommandOrigin origin = MyInvocation.CommandOrigin;

            foreach (string varName in varNames)
            {
                // First look for existing variables to set.

                List <PSVariable> matchingVariables = new List <PSVariable>();

                bool wasFiltered = false;

                if (!string.IsNullOrEmpty(Scope))
                {
                    // We really only need to find matches if the scope was specified.
                    // If the scope wasn't specified then we need to create the
                    // variable in the local scope.

                    matchingVariables =
                        GetMatchingVariables(varName, Scope, out wasFiltered, /* quiet */ false);
                }
                else
                {
                    // Since the scope wasn't specified, it doesn't matter if there
                    // is a variable in another scope, it only matters if there is a
                    // variable in the local scope.

                    matchingVariables =
                        GetMatchingVariables(
                            varName,
                            System.Management.Automation.StringLiterals.Local,
                            out wasFiltered,
                            false);
                }

                // We only want to create the variable if we are not filtering
                // the name.

                if (matchingVariables.Count == 0 &&
                    !wasFiltered)
                {
                    try
                    {
                        ScopedItemOptions newOptions = ScopedItemOptions.None;

                        if (!string.IsNullOrEmpty(Scope) &&
                            string.Equals("private", Scope, StringComparison.OrdinalIgnoreCase))
                        {
                            newOptions = ScopedItemOptions.Private;
                        }

                        if (_options != null)
                        {
                            newOptions |= (ScopedItemOptions)_options;
                        }

                        object newVarValue = varValue;
                        if (newVarValue == AutomationNull.Value)
                        {
                            newVarValue = null;
                        }

                        PSVariable varToSet =
                            new PSVariable(
                                varName,
                                newVarValue,
                                newOptions);

                        if (Description == null)
                        {
                            Description = string.Empty;
                        }

                        varToSet.Description = Description;

                        // If visibility was specified, set it on the variable
                        if (_visibility != null)
                        {
                            varToSet.Visibility = Visibility;
                        }

                        string action = VariableCommandStrings.SetVariableAction;

                        string target = StringUtil.Format(VariableCommandStrings.SetVariableTarget, varName, newVarValue);

                        if (ShouldProcess(target, action))
                        {
                            object result = null;

                            if (string.IsNullOrEmpty(Scope))
                            {
                                result =
                                    SessionState.Internal.SetVariable(varToSet, Force, origin);
                            }
                            else
                            {
                                result =
                                    SessionState.Internal.SetVariableAtScope(varToSet, Scope, Force, origin);
                            }

                            if (_passThru && result != null)
                            {
                                WriteObject(result);
                            }
                        }
                    }
                    catch (SessionStateException sessionStateException)
                    {
                        WriteError(
                            new ErrorRecord(
                                sessionStateException.ErrorRecord,
                                sessionStateException));
                        continue;
                    }
                    catch (PSArgumentException argException)
                    {
                        WriteError(
                            new ErrorRecord(
                                argException.ErrorRecord,
                                argException));
                        continue;
                    }
                }
                else
                {
                    foreach (PSVariable matchingVariable in matchingVariables)
                    {
                        string action = VariableCommandStrings.SetVariableAction;

                        string target = StringUtil.Format(VariableCommandStrings.SetVariableTarget, matchingVariable.Name, varValue);

                        if (ShouldProcess(target, action))
                        {
                            object result = null;

                            try
                            {
                                // Since the variable existed in the specified scope, or
                                // in the local scope if no scope was specified, use
                                // the reference returned to set the variable properties.

                                // If we want to force setting over a readonly variable
                                // we have to temporarily mark the variable writable.

                                bool wasReadOnly = false;
                                if (Force &&
                                    (matchingVariable.Options & ScopedItemOptions.ReadOnly) != 0)
                                {
                                    matchingVariable.SetOptions(matchingVariable.Options & ~ScopedItemOptions.ReadOnly, true);
                                    wasReadOnly = true;
                                }

                                // Now change the value, options, or description
                                // and set the variable

                                if (varValue != AutomationNull.Value)
                                {
                                    matchingVariable.Value = varValue;

                                    if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage)
                                    {
                                        // In 'ConstrainedLanguage' we want to monitor untrusted values assigned to 'Global:' variables
                                        // and 'Script:' variables, because they may be set from 'ConstrainedLanguage' environment and
                                        // referenced within trusted script block, and thus result in security issues.
                                        // Here we are setting the value of an existing variable and don't know what scope this variable
                                        // is from, so we mark the value as untrusted, regardless of the scope.
                                        ExecutionContext.MarkObjectAsUntrusted(matchingVariable.Value);
                                    }
                                }

                                if (Description != null)
                                {
                                    matchingVariable.Description = Description;
                                }

                                if (_options != null)
                                {
                                    matchingVariable.Options = (ScopedItemOptions)_options;
                                }
                                else
                                {
                                    if (wasReadOnly)
                                    {
                                        matchingVariable.SetOptions(matchingVariable.Options | ScopedItemOptions.ReadOnly, true);
                                    }
                                }

                                // If visibility was specified, set it on the variable
                                if (_visibility != null)
                                {
                                    matchingVariable.Visibility = Visibility;
                                }

                                result = matchingVariable;
                            }
                            catch (SessionStateException sessionStateException)
                            {
                                WriteError(
                                    new ErrorRecord(
                                        sessionStateException.ErrorRecord,
                                        sessionStateException));
                                continue;
                            }
                            catch (PSArgumentException argException)
                            {
                                WriteError(
                                    new ErrorRecord(
                                        argException.ErrorRecord,
                                        argException));
                                continue;
                            }

                            if (_passThru && result != null)
                            {
                                WriteObject(result);
                            }
                        }
                    }
                }
            }
        }
示例#48
0
 internal FunctionInfo SetFunction(string name, ScriptBlock function, FunctionInfo originalFunction, ScopedItemOptions options, bool force, CommandOrigin origin, System.Management.Automation.ExecutionContext context, string helpFile)
 {
     return this.SetFunction(name, function, originalFunction, options, force, origin, context, helpFile, new Func<string, ScriptBlock, FunctionInfo, ScopedItemOptions, System.Management.Automation.ExecutionContext, string, FunctionInfo>(SessionStateScope.CreateFunction));
 }
示例#49
0
        /// <summary>
        /// determine if we should run the specified file
        /// </summary>
        /// <param name="commandInfo">Info on entity to be run.</param>
        /// <param name="origin">The dispatch origin of a command.</param>
        /// <param name="host">Allows access to the host.</param>
        /// <remarks>
        /// This method throws SecurityException in case running is not allowed.
        /// </remarks>
        /// <exception cref="System.Management.Automation.PSSecurityException">
        /// If the derived security manager threw an exception or returned
        /// false with a reason.
        /// </exception>
        internal void ShouldRunInternal(CommandInfo commandInfo,
                                        CommandOrigin origin,
                                        PSHost host)
        {
#if UNIX
            // TODO:PSL this is a workaround since the exception below
            // hides the internal issue of what's going on in terms of
            // execution policy.
            // On non-Windows platform Set/Get-ExecutionPolicy throw
            // PlatformNotSupportedException
            return;
#else
#if DEBUG
            // If we are debugging, let the unit tests swap the file from beneath us
            if (commandInfo.CommandType == CommandTypes.ExternalScript)
            {
                while (Environment.GetEnvironmentVariable("PSCommandDiscoveryPreDelay") != null)
                {
                    System.Threading.Thread.Sleep(100);
                }
            }
#endif

            bool      result       = false;
            bool      defaultCatch = false;
            Exception authorizationManagerException = null;

            try
            {
                lock (_policyCheckLock)
                {
                    result = this.ShouldRun(commandInfo, origin, host, out authorizationManagerException);
                }

#if DEBUG
                // If we are debugging, let the unit tests swap the file from beneath us
                if (commandInfo.CommandType == CommandTypes.ExternalScript)
                {
                    while (Environment.GetEnvironmentVariable("PSCommandDiscoveryPostDelay") != null)
                    {
                        System.Threading.Thread.Sleep(100);
                    }
                }
#endif
            }
            catch (Exception e) // Catch-all OK. 3rd party callout
            {
                authorizationManagerException = e;

                defaultCatch = true;
                result       = false;
            }

            if (!result)
            {
                if (authorizationManagerException != null)
                {
                    if (authorizationManagerException is PSSecurityException)
                    {
                        throw authorizationManagerException;
                    }
                    else
                    {
                        string message = authorizationManagerException.Message;
                        if (defaultCatch)
                        {
                            message = AuthorizationManagerBase.AuthorizationManagerDefaultFailureReason;
                        }

                        PSSecurityException securityException = new PSSecurityException(message, authorizationManagerException);
                        throw securityException;
                    }
                }
                else
                {
                    throw new PSSecurityException(AuthorizationManagerBase.AuthorizationManagerDefaultFailureReason);
                }
            }
#endif
        }
示例#50
0
 internal FunctionInfo SetFunction(string name, ScriptBlock function, FunctionInfo originalFunction, ScopedItemOptions options, bool force, CommandOrigin origin, System.Management.Automation.ExecutionContext context, string helpFile, Func<string, ScriptBlock, FunctionInfo, ScopedItemOptions, System.Management.Automation.ExecutionContext, string, FunctionInfo> functionFactory)
 {
     if (!this.GetFunctions().ContainsKey(name))
     {
         if (this.GetFunctions().Count > (this.FunctionCapacity.FastValue - 1))
         {
             SessionStateOverflowException exception = new SessionStateOverflowException(name, SessionStateCategory.Function, "FunctionOverflow", SessionStateStrings.FunctionOverflow, new object[] { this.FunctionCapacity.FastValue });
             throw exception;
         }
         FunctionInfo info = functionFactory(name, function, originalFunction, options, context, helpFile);
         this.GetFunctions()[name] = info;
         if (IsFunctionOptionSet(info, ScopedItemOptions.AllScope))
         {
             this.GetAllScopeFunctions()[name] = info;
         }
     }
     else
     {
         FunctionInfo valueToCheck = this.GetFunctions()[name];
         SessionState.ThrowIfNotVisible(origin, valueToCheck);
         if (IsFunctionOptionSet(valueToCheck, ScopedItemOptions.Constant) || (!force && IsFunctionOptionSet(valueToCheck, ScopedItemOptions.ReadOnly)))
         {
             SessionStateUnauthorizedAccessException exception2 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Function, "FunctionNotWritable", SessionStateStrings.FunctionNotWritable);
             throw exception2;
         }
         if ((options & ScopedItemOptions.Constant) != ScopedItemOptions.None)
         {
             SessionStateUnauthorizedAccessException exception3 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Function, "FunctionCannotBeMadeConstant", SessionStateStrings.FunctionCannotBeMadeConstant);
             throw exception3;
         }
         if (((options & ScopedItemOptions.AllScope) == ScopedItemOptions.None) && IsFunctionOptionSet(valueToCheck, ScopedItemOptions.AllScope))
         {
             SessionStateUnauthorizedAccessException exception4 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Function, "FunctionAllScopeOptionCannotBeRemoved", SessionStateStrings.FunctionAllScopeOptionCannotBeRemoved);
             throw exception4;
         }
         FunctionInfo info3 = valueToCheck;
         FunctionInfo newFunction = null;
         if (info3 != null)
         {
             newFunction = functionFactory(name, function, originalFunction, options, context, helpFile);
             if (!info3.GetType().Equals(newFunction.GetType()) || (((info3.Options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None) && force))
             {
                 this.GetFunctions()[name] = newFunction;
             }
             else
             {
                 bool flag2 = force || ((options & ScopedItemOptions.ReadOnly) == ScopedItemOptions.None);
                 info3.Update(newFunction, flag2, options, helpFile);
             }
         }
     }
     return this.GetFunctions()[name];
 }
        protected ScriptCommandProcessorBase(ScriptBlock scriptBlock, ExecutionContext context, bool useLocalScope, CommandOrigin origin, SessionStateInternal sessionState)
            : base(new ScriptInfo(string.Empty, scriptBlock, context))
        {
            this._dontUseScopeCommandOrigin = false;
            this._fromScriptFile            = false;

            CommonInitialization(scriptBlock, context, useLocalScope, origin, sessionState);
        }
示例#52
0
 internal PSVariable SetVariable(string name, object value, bool asValue, bool force, SessionStateInternal sessionState, CommandOrigin origin = CommandOrigin.Internal, bool fastPath = false)
 {
     PSVariable variable;
     PSVariable variable2 = value as PSVariable;
     if (fastPath)
     {
         if (this.Parent != null)
         {
             throw new NotImplementedException("fastPath");
         }
         variable = new PSVariable(name, variable2.Value, variable2.Options, variable2.Attributes) {
             Description = variable2.Description
         };
         this.GetPrivateVariables()[name] = variable;
         return variable;
     }
     bool flag = this.TryGetVariable(name, origin, true, out variable);
     if (!asValue && (variable2 != null))
     {
         if (flag)
         {
             if (((variable == null) || variable.IsConstant) || (!force && variable.IsReadOnly))
             {
                 SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Variable, "VariableNotWritable", SessionStateStrings.VariableNotWritable);
                 throw exception;
             }
             if ((variable is LocalVariable) && (variable2.Attributes.Any<Attribute>() || (variable2.Options != variable.Options)))
             {
                 SessionStateUnauthorizedAccessException exception2 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Variable, "VariableNotWritableRare", SessionStateStrings.VariableNotWritableRare);
                 throw exception2;
             }
             if (variable.IsReadOnly && force)
             {
                 this._variables.Remove(name);
                 flag = false;
                 variable = new PSVariable(name, variable2.Value, variable2.Options, variable2.Attributes) {
                     Description = variable2.Description
                 };
             }
             else
             {
                 variable.Attributes.Clear();
                 variable.Value = variable2.Value;
                 variable.Options = variable2.Options;
                 variable.Description = variable2.Description;
                 foreach (Attribute attribute in variable2.Attributes)
                 {
                     variable.Attributes.Add(attribute);
                 }
             }
         }
         else
         {
             variable = variable2;
         }
     }
     else if (variable != null)
     {
         variable.Value = value;
     }
     else
     {
         variable = (this.LocalsTuple != null) ? (this.LocalsTuple.TrySetVariable(name, value)) ?? new PSVariable(name, value) : new PSVariable(name, value);
     }
     if (!flag && (this._variables.Count > (this.VariableCapacity.FastValue - 1)))
     {
         SessionStateOverflowException exception3 = new SessionStateOverflowException(name, SessionStateCategory.Variable, "VariableOverflow", SessionStateStrings.VariableOverflow, new object[] { this.VariableCapacity.FastValue });
         throw exception3;
     }
     if (System.Management.Automation.ExecutionContext.HasEverUsedConstrainedLanguage)
     {
         System.Management.Automation.ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();
         if (((executionContextFromTLS != null) && (executionContextFromTLS.LanguageMode == PSLanguageMode.ConstrainedLanguage)) && ((variable.Options & ScopedItemOptions.AllScope) == ScopedItemOptions.AllScope))
         {
             /* TODO: Review how to  get around this: */ /* throw new PSNotSupportedException(); */
         }
     }
     this._variables[name] = variable;
     variable.SessionState = sessionState;
     return variable;
 }
        /// <summary>
        /// Helper function for setting up command object and commandRuntime object
        /// for script command processor.
        /// </summary>
        protected void CommonInitialization(ScriptBlock scriptBlock, ExecutionContext context, bool useLocalScope, CommandOrigin origin, SessionStateInternal sessionState)
        {
            Diagnostics.Assert(context != null, "execution context cannot be null");
            Diagnostics.Assert(context.Engine != null, "context.engine cannot be null");

            this.CommandSessionState   = sessionState;
            this._context              = context;
            this._rethrowExitException = this.Context.ScriptCommandProcessorShouldRethrowExit;
            this._context.ScriptCommandProcessorShouldRethrowExit = false;

            ScriptCommand scriptCommand = new ScriptCommand {
                CommandInfo = this.CommandInfo
            };

            this.Command = scriptCommand;
            // WinBlue: 219115
            // Set the command origin for the new ScriptCommand object since we're not
            // going through command discovery here where it's usually set.
            this.Command.CommandOriginInternal = origin;
            this.Command.commandRuntime        = this.commandRuntime = new MshCommandRuntime(this.Context, this.CommandInfo, scriptCommand);

            this.CommandScope = useLocalScope
                                    ? CommandSessionState.NewScope(this.FromScriptFile)
                                    : CommandSessionState.CurrentScope;

            this.UseLocalScope = useLocalScope;

            _scriptBlock = scriptBlock;

            // If the script has been dotted, throw an error if it's from a different language mode.
            // Unless it was a script loaded through -File, in which case the danger of dotting other
            // language modes (getting internal functions in the user's state) isn't a danger
            if ((!this.UseLocalScope) && (!this._rethrowExitException))
            {
                ValidateCompatibleLanguageMode(_scriptBlock, context.LanguageMode, Command.MyInvocation);
            }
        }
示例#54
0
 internal bool TryGetVariable(string name, CommandOrigin origin, bool fromNewOrSet, out PSVariable variable)
 {
     if (this.TryGetLocalVariableFromTuple(name, fromNewOrSet, out variable))
     {
         SessionState.ThrowIfNotVisible(origin, variable);
         return true;
     }
     if (this.GetPrivateVariables().TryGetValue(name, out variable))
     {
         SessionState.ThrowIfNotVisible(origin, variable);
         return true;
     }
     return false;
 }
示例#55
0
        /// <summary>
        /// Set a function in the current scope of session state.
        /// </summary>
        /// <param name="name">
        /// The name of the function to set.
        /// </param>
        /// <param name="function">
        /// The new value of the function being set.
        /// </param>
        /// <param name="originalFunction">
        /// The original function (if any) from which the ScriptBlock is derived.
        /// </param>
        /// <param name="force">
        /// If true, the function will be set even if its ReadOnly.
        /// </param>
        /// <param name="origin">
        /// The origin of the caller
        /// </param>
        /// <exception cref="ArgumentException">
        /// If <paramref name="name"/> is null or empty.
        /// or
        /// If <paramref name="function"/> is not a <see cref="FilterInfo">FilterInfo</see>
        /// or <see cref="FunctionInfo">FunctionInfo</see>
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="function"/> is null.
        /// </exception>
        /// <exception cref="SessionStateUnauthorizedAccessException">
        /// If the function is read-only or constant.
        /// </exception>
        internal FunctionInfo SetFunction(
            string name,
            ScriptBlock function,
            FunctionInfo originalFunction,
            bool force,
            CommandOrigin origin)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw PSTraceSource.NewArgumentException("name");
            }

            if (function == null)
            {
                throw PSTraceSource.NewArgumentNullException("function");
            }

            string originalName = name;

            FunctionLookupPath path = new FunctionLookupPath(name);

            name = path.UnqualifiedPath;

            if (string.IsNullOrEmpty(name))
            {
                SessionStateException exception =
                    new SessionStateException(
                        originalName,
                        SessionStateCategory.Function,
                        "ScopedFunctionMustHaveName",
                        SessionStateStrings.ScopedFunctionMustHaveName,
                        ErrorCategory.InvalidArgument);

                throw exception;
            }

            ScopedItemOptions options = ScopedItemOptions.None;

            if (path.IsPrivate)
            {
                options |= ScopedItemOptions.Private;
            }

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

            FunctionInfo result = null;

            SessionStateScope scope = searcher.InitialScope;

            if (searcher.MoveNext())
            {
                scope = searcher.CurrentLookupScope;
                name  = searcher.Name;

                if (path.IsPrivate)
                {
                    // Need to add the Private flag
                    FunctionInfo existingFunction = scope.GetFunction(name);
                    options |= existingFunction.Options;
                    result   = scope.SetFunction(name, function, originalFunction, options, force, origin, ExecutionContext);
                }
                else
                {
                    result = scope.SetFunction(name, function, force, origin, ExecutionContext);
                }
            }
            else
            {
                if (path.IsPrivate)
                {
                    result = scope.SetFunction(name, function, originalFunction, options, force, origin, ExecutionContext);
                }
                else
                {
                    result = scope.SetFunction(name, function, force, origin, ExecutionContext);
                }
            }

            return(result);
        }
示例#56
0
 internal static void ShouldRun(ExecutionContext context, PSHost host, CommandInfo commandInfo, CommandOrigin commandOrigin)
 {
     try
     {
         if ((commandOrigin == CommandOrigin.Runspace) && (commandInfo.Visibility != SessionStateEntryVisibility.Public))
         {
             CommandNotFoundException exception = new CommandNotFoundException(commandInfo.Name, null, "CommandNotFoundException", DiscoveryExceptions.CommandNotFoundException, new object[0]);
             throw exception;
         }
         context.AuthorizationManager.ShouldRunInternal(commandInfo, commandOrigin, host);
     }
     catch (PSSecurityException exception2)
     {
         MshLog.LogCommandHealthEvent(context, exception2, Severity.Warning);
         MshLog.LogCommandLifecycleEvent(context, CommandState.Terminated, commandInfo.Name);
         throw;
     }
 }
示例#57
0
        /// <summary>
        /// Gets the matching variable for the specified name, using the
        /// Include, Exclude, and Scope parameters defined in the base class.
        /// </summary>
        /// <param name="name">
        /// The name or pattern of the variables to retrieve.
        /// </param>
        /// <param name="lookupScope">
        /// The scope to do the lookup in. If null or empty the normal scoping rules apply.
        /// </param>
        /// <param name="wasFiltered">
        /// True is returned if a variable exists of the given name but was filtered
        /// out via globbing, include, or exclude.
        /// </param>
        /// <param name="quiet">
        /// If true, don't report errors when trying to access private variables.
        /// </param>
        /// <returns>
        /// A collection of the variables matching the name, include, and exclude
        /// pattern in the specified scope.
        /// </returns>
        internal List <PSVariable> GetMatchingVariables(string name, string lookupScope, out bool wasFiltered, bool quiet)
        {
            wasFiltered = false;

            List <PSVariable> result = new List <PSVariable>();

            if (string.IsNullOrEmpty(name))
            {
                name = "*";
            }

            bool nameContainsWildcard = WildcardPattern.ContainsWildcardCharacters(name);

            // Now create the filters

            WildcardPattern nameFilter =
                WildcardPattern.Get(
                    name,
                    WildcardOptions.IgnoreCase);

            Collection <WildcardPattern> includeFilters =
                SessionStateUtilities.CreateWildcardsFromStrings(
                    _include,
                    WildcardOptions.IgnoreCase);

            Collection <WildcardPattern> excludeFilters =
                SessionStateUtilities.CreateWildcardsFromStrings(
                    _exclude,
                    WildcardOptions.IgnoreCase);

            if (!nameContainsWildcard)
            {
                // Filter the name here against the include and exclude so that
                // we can report if the name was filtered vs. there being no
                // variable existing of that name.

                bool isIncludeMatch =
                    SessionStateUtilities.MatchesAnyWildcardPattern(
                        name,
                        includeFilters,
                        true);

                bool isExcludeMatch =
                    SessionStateUtilities.MatchesAnyWildcardPattern(
                        name,
                        excludeFilters,
                        false);

                if (!isIncludeMatch || isExcludeMatch)
                {
                    wasFiltered = true;
                    return(result);
                }
            }

            // First get the appropriate view of the variables. If no scope
            // is specified, flatten all scopes to produce a currently active
            // view.

            IDictionary <string, PSVariable> variableTable = null;

            if (string.IsNullOrEmpty(lookupScope))
            {
                variableTable = SessionState.Internal.GetVariableTable();
            }
            else
            {
                variableTable = SessionState.Internal.GetVariableTableAtScope(lookupScope);
            }

            CommandOrigin origin = MyInvocation.CommandOrigin;

            foreach (KeyValuePair <string, PSVariable> entry in variableTable)
            {
                bool isNameMatch    = nameFilter.IsMatch(entry.Key);
                bool isIncludeMatch =
                    SessionStateUtilities.MatchesAnyWildcardPattern(
                        entry.Key,
                        includeFilters,
                        true);

                bool isExcludeMatch =
                    SessionStateUtilities.MatchesAnyWildcardPattern(
                        entry.Key,
                        excludeFilters,
                        false);

                if (isNameMatch)
                {
                    if (isIncludeMatch && !isExcludeMatch)
                    {
                        // See if the variable is visible
                        if (!SessionState.IsVisible(origin, entry.Value))
                        {
                            // In quiet mode, don't report private variable accesses unless they are specific matches...
                            if (quiet || nameContainsWildcard)
                            {
                                wasFiltered = true;
                                continue;
                            }
                            else
                            {
                                // Generate an error for elements that aren't visible...
                                try
                                {
                                    SessionState.ThrowIfNotVisible(origin, entry.Value);
                                }
                                catch (SessionStateException sessionStateException)
                                {
                                    WriteError(
                                        new ErrorRecord(
                                            sessionStateException.ErrorRecord,
                                            sessionStateException));
                                    // Only report the error once...
                                    wasFiltered = true;
                                    continue;
                                }
                            }
                        }

                        result.Add(entry.Value);
                    }
                    else
                    {
                        wasFiltered = true;
                    }
                }
                else
                {
                    if (nameContainsWildcard)
                    {
                        wasFiltered = true;
                    }
                }
            }

            return(result);
        }
示例#58
0
 private static CommandInfo TryModuleAutoDiscovery(string commandName, ExecutionContext context, string originalCommandName, CommandOrigin commandOrigin, SearchResolutionOptions searchResolutionOptions, CommandTypes commandTypes, ref Exception lastError)
 {
     CommandInfo info = null;
     try
     {
         CmdletInfo cmdlet = context.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Get-Module");
         if ((commandOrigin == CommandOrigin.Internal) || ((cmdlet != null) && (cmdlet.Visibility == SessionStateEntryVisibility.Public)))
         {
             cmdlet = context.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Import-Module");
             if ((commandOrigin == CommandOrigin.Internal) || ((cmdlet != null) && (cmdlet.Visibility == SessionStateEntryVisibility.Public)))
             {
                 discoveryTracer.WriteLine("Executing non module-qualified search: {0}", new object[] { commandName });
                 context.CommandDiscovery.RegisterLookupCommandInfoAction("ActiveModuleSearch", commandName);
                 foreach (string str in ModuleUtils.GetDefaultAvailableModuleFiles(true, true, context))
                 {
                     string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(str);
                     Dictionary<string, List<CommandTypes>> dictionary = AnalysisCache.GetExportedCommands(str, false, context);
                     if (dictionary != null)
                     {
                         if (dictionary.ContainsKey(commandName))
                         {
                             CommandInfo commandInfo = new CmdletInfo("Import-Module", typeof(ImportModuleCommand), null, null, context) {
                                 Visibility = cmdlet.Visibility
                             };
                             Command command = new Command(commandInfo);
                             discoveryTracer.WriteLine("Found in module: {0}", new object[] { str });
                             PowerShell shell = PowerShell.Create(RunspaceMode.CurrentRunspace).AddCommand(command).AddParameter("Name", str).AddParameter("Scope", "GLOBAL").AddParameter("PassThru").AddParameter("ErrorAction", ActionPreference.Ignore).AddParameter("WarningAction", ActionPreference.Ignore).AddParameter("Verbose", false).AddParameter("Debug", false);
                             Collection<PSModuleInfo> collection = null;
                             try
                             {
                                 collection = shell.Invoke<PSModuleInfo>();
                             }
                             catch (Exception exception)
                             {
                                 discoveryTracer.WriteLine("Encountered error importing module: {0}", new object[] { exception.Message });
                                 lastError = exception;
                                 CommandProcessorBase.CheckForSevereException(exception);
                             }
                             if ((collection == null) || (collection.Count == 0))
                             {
                                 string resourceStr = StringUtil.Format(DiscoveryExceptions.CouldNotAutoImportMatchingModule, commandName, fileNameWithoutExtension);
                                 CommandNotFoundException exception2 = new CommandNotFoundException(originalCommandName, lastError, "CouldNotAutoloadMatchingModule", resourceStr, new object[0]);
                                 throw exception2;
                             }
                             info = LookupCommandInfo(commandName, commandTypes, searchResolutionOptions, commandOrigin, context);
                         }
                         if (info != null)
                         {
                             return info;
                         }
                     }
                 }
             }
             return info;
         }
         return info;
     }
     catch (CommandNotFoundException)
     {
         throw;
     }
     catch (Exception exception3)
     {
         CommandProcessorBase.CheckForSevereException(exception3);
     }
     finally
     {
         context.CommandDiscovery.UnregisterLookupCommandInfoAction("ActiveModuleSearch", commandName);
     }
     return info;
 }
示例#59
0
        protected override int ExecCommandThatDependsOnSelectedNodes(Guid cmdGroup, uint cmdId, uint cmdExecOpt, IntPtr vaIn, IntPtr vaOut, CommandOrigin commandOrigin, IList <HierarchyNode> selectedNodes, out bool handled)
        {
            if (cmdGroup == Guids.NodejsNpmCmdSet)
            {
                try
                {
                    NpmHelpers.GetPathToNpm(
                        Nodejs.GetAbsoluteNodeExePath(
                            this.ProjectHome,
                            this.Project.GetNodejsProject().GetProjectProperty(NodeProjectProperty.NodeExePath)
                            ));
                }
                catch (NpmNotFoundException)
                {
                    Nodejs.ShowNodejsNotInstalled();
                    handled = true;
                    return(VSConstants.S_OK);
                }

                switch (cmdId)
                {
                case PkgCmdId.cmdidNpmManageModules:
                    if (!ShowManageModulesCommandOnNode(selectedNodes))
                    {
                        this.ModulesNode.ManageModules();
                        handled = true;
                        return(VSConstants.S_OK);
                    }

                    var node = selectedNodes[0] as AbstractNpmNode;
                    if (node != null)
                    {
                        var abstractNpmNode = node;
                        abstractNpmNode.ManageNpmModules();
                        handled = true;
                        return(VSConstants.S_OK);
                    }
                    break;
                }
            }
            else if (cmdGroup == Guids.NodejsCmdSet)
            {
                switch (cmdId)
                {
                case PkgCmdId.cmdidSetAsNodejsStartupFile:
                    // Set the StartupFile project property to the Url of this node
                    SetProjectProperty(
                        CommonConstants.StartupFile,
                        CommonUtils.GetRelativeFilePath(this.ProjectHome, selectedNodes[0].Url)
                        );
                    handled = true;
                    return(VSConstants.S_OK);

                case PkgCmdId.cmdidAddFileCommand:
                    NewFileMenuGroup.NewFileUtilities.CreateNewFile(projectNode: this, containerId: selectedNodes[0].ID);
                    handled = true;
                    return(VSConstants.S_OK);
                }
            }

            return(base.ExecCommandThatDependsOnSelectedNodes(cmdGroup, cmdId, cmdExecOpt, vaIn, vaOut, commandOrigin, selectedNodes, out handled));
        }
示例#60
0
 internal CommandProcessorBase LookupCommandProcessor(string commandName, CommandOrigin commandOrigin, bool? useLocalScope)
 {
     CommandInfo commandInfo = null;
     commandInfo = this.LookupCommandInfo(commandName, commandOrigin);
     CommandProcessorBase base2 = this.LookupCommandProcessor(commandInfo, commandOrigin, useLocalScope, null);
     base2.Command.MyInvocation.InvocationName = commandName;
     return base2;
 }