internal MergedCompiledCommandParameter(
     CompiledCommandParameter parameter,
     ParameterBinderAssociation binderAssociation)
 {
     this.parameter         = parameter != null ? parameter : throw new ArgumentNullException(nameof(parameter));
     this.binderAssociation = binderAssociation;
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Constructs the parameter info using the specified aliases, attributes, and
        /// parameter set metadata.
        /// </summary>
        /// <param name="parameter">
        /// The parameter metadata to retrieve the parameter information from.
        /// </param>
        /// <param name="parameterSetFlag">
        /// The parameter set flag to get the parameter information from.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="parameter"/> is null.
        /// </exception>
        internal CommandParameterInfo(
            CompiledCommandParameter parameter,
            uint parameterSetFlag)
        {
            if (parameter == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(parameter));
            }

            Name          = parameter.Name;
            ParameterType = parameter.Type;
            IsDynamic     = parameter.IsDynamic;
            Aliases       = new ReadOnlyCollection <string>(parameter.Aliases);

            SetAttributes(parameter.CompiledAttributes);
            SetParameterSetData(parameter.GetParameterSetData(parameterSetFlag));
        }
Ejemplo n.º 3
0
        private bool PrepareCommandElements(ExecutionContext context)
        {
            int  num                   = 0;
            bool dotSource             = this._commandAst.InvocationOperator == TokenKind.Dot;
            CommandProcessorBase base2 = null;
            string resolvedCommandName = null;
            bool   flag2               = false;

            try
            {
                base2 = this.PrepareFromAst(context, out resolvedCommandName) ?? context.CreateCommand(resolvedCommandName, dotSource);
            }
            catch (RuntimeException exception)
            {
                CommandProcessorBase.CheckForSevereException(exception);
                if ((this._commandAst.IsInWorkflow() && (resolvedCommandName != null)) && CompletionCompleters.PseudoWorkflowCommands.Contains <string>(resolvedCommandName, StringComparer.OrdinalIgnoreCase))
                {
                    flag2 = true;
                }
                else
                {
                    return(false);
                }
            }
            CommandProcessor           commandProcessor = base2 as CommandProcessor;
            ScriptCommandProcessorBase base3            = base2 as ScriptCommandProcessorBase;
            bool          flag3 = (commandProcessor != null) && commandProcessor.CommandInfo.ImplementsDynamicParameters;
            List <object> list  = flag3 ? new List <object>(this._commandElements.Count) : null;

            if (((commandProcessor != null) || (base3 != null)) || flag2)
            {
                num++;
                while (num < this._commandElements.Count)
                {
                    CommandParameterAst parameterAst = this._commandElements[num] as CommandParameterAst;
                    if (parameterAst != null)
                    {
                        if (list != null)
                        {
                            list.Add(parameterAst.Extent.Text);
                        }
                        AstPair item = (parameterAst.Argument != null) ? new AstPair(parameterAst, parameterAst.Argument) : new AstPair(parameterAst);
                        this._arguments.Add(item);
                    }
                    else
                    {
                        StringConstantExpressionAst ast2 = this._commandElements[num] as StringConstantExpressionAst;
                        if ((ast2 == null) || !ast2.Value.Trim().Equals("-", StringComparison.OrdinalIgnoreCase))
                        {
                            ExpressionAst argumentAst = this._commandElements[num] as ExpressionAst;
                            if (argumentAst != null)
                            {
                                if (list != null)
                                {
                                    list.Add(argumentAst.Extent.Text);
                                }
                                this._arguments.Add(new AstPair(null, argumentAst));
                            }
                        }
                    }
                    num++;
                }
            }
            if (commandProcessor != null)
            {
                this._function = false;
                if (flag3)
                {
                    ParameterBinderController.AddArgumentsToCommandProcessor(commandProcessor, list.ToArray());
                    bool flag4 = false;
                    bool flag5 = false;
                    do
                    {
                        CommandProcessorBase currentCommandProcessor = context.CurrentCommandProcessor;
                        try
                        {
                            context.CurrentCommandProcessor = commandProcessor;
                            commandProcessor.SetCurrentScopeToExecutionScope();
                            if (!flag4)
                            {
                                commandProcessor.CmdletParameterBinderController.BindCommandLineParametersNoValidation(commandProcessor.arguments);
                            }
                            else
                            {
                                flag5 = true;
                                commandProcessor.CmdletParameterBinderController.ClearUnboundArguments();
                                commandProcessor.CmdletParameterBinderController.BindCommandLineParametersNoValidation(new Collection <CommandParameterInternal>());
                            }
                        }
                        catch (ParameterBindingException exception2)
                        {
                            if ((exception2.ErrorId == "MissingArgument") || (exception2.ErrorId == "AmbiguousParameter"))
                            {
                                flag4 = true;
                            }
                        }
                        catch (Exception exception3)
                        {
                            CommandProcessorBase.CheckForSevereException(exception3);
                        }
                        finally
                        {
                            context.CurrentCommandProcessor = currentCommandProcessor;
                            commandProcessor.RestorePreviousScope();
                        }
                    }while (flag4 && !flag5);
                }
                this._commandInfo             = commandProcessor.CommandInfo;
                this._commandName             = commandProcessor.CommandInfo.Name;
                this._bindableParameters      = commandProcessor.CmdletParameterBinderController.BindableParameters;
                this._defaultParameterSetFlag = commandProcessor.CommandInfo.CommandMetadata.DefaultParameterSetFlag;
            }
            else if (base3 != null)
            {
                this._function                = true;
                this._commandInfo             = base3.CommandInfo;
                this._commandName             = base3.CommandInfo.Name;
                this._bindableParameters      = base3.ScriptParameterBinderController.BindableParameters;
                this._defaultParameterSetFlag = 0;
            }
            else if (!flag2)
            {
                return(false);
            }
            if (this._commandAst.IsInWorkflow())
            {
                Type type = Type.GetType("Microsoft.PowerShell.Workflow.AstToWorkflowConverter, Microsoft.PowerShell.Activities, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
                if (type != null)
                {
                    Dictionary <string, Type> dictionary = (Dictionary <string, Type>)type.GetMethod("GetActivityParameters").Invoke(null, new object[] { this._commandAst });
                    if (dictionary != null)
                    {
                        bool flag6 = dictionary.ContainsKey("PSComputerName") && !dictionary.ContainsKey("ComputerName");
                        List <MergedCompiledCommandParameter> source = new List <MergedCompiledCommandParameter>();
                        Collection <Attribute> attributes            = new Collection <Attribute> {
                            new ParameterAttribute()
                        };
                        foreach (KeyValuePair <string, Type> pair2 in dictionary)
                        {
                            if (flag2 || !this._bindableParameters.BindableParameters.ContainsKey(pair2.Key))
                            {
                                Type actualActivityParameterType = GetActualActivityParameterType(pair2.Value);
                                RuntimeDefinedParameter  runtimeDefinedParameter = new RuntimeDefinedParameter(pair2.Key, actualActivityParameterType, attributes);
                                CompiledCommandParameter parameter = new CompiledCommandParameter(runtimeDefinedParameter, false)
                                {
                                    IsInAllSets = true
                                };
                                MergedCompiledCommandParameter parameter3 = new MergedCompiledCommandParameter(parameter, ParameterBinderAssociation.DeclaredFormalParameters);
                                source.Add(parameter3);
                            }
                        }
                        if (source.Any <MergedCompiledCommandParameter>())
                        {
                            MergedCommandParameterMetadata metadata = new MergedCommandParameterMetadata();
                            if (!flag2)
                            {
                                metadata.ReplaceMetadata(this._bindableParameters);
                            }
                            foreach (MergedCompiledCommandParameter parameter5 in source)
                            {
                                metadata.BindableParameters.Add(parameter5.Parameter.Name, parameter5);
                            }
                            this._bindableParameters = metadata;
                        }
                        foreach (string str2 in ignoredWorkflowParameters)
                        {
                            if (this._bindableParameters.BindableParameters.ContainsKey(str2))
                            {
                                this._bindableParameters.BindableParameters.Remove(str2);
                            }
                        }
                        if (this._bindableParameters.BindableParameters.ContainsKey("ComputerName") && flag6)
                        {
                            this._bindableParameters.BindableParameters.Remove("ComputerName");
                            string key = (from aliasPair in this._bindableParameters.AliasedParameters
                                          where string.Equals("ComputerName", aliasPair.Value.Parameter.Name)
                                          select aliasPair.Key).FirstOrDefault <string>();
                            this._bindableParameters.AliasedParameters.Remove(key);
                        }
                    }
                }
            }
            this._unboundParameters.AddRange(this._bindableParameters.BindableParameters.Values);
            CommandBaseAst ast4   = null;
            PipelineAst    parent = this._commandAst.Parent as PipelineAst;

            if (parent.PipelineElements.Count > 1)
            {
                foreach (CommandBaseAst ast6 in parent.PipelineElements)
                {
                    if (ast6.GetHashCode() == this._commandAst.GetHashCode())
                    {
                        this._isPipelineInputExpected = ast4 != null;
                        if (this._isPipelineInputExpected)
                        {
                            this._pipelineInputType = typeof(object);
                        }
                        break;
                    }
                    ast4 = ast6;
                }
            }
            return(true);
        }
Ejemplo n.º 4
0
 internal ParameterBindingResult(CompiledCommandParameter parameter, CommandElementAst value, Object constantValue)
 {
     this.Parameter = new ParameterMetadata(parameter);
     this.Value = value;
     this.ConstantValue = constantValue;
 }
Ejemplo n.º 5
0
        private bool PrepareCommandElements(ExecutionContext context)
        {
            int commandIndex = 0;
            bool dotSource = _commandAst.InvocationOperator == TokenKind.Dot;

            CommandProcessorBase processor = null;
            string commandName = null;
            bool psuedoWorkflowCommand = false;
            try
            {
                processor = PrepareFromAst(context, out commandName) ?? context.CreateCommand(commandName, dotSource);
            }
            catch (RuntimeException rte)
            {
                // Failed to create the CommandProcessor;
                CommandProcessorBase.CheckForSevereException(rte);

                if (_commandAst.IsInWorkflow() &&
                    commandName != null &&
                    CompletionCompleters.PseudoWorkflowCommands.Contains(commandName, StringComparer.OrdinalIgnoreCase))
                {
                    psuedoWorkflowCommand = true;
                }
                else
                {
                    return false;
                }
            }

            var commandProcessor = processor as CommandProcessor;
            var scriptProcessor = processor as ScriptCommandProcessorBase;
            bool implementsDynamicParameters = commandProcessor != null &&
                                               commandProcessor.CommandInfo.ImplementsDynamicParameters;

            var argumentsToGetDynamicParameters = implementsDynamicParameters
                                                      ? new List<object>(_commandElements.Count)
                                                      : null;
            if (commandProcessor != null || scriptProcessor != null || psuedoWorkflowCommand)
            {
                // Pre-processing the arguments -- command arguments
                for (commandIndex++; commandIndex < _commandElements.Count; commandIndex++)
                {
                    var parameter = _commandElements[commandIndex] as CommandParameterAst;
                    if (parameter != null)
                    {
                        if (argumentsToGetDynamicParameters != null)
                        {
                            argumentsToGetDynamicParameters.Add(parameter.Extent.Text);
                        }

                        AstPair parameterArg = parameter.Argument != null
                            ? new AstPair(parameter)
                            : new AstPair(parameter, (ExpressionAst)null);

                        _arguments.Add(parameterArg);
                    }
                    else
                    {
                        var dash = _commandElements[commandIndex] as StringConstantExpressionAst;
                        if (dash != null && dash.Value.Trim().Equals("-", StringComparison.OrdinalIgnoreCase))
                        {
                            // "-" is represented by StringConstantExpressionAst. Most likely the user type a tab here,
                            // and we don't want it be treated as an argument
                            continue;
                        }

                        var expressionArgument = _commandElements[commandIndex] as ExpressionAst;
                        if (expressionArgument != null)
                        {
                            if (argumentsToGetDynamicParameters != null)
                            {
                                argumentsToGetDynamicParameters.Add(expressionArgument.Extent.Text);
                            }

                            _arguments.Add(new AstPair(null, expressionArgument));
                        }
                    }
                }
            }

            if (commandProcessor != null)
            {
                _function = false;
                if (implementsDynamicParameters)
                {
                    ParameterBinderController.AddArgumentsToCommandProcessor(commandProcessor, argumentsToGetDynamicParameters.ToArray());
                    bool retryWithNoArgs = false, alreadyRetried = false;

                    do
                    {
                        CommandProcessorBase oldCurrentCommandProcessor = context.CurrentCommandProcessor;
                        try
                        {
                            context.CurrentCommandProcessor = commandProcessor;
                            commandProcessor.SetCurrentScopeToExecutionScope();
                            // Run method "BindCommandLineParametersNoValidation" to get all available parameters, including the dynamic
                            // parameters (some of them, not necessarilly all. Since we don't do the actual binding, some dynamic parameters
                            // might not be retrieved). 
                            if (!retryWithNoArgs)
                            {
                                // Win8 345299: First try with all unbounded arguments
                                commandProcessor.CmdletParameterBinderController.BindCommandLineParametersNoValidation(commandProcessor.arguments);
                            }
                            else
                            {
                                // Win8 345299: If the first try ended with ParameterBindingException, try again with no arguments
                                alreadyRetried = true;
                                commandProcessor.CmdletParameterBinderController.ClearUnboundArguments();
                                commandProcessor.CmdletParameterBinderController.BindCommandLineParametersNoValidation(new Collection<CommandParameterInternal>());
                            }
                        }
                        catch (ParameterBindingException e)
                        {
                            // Catch the parameter binding exception thrown when Reparsing the argument.
                            //   "MissingArgument" - a single parameter is matched, but no argument is present
                            //   "AmbiguousParameter" - multiple parameters are matched
                            // When such exceptions are caught, retry again without arguments, so as to get dynamic parameters
                            // based on the current provider
                            if (e.ErrorId == "MissingArgument" || e.ErrorId == "AmbiguousParameter")
                                retryWithNoArgs = true;
                        }
                        catch (Exception e)
                        {
                            CommandProcessorBase.CheckForSevereException(e);
                        }
                        finally
                        {
                            context.CurrentCommandProcessor = oldCurrentCommandProcessor;
                            commandProcessor.RestorePreviousScope();
                        }
                    } while (retryWithNoArgs && !alreadyRetried);
                }
                // Get all bindable parameters and initialize the _unboundParameters
                _commandInfo = commandProcessor.CommandInfo;
                _commandName = commandProcessor.CommandInfo.Name;
                _bindableParameters = commandProcessor.CmdletParameterBinderController.BindableParameters;
                _defaultParameterSetFlag = commandProcessor.CommandInfo.CommandMetadata.DefaultParameterSetFlag;
            }
            else if (scriptProcessor != null)
            {
                _function = true;
                _commandInfo = scriptProcessor.CommandInfo;
                _commandName = scriptProcessor.CommandInfo.Name;
                _bindableParameters = scriptProcessor.ScriptParameterBinderController.BindableParameters;
                _defaultParameterSetFlag = 0;
            }
            else if (!psuedoWorkflowCommand)
            {
                // The command is not a function, cmdlet and script cmdlet
                return false;
            }

            if (_commandAst.IsInWorkflow())
            {
                var converterType = Type.GetType(Utils.WorkflowType);
                if (converterType != null)
                {
                    var activityParameters = (Dictionary<string, Type>)converterType.GetMethod("GetActivityParameters").Invoke(null, new object[] { _commandAst });
                    if (activityParameters != null)
                    {
                        bool needToRemoveReplacedProperty = activityParameters.ContainsKey("PSComputerName") &&
                                                            !activityParameters.ContainsKey("ComputerName");

                        var parametersToAdd = new List<MergedCompiledCommandParameter>();
                        var attrCollection = new Collection<Attribute> { new ParameterAttribute() };
                        foreach (var pair in activityParameters)
                        {
                            if (psuedoWorkflowCommand || !_bindableParameters.BindableParameters.ContainsKey(pair.Key))
                            {
                                Type parameterType = GetActualActivityParameterType(pair.Value);
                                var runtimeDefinedParameter = new RuntimeDefinedParameter(pair.Key, parameterType, attrCollection);
                                var compiledCommandParameter = new CompiledCommandParameter(runtimeDefinedParameter, false) { IsInAllSets = true };
                                var mergedCompiledCommandParameter = new MergedCompiledCommandParameter(compiledCommandParameter, ParameterBinderAssociation.DeclaredFormalParameters);
                                parametersToAdd.Add(mergedCompiledCommandParameter);
                            }
                        }
                        if (parametersToAdd.Any())
                        {
                            var mergedBindableParameters = new MergedCommandParameterMetadata();
                            if (!psuedoWorkflowCommand)
                            {
                                mergedBindableParameters.ReplaceMetadata(_bindableParameters);
                            }
                            foreach (var p in parametersToAdd)
                            {
                                mergedBindableParameters.BindableParameters.Add(p.Parameter.Name, p);
                            }
                            _bindableParameters = mergedBindableParameters;
                        }

                        // Remove common parameters that are supported by all commands, but not
                        // by workflows
                        bool fixedReadOnly = false;
                        foreach (var ignored in _ignoredWorkflowParameters)
                        {
                            if (_bindableParameters.BindableParameters.ContainsKey(ignored))
                            {
                                // However, some ignored parameters are explicitly implemented by
                                // activities, so keep them.
                                if (!activityParameters.ContainsKey(ignored))
                                {
                                    if (!fixedReadOnly)
                                    {
                                        _bindableParameters.ResetReadOnly();
                                        fixedReadOnly = true;
                                    }

                                    _bindableParameters.BindableParameters.Remove(ignored);
                                }
                            }
                        }

                        if (_bindableParameters.BindableParameters.ContainsKey("ComputerName") && needToRemoveReplacedProperty)
                        {
                            if (!fixedReadOnly)
                            {
                                _bindableParameters.ResetReadOnly();
                                fixedReadOnly = true;
                            }

                            _bindableParameters.BindableParameters.Remove("ComputerName");
                            string aliasOfComputerName = (from aliasPair in _bindableParameters.AliasedParameters
                                                          where String.Equals("ComputerName", aliasPair.Value.Parameter.Name)
                                                          select aliasPair.Key).FirstOrDefault();
                            if (aliasOfComputerName != null)
                            {
                                _bindableParameters.AliasedParameters.Remove(aliasOfComputerName);
                            }
                        }
                    }
                }
            }
            _unboundParameters.AddRange(_bindableParameters.BindableParameters.Values);

            // Pre-processing the arguments -- pipeline input
            // Check if there is pipeline input
            CommandBaseAst preCmdBaseAst = null;
            var pipe = _commandAst.Parent as PipelineAst;
            Diagnostics.Assert(pipe != null, "CommandAst should has a PipelineAst parent");
            if (pipe.PipelineElements.Count > 1)
            {
                foreach (CommandBaseAst cmdBase in pipe.PipelineElements)
                {
                    if (cmdBase.GetHashCode() == _commandAst.GetHashCode())
                    {
                        _isPipelineInputExpected = preCmdBaseAst != null;
                        if (_isPipelineInputExpected)
                            _pipelineInputType = typeof(object);
                        break;
                    }
                    preCmdBaseAst = cmdBase;
                }
            }

            return true;
        }