Esempio n. 1
0
 internal static CommandParameter FromCommandParameterInternal(CommandParameterInternal internalParameter)
 {
     if (internalParameter == null)
     {
         throw PSTraceSource.NewArgumentNullException("internalParameter");
     }
     string name = null;
     if (internalParameter.ParameterNameSpecified)
     {
         name = internalParameter.ParameterText;
         if (internalParameter.SpaceAfterParameter)
         {
             name = name + " ";
         }
     }
     if (internalParameter.ParameterAndArgumentSpecified)
     {
         return new CommandParameter(name, internalParameter.ArgumentValue);
     }
     if (name != null)
     {
         return new CommandParameter(name);
     }
     return new CommandParameter(null, internalParameter.ArgumentValue);
 }
        } // Arguments

        /// <summary>
        /// Passes the binding directly through to the parameter binder.
        /// It does no verification against metadata.
        /// </summary>
        ///
        /// <param name="argument">
        /// The name and value of the variable to bind.
        /// </param>
        ///
        /// <param name="flags">
        /// Ignored.
        /// </param>
        ///
        /// <returns>
        /// True if the parameter was successfully bound. Any error condition
        /// produces an exception.
        /// </returns>
        ///
        internal override bool BindParameter(
            CommandParameterInternal argument,
            ParameterBindingFlags flags)
        {
            Diagnostics.Assert(false, "Unreachable code");

            throw new InvalidOperationException();
        }
        } // Arguments

        /// <summary>
        /// Passes the binding directly through to the parameter binder.
        /// It does no verification against metadata.
        /// </summary>
        /// 
        /// <param name="argument">
        /// The name and value of the variable to bind.
        /// </param>
        /// 
        /// <param name="flags">
        /// Ignored.
        /// </param>
        /// 
        /// <returns>
        /// True if the parameter was successfully bound. Any error condition
        /// produces an exception.
        /// </returns>
        /// 
        internal override bool BindParameter(
            CommandParameterInternal argument,
            ParameterBindingFlags flags)
        {
            Diagnostics.Assert(false, "Unreachable code");

            throw new InvalidOperationException();
        }
Esempio n. 4
0
        protected IScriptExtent GetParameterErrorExtent(CommandParameterInternal cpi)
        {
            IScriptExtent parameterExtent = cpi.ParameterExtent;

            if (parameterExtent == PositionUtilities.EmptyExtent)
            {
                parameterExtent = this.InvocationInfo.ScriptPosition;
            }
            return(parameterExtent);
        }
Esempio n. 5
0
        internal void ReparseUnboundArguments()
        {
            Collection <CommandParameterInternal> collection = new Collection <CommandParameterInternal>();

            for (int i = 0; i < this._unboundArguments.Count; i++)
            {
                CommandParameterInternal item = this._unboundArguments[i];
                if (!item.ParameterNameSpecified || item.ArgumentSpecified)
                {
                    collection.Add(item);
                }
                else
                {
                    string parameterName = item.ParameterName;
                    MergedCompiledCommandParameter parameter = this._bindableParameters.GetMatchingParameter(parameterName, false, true, new System.Management.Automation.InvocationInfo(this.InvocationInfo.MyCommand, item.ParameterExtent));
                    if (parameter == null)
                    {
                        collection.Add(item);
                    }
                    else if (IsSwitchAndSetValue(parameterName, item, parameter.Parameter))
                    {
                        collection.Add(item);
                    }
                    else if ((this._unboundArguments.Count - 1) > i)
                    {
                        CommandParameterInternal internal3 = this._unboundArguments[i + 1];
                        if (internal3.ParameterNameSpecified)
                        {
                            if ((this._bindableParameters.GetMatchingParameter(internal3.ParameterName, false, true, new System.Management.Automation.InvocationInfo(this.InvocationInfo.MyCommand, internal3.ParameterExtent)) != null) || internal3.ParameterAndArgumentSpecified)
                            {
                                ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetParameterErrorExtent(item), parameter.Parameter.Name, parameter.Parameter.Type, null, "ParameterBinderStrings", "MissingArgument", new object[0]);
                                throw exception;
                            }
                            i++;
                            item.ParameterName = parameter.Parameter.Name;
                            item.SetArgumentValue(internal3.ArgumentExtent, internal3.ParameterText);
                            collection.Add(item);
                        }
                        else
                        {
                            i++;
                            item.ParameterName = parameter.Parameter.Name;
                            item.SetArgumentValue(internal3.ArgumentExtent, internal3.ArgumentValue);
                            collection.Add(item);
                        }
                    }
                    else
                    {
                        ParameterBindingException exception2 = new ParameterBindingException(ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetParameterErrorExtent(item), parameter.Parameter.Name, parameter.Parameter.Type, null, "ParameterBinderStrings", "MissingArgument", new object[0]);
                        throw exception2;
                    }
                }
            }
            this._unboundArguments = collection;
        }
Esempio n. 6
0
 internal static CommandParameterInternal CreateArgument(IScriptExtent extent, object value, bool splatted = false)
 {
     CommandParameterInternal internal2 = new CommandParameterInternal();
     Argument argument = new Argument {
         extent = extent,
         value = value,
         splatted = splatted
     };
     internal2._argument = argument;
     return internal2;
 }
Esempio n. 7
0
 internal static CommandParameterInternal CreateParameter(IScriptExtent extent, string parameterName, string parameterText)
 {
     CommandParameterInternal internal2 = new CommandParameterInternal();
     Parameter parameter = new Parameter {
         extent = extent,
         parameterName = parameterName,
         parameterText = parameterText
     };
     internal2._parameter = parameter;
     return internal2;
 }
Esempio n. 8
0
        internal static SteppablePipeline GetSteppablePipeline(PipelineAst pipelineAst, CommandOrigin commandOrigin)
        {
            PipelineProcessor pipe = new PipelineProcessor();

            System.Management.Automation.ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();
            foreach (CommandAst ast in pipelineAst.PipelineElements.Cast <CommandAst>())
            {
                List <CommandParameterInternal> list = new List <CommandParameterInternal>();
                foreach (CommandElementAst ast2 in ast.CommandElements)
                {
                    CommandParameterAst commandParameterAst = ast2 as CommandParameterAst;
                    if (commandParameterAst != null)
                    {
                        list.Add(GetCommandParameter(commandParameterAst, executionContextFromTLS));
                    }
                    else
                    {
                        ExpressionAst expressionAst = (ExpressionAst)ast2;
                        object        obj2          = Compiler.GetExpressionValue(expressionAst, executionContextFromTLS, (IList)null);
                        bool          splatted      = (expressionAst is VariableExpressionAst) && ((VariableExpressionAst)expressionAst).Splatted;
                        list.Add(CommandParameterInternal.CreateArgument(expressionAst.Extent, obj2, splatted));
                    }
                }
                List <CommandRedirection> list2 = new List <CommandRedirection>();
                foreach (RedirectionAst ast5 in ast.Redirections)
                {
                    list2.Add(GetCommandRedirection(ast5, executionContextFromTLS));
                }
                CommandProcessorBase base2 = AddCommand(pipe, list.ToArray(), ast, list2.ToArray(), executionContextFromTLS);
                base2.Command.CommandOriginInternal      = commandOrigin;
                base2.CommandScope.ScopeOrigin           = commandOrigin;
                base2.Command.MyInvocation.CommandOrigin = commandOrigin;
                CallStackFrame[] frameArray = executionContextFromTLS.Debugger.GetCallStack().ToArray <CallStackFrame>();
                if ((frameArray.Length > 0) && Regex.IsMatch(frameArray[0].Position.Text, "GetSteppablePipeline", RegexOptions.IgnoreCase))
                {
                    InvocationInfo myInvocation = base2.Command.MyInvocation;
                    myInvocation.InvocationName = frameArray[0].InvocationInfo.InvocationName;
                    if (frameArray.Length > 1)
                    {
                        IScriptExtent position = frameArray[1].Position;
                        if ((position != null) && (position != PositionUtilities.EmptyExtent))
                        {
                            myInvocation.DisplayScriptPosition = position;
                        }
                    }
                }
                if ((executionContextFromTLS.CurrentCommandProcessor != null) && (executionContextFromTLS.CurrentCommandProcessor.CommandRuntime != null))
                {
                    base2.CommandRuntime.SetMergeFromRuntime(executionContextFromTLS.CurrentCommandProcessor.CommandRuntime);
                }
            }
            return(new SteppablePipeline(executionContextFromTLS, pipe));
        }
Esempio n. 9
0
        internal static CommandParameterInternal CreateArgument(IScriptExtent extent, object value, bool splatted = false)
        {
            CommandParameterInternal internal2 = new CommandParameterInternal();
            Argument argument = new Argument {
                extent   = extent,
                value    = value,
                splatted = splatted
            };

            internal2._argument = argument;
            return(internal2);
        }
Esempio n. 10
0
        internal static CommandParameterInternal CreateParameter(IScriptExtent extent, string parameterName, string parameterText)
        {
            CommandParameterInternal internal2 = new CommandParameterInternal();
            Parameter parameter = new Parameter {
                extent        = extent,
                parameterName = parameterName,
                parameterText = parameterText
            };

            internal2._parameter = parameter;
            return(internal2);
        }
Esempio n. 11
0
 private bool IsMiniShell()
 {
     for (int i = 0; i < base.arguments.Count; i++)
     {
         CommandParameterInternal internal2 = base.arguments[i];
         if (!internal2.ParameterNameSpecified && (internal2.ArgumentValue is ScriptBlock))
         {
             return(true);
         }
     }
     return(false);
 }
Esempio n. 12
0
        private static bool IsSwitchAndSetValue(string argumentName, CommandParameterInternal argument, CompiledCommandParameter matchingParameter)
        {
            bool flag = false;

            if (matchingParameter.Type == typeof(SwitchParameter))
            {
                argument.ParameterName = argumentName;
                argument.SetArgumentValue(PositionUtilities.EmptyExtent, SwitchParameter.Present);
                flag = true;
            }
            return(flag);
        }
 private bool IsMiniShell()
 {
     for (int index = 0; index < this.arguments.Count; ++index)
     {
         CommandParameterInternal parameterInternal = this.arguments[index];
         if (parameterInternal.Name == null && parameterInternal.Value1 != null && parameterInternal.Value1 is ScriptBlock)
         {
             NativeCommandProcessor.tracer.WriteLine("Argument number {0} is scriptblock. Its value is {1} ", (object)index, (object)parameterInternal.Value1.ToString());
             return(true);
         }
     }
     return(false);
 }
Esempio n. 14
0
        private static CommandParameterInternal GetCommandParameter(CommandParameterAst commandParameterAst, System.Management.Automation.ExecutionContext context)
        {
            ExpressionAst argument      = commandParameterAst.Argument;
            IScriptExtent errorPosition = commandParameterAst.ErrorPosition;

            if (argument == null)
            {
                return(CommandParameterInternal.CreateParameter(errorPosition, commandParameterAst.ParameterName, errorPosition.Text));
            }
            object obj2 = Compiler.GetExpressionValue(argument, context, (IList)null);
            bool   spaceAfterParameter = (errorPosition.EndLineNumber != argument.Extent.StartLineNumber) || (errorPosition.EndColumnNumber != argument.Extent.StartColumnNumber);

            return(CommandParameterInternal.CreateParameterWithArgument(errorPosition, commandParameterAst.ParameterName, errorPosition.Text, argument.Extent, obj2, spaceAfterParameter));
        }
 /// <summary>
 /// Add an argument to the ArgumentList.
 /// We may need to construct the argument out of the parameter text and the argument
 /// in the case that we have a parameter that appears as "-switch:value".
 /// </summary>
 /// <param name="parameter">The parameter associated with the operation.</param>
 /// <param name="argument">The value used with parameter.</param>
 internal void AddToArgumentList(CommandParameterInternal parameter, string argument)
 {
     if (parameter.ParameterNameSpecified && parameter.ParameterText.EndsWith(":"))
     {
         if (argument != parameter.ParameterText)
         {
             _argumentList.Add(parameter.ParameterText + argument);
         }
     }
     else
     {
         _argumentList.Add(argument);
     }
 }
Esempio n. 16
0
        internal virtual bool BindParameter(int parameterSets, CommandParameterInternal argument, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags)
        {
            bool flag = false;

            if (parameter.BinderAssociation == ParameterBinderAssociation.DeclaredFormalParameters)
            {
                flag = this.DefaultParameterBinder.BindParameter(argument, parameter.Parameter, flags);
            }
            if (flag && ((flags & ParameterBindingFlags.IsDefaultValue) == ParameterBindingFlags.None))
            {
                this.UnboundParameters.Remove(parameter);
                this.BoundParameters.Add(parameter.Parameter.Name, parameter);
            }
            return(flag);
        }
Esempio n. 17
0
        private static CommandParameterInternal SplatEnumerableElement(object splattedArgument, IScriptExtent splatExtent)
        {
            PSObject obj2 = splattedArgument as PSObject;

            if (obj2 != null)
            {
                PSPropertyInfo info       = obj2.Properties["<CommandParameterName>"];
                object         baseObject = obj2.BaseObject;
                if (((info != null) && (info.Value is string)) && (baseObject is string))
                {
                    return(CommandParameterInternal.CreateParameter(splatExtent, (string)info.Value, (string)baseObject));
                }
            }
            return(CommandParameterInternal.CreateArgument(splatExtent, splattedArgument, false));
        }
Esempio n. 18
0
 private void ValidateNullOrEmptyArgument(CommandParameterInternal parameter, CompiledCommandParameter parameterMetadata, Type argumentType, object parameterValue, bool recurseIntoCollections)
 {
     if ((parameterValue == null) && (argumentType != typeof(bool?)))
     {
         if (!parameterMetadata.AllowsNullArgument)
         {
             bindingTracer.WriteLine("ERROR: Argument cannot be null", new object[0]);
             ParameterBindingValidationException exception = new ParameterBindingValidationException(ErrorCategory.InvalidData, this.InvocationInfo, this.GetErrorExtent(parameter), parameterMetadata.Name, argumentType, (parameterValue == null) ? null : parameterValue.GetType(), "ParameterBinderStrings", "ParameterArgumentValidationErrorNullNotAllowed", new object[0]);
             throw exception;
         }
     }
     else if (argumentType == typeof(string))
     {
         string str = parameterValue as string;
         if ((str.Length == 0) && !parameterMetadata.AllowsEmptyStringArgument)
         {
             bindingTracer.WriteLine("ERROR: Argument cannot be an empty string", new object[0]);
             ParameterBindingValidationException exception2 = new ParameterBindingValidationException(ErrorCategory.InvalidData, this.InvocationInfo, this.GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, (parameterValue == null) ? null : parameterValue.GetType(), "ParameterBinderStrings", "ParameterArgumentValidationErrorEmptyStringNotAllowed", new object[0]);
             throw exception2;
         }
     }
     else if (recurseIntoCollections)
     {
         switch (parameterMetadata.CollectionTypeInformation.ParameterCollectionType)
         {
         case ParameterCollectionType.IList:
         case ParameterCollectionType.Array:
         case ParameterCollectionType.ICollectionGeneric:
         {
             IEnumerator enumerator = LanguagePrimitives.GetEnumerator(parameterValue);
             bool        flag       = true;
             while (ParserOps.MoveNext(null, null, enumerator))
             {
                 object obj2 = ParserOps.Current(null, enumerator);
                 flag = false;
                 this.ValidateNullOrEmptyArgument(parameter, parameterMetadata, parameterMetadata.CollectionTypeInformation.ElementType, obj2, false);
             }
             if (flag && !parameterMetadata.AllowsEmptyCollectionArgument)
             {
                 bindingTracer.WriteLine("ERROR: Argument cannot be an empty collection", new object[0]);
                 ParameterBindingValidationException exception3 = new ParameterBindingValidationException(ErrorCategory.InvalidData, this.InvocationInfo, this.GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, (parameterValue == null) ? null : parameterValue.GetType(), "ParameterBinderStrings", (parameterMetadata.CollectionTypeInformation.ParameterCollectionType == ParameterCollectionType.Array) ? "ParameterArgumentValidationErrorEmptyArrayNotAllowed" : "ParameterArgumentValidationErrorEmptyCollectionNotAllowed", new object[0]);
                 throw exception3;
             }
             return;
         }
         }
     }
 }
Esempio n. 19
0
        internal virtual bool BindParameter(CommandParameterInternal argument, ParameterBindingFlags flags)
        {
            bool flag = false;
            MergedCompiledCommandParameter parameter = this.BindableParameters.GetMatchingParameter(argument.ParameterName, (flags & ParameterBindingFlags.ThrowOnParameterNotFound) != ParameterBindingFlags.None, true, new System.Management.Automation.InvocationInfo(this.InvocationInfo.MyCommand, argument.ParameterExtent));

            if (parameter == null)
            {
                return(flag);
            }
            if (this.BoundParameters.ContainsKey(parameter.Parameter.Name))
            {
                ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetParameterErrorExtent(argument), argument.ParameterName, null, null, "ParameterBinderStrings", "ParameterAlreadyBound", new object[0]);
                throw exception;
            }
            flags &= ~ParameterBindingFlags.DelayBindScriptBlock;
            return(this.BindParameter(this._currentParameterSetFlag, argument, parameter, flags));
        }
Esempio n. 20
0
 internal static CommandParameterInternal CreateParameterWithArgument(IScriptExtent parameterExtent, string parameterName, string parameterText, IScriptExtent argumentExtent, object value, bool spaceAfterParameter)
 {
     CommandParameterInternal internal2 = new CommandParameterInternal();
     Parameter parameter = new Parameter {
         extent = parameterExtent,
         parameterName = parameterName,
         parameterText = parameterText
     };
     internal2._parameter = parameter;
     Argument argument = new Argument {
         extent = argumentExtent,
         value = value
     };
     internal2._argument = argument;
     internal2._spaceAfterParameter = spaceAfterParameter;
     return internal2;
 }
Esempio n. 21
0
        internal static CommandProcessorBase CreateGetHelpCommandProcessor(ExecutionContext context, string helpTarget, HelpCategory helpCategory)
        {
            if (context == null)
            {
                throw PSTraceSource.NewArgumentNullException("context");
            }
            if (string.IsNullOrEmpty(helpTarget))
            {
                throw PSTraceSource.NewArgumentNullException("helpTarget");
            }
            CommandProcessorBase     base2     = context.CreateCommand("get-help", false);
            CommandParameterInternal parameter = CommandParameterInternal.CreateParameterWithArgument(PositionUtilities.EmptyExtent, "Name", "-Name:", PositionUtilities.EmptyExtent, helpTarget, false);

            base2.AddParameter(parameter);
            parameter = CommandParameterInternal.CreateParameterWithArgument(PositionUtilities.EmptyExtent, "Category", "-Category:", PositionUtilities.EmptyExtent, helpCategory.ToString(), false);
            base2.AddParameter(parameter);
            return(base2);
        }
Esempio n. 22
0
        private bool ShouldContinueUncoercedBind(CommandParameterInternal parameter, CompiledCommandParameter parameterMetadata, ParameterBindingFlags flags, ref object parameterValue)
        {
            bool flag = false;
            Type c    = parameterMetadata.Type;

            if (parameterValue == null)
            {
                return(((c == null) || ((flags & ParameterBindingFlags.IsDefaultValue) != ParameterBindingFlags.None)) || (!c.IsValueType && (c != typeof(string))));
            }
            Type type = parameterValue.GetType();

            if (type == c)
            {
                return(true);
            }
            if (type.IsSubclassOf(c))
            {
                return(true);
            }
            if (c.IsAssignableFrom(type))
            {
                return(true);
            }
            if ((parameterValue is PSObject) && !((PSObject)parameterValue).immediateBaseObjectIsEmpty)
            {
                parameterValue = ((PSObject)parameterValue).BaseObject;
                type           = parameterValue.GetType();
                if (((type == c) || type.IsSubclassOf(c)) || c.IsAssignableFrom(type))
                {
                    return(true);
                }
            }
            if (parameterMetadata.CollectionTypeInformation.ParameterCollectionType != ParameterCollectionType.NotCollection)
            {
                bool   coercionRequired = false;
                object obj2             = this.EncodeCollection(parameter, parameterMetadata.Name, parameterMetadata.CollectionTypeInformation, c, parameterValue, false, out coercionRequired);
                if ((obj2 != null) && !coercionRequired)
                {
                    parameterValue = obj2;
                    flag           = true;
                }
            }
            return(flag);
        }
Esempio n. 23
0
        internal static CommandParameterInternal CreateParameterWithArgument(IScriptExtent parameterExtent, string parameterName, string parameterText, IScriptExtent argumentExtent, object value, bool spaceAfterParameter)
        {
            CommandParameterInternal internal2 = new CommandParameterInternal();
            Parameter parameter = new Parameter {
                extent        = parameterExtent,
                parameterName = parameterName,
                parameterText = parameterText
            };

            internal2._parameter = parameter;
            Argument argument = new Argument {
                extent = argumentExtent,
                value  = value
            };

            internal2._argument            = argument;
            internal2._spaceAfterParameter = spaceAfterParameter;
            return(internal2);
        }
Esempio n. 24
0
 private static CommandParameterInternal GetNextPositionalArgument(List <CommandParameterInternal> unboundArgumentsCollection, Collection <CommandParameterInternal> nonPositionalArguments, ref int unboundArgumentsIndex)
 {
     while (unboundArgumentsIndex < unboundArgumentsCollection.Count)
     {
         CommandParameterInternal item = unboundArgumentsCollection[unboundArgumentsIndex++];
         if (!item.ParameterNameSpecified)
         {
             return(item);
         }
         nonPositionalArguments.Add(item);
         if ((unboundArgumentsCollection.Count - 1) >= unboundArgumentsIndex)
         {
             item = unboundArgumentsCollection[unboundArgumentsIndex];
             if (!item.ParameterNameSpecified)
             {
                 nonPositionalArguments.Add(item);
                 unboundArgumentsIndex++;
             }
         }
     }
     return(null);
 }
Esempio n. 25
0
 private object HandleNullParameterForSpecialTypes(CommandParameterInternal argument, string parameterName, Type toType, object currentValue)
 {
     if (toType == typeof(bool))
     {
         bindingTracer.WriteLine("ERROR: No argument is specified for parameter and parameter type is BOOL", new object[0]);
         ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, null, "ParameterBinderStrings", "ParameterArgumentValidationErrorNullNotAllowed", new object[] { "" });
         throw exception;
     }
     if (toType == typeof(SwitchParameter))
     {
         bindingTracer.WriteLine("Arg is null or not present, parameter type is SWITCHPARAMTER, value is true.", new object[0]);
         return(SwitchParameter.Present);
     }
     if (currentValue == UnboundParameter.Value)
     {
         bindingTracer.TraceError("ERROR: No argument was specified for the parameter and the parameter is not of type bool", new object[0]);
         ParameterBindingException exception2 = new ParameterBindingException(ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetParameterErrorExtent(argument), parameterName, toType, null, "ParameterBinderStrings", "MissingArgument", new object[0]);
         throw exception2;
     }
     bindingTracer.WriteLine("Arg is null, parameter type not bool or SwitchParameter, value is null.", new object[0]);
     return(null);
 }
Esempio n. 26
0
        internal Pipe GetRedirectionPipe(ExecutionContext context, System.Management.Automation.Internal.PipelineProcessor parentPipelineProcessor)
        {
            if (string.IsNullOrWhiteSpace(this.File))
            {
                return(new Pipe {
                    NullPipe = true
                });
            }
            CommandProcessorBase     commandProcessor = context.CreateCommand("out-file", false);
            CommandParameterInternal parameter        = CommandParameterInternal.CreateParameterWithArgument(PositionUtilities.EmptyExtent, "Encoding", "-Encoding:", PositionUtilities.EmptyExtent, "Unicode", false);

            commandProcessor.AddParameter(parameter);
            if (this.Appending)
            {
                parameter = CommandParameterInternal.CreateParameterWithArgument(PositionUtilities.EmptyExtent, "Append", "-Append:", PositionUtilities.EmptyExtent, true, false);
                commandProcessor.AddParameter(parameter);
            }
            parameter = CommandParameterInternal.CreateParameterWithArgument(PositionUtilities.EmptyExtent, "Filepath", "-Filepath:", PositionUtilities.EmptyExtent, this.File, false);
            commandProcessor.AddParameter(parameter);
            this.PipelineProcessor = new System.Management.Automation.Internal.PipelineProcessor();
            this.PipelineProcessor.Add(commandProcessor);
            try
            {
                this.PipelineProcessor.StartStepping(true);
            }
            catch (RuntimeException exception)
            {
                if (exception.ErrorRecord.Exception is ArgumentException)
                {
                    throw InterpreterError.NewInterpreterExceptionWithInnerException(null, typeof(RuntimeException), null, "RedirectionFailed", ParserStrings.RedirectionFailed, exception.ErrorRecord.Exception, new object[] { this.File, exception.ErrorRecord.Exception.Message });
                }
                throw;
            }
            if (parentPipelineProcessor != null)
            {
                parentPipelineProcessor.AddRedirectionPipe(this.PipelineProcessor);
            }
            return(new Pipe(context, this.PipelineProcessor));
        }
Esempio n. 27
0
 private void ValidatePSTypeName(CommandParameterInternal parameter, CompiledCommandParameter parameterMetadata, bool retryOtherBindingAfterFailure, object parameterValue)
 {
     if (parameterValue != null)
     {
         IEnumerable <string> internalTypeNames = PSObject.AsPSObject(parameterValue).InternalTypeNames;
         string pSTypeName = parameterMetadata.PSTypeName;
         if (!internalTypeNames.Contains <string>(pSTypeName, StringComparer.OrdinalIgnoreCase))
         {
             ParameterBindingException exception2;
             object[] arguments = new object[] { ((this.invocationInfo != null) && (this.invocationInfo.MyCommand != null)) ? this.invocationInfo.MyCommand.Name : string.Empty, parameterMetadata.Name, parameterMetadata.Type, parameterValue.GetType(), 0, 0, pSTypeName };
             PSInvalidCastException innerException = new PSInvalidCastException(ErrorCategory.InvalidArgument.ToString(), null, ResourceManagerCache.GetResourceString("ParameterBinderStrings", "MismatchedPSTypeName"), arguments);
             if (!retryOtherBindingAfterFailure)
             {
                 exception2 = new ParameterBindingArgumentTransformationException(innerException, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, parameterValue.GetType(), "ParameterBinderStrings", "MismatchedPSTypeName", new object[] { pSTypeName });
             }
             else
             {
                 exception2 = new ParameterBindingException(innerException, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, parameterValue.GetType(), "ParameterBinderStrings", "MismatchedPSTypeName", new object[] { pSTypeName });
             }
             throw exception2;
         }
     }
 }
 /// <summary>
 /// Add an argument to the ArgumentList.
 /// We may need to construct the argument out of the parameter text and the argument
 /// in the case that we have a parameter that appears as "-switch:value".
 /// </summary>
 /// <param name="parameter">The parameter associated with the operation.</param>
 /// <param name="argument">The value used with parameter.</param>
 internal void AddToArgumentList(CommandParameterInternal parameter, string argument)
 {
     if (parameter.ParameterNameSpecified && parameter.ParameterText.EndsWith(":"))
     {
         if (argument != parameter.ParameterText)
         {
             // Only combine the text and argument if there was no space after the parameter,
             // otherwise, add the parameter and arguments as separate elements.
             if (parameter.SpaceAfterParameter)
             {
                 _argumentList.Add(parameter.ParameterText);
                 _argumentList.Add(argument);
             }
             else
             {
                 _argumentList.Add(parameter.ParameterText + argument);
             }
         }
     }
     else
     {
         _argumentList.Add(argument);
     }
 }
Esempio n. 29
0
        internal static void InvokePipeline (object input, bool ignoreInput, CommandParameterInternal[][] pipeElements, CommandBaseAst[] pipeElementAsts, CommandRedirection[][] commandRedirections, FunctionContext funcContext)
		{
			PipelineProcessor pipelineProcessor = new PipelineProcessor ();
			System.Management.Automation.ExecutionContext context = funcContext._executionContext;
			Pipe pipe = funcContext._outputPipe;
			try {
				if (context.Events != null) {
					context.Events.ProcessPendingActions ();
				}
				if ((input == AutomationNull.Value) && !ignoreInput) {
					AddNoopCommandProcessor (pipelineProcessor, context);
				}
				CommandProcessorBase commandProcessor = null;
				CommandRedirection[] redirections = null;
				for (int i = 0; i < pipeElements.Length; i++) {
					redirections = (commandRedirections != null) ? commandRedirections [i] : null;
					commandProcessor = AddCommand (pipelineProcessor, pipeElements [i], pipeElementAsts [i], redirections, context);
				}
				if ((commandProcessor != null) && !commandProcessor.CommandRuntime.OutputPipe.IsRedirected) {
					pipelineProcessor.LinkPipelineSuccessOutput (pipe ?? new Pipe (new ArrayList ()));
					if (redirections != null) {
						foreach (CommandRedirection redirection in redirections) {
							if (redirection is MergingRedirection) {
								redirection.Bind (pipelineProcessor, commandProcessor, context);
							}
						}
					}
				}
				context.PushPipelineProcessor (pipelineProcessor);
				try {
					pipelineProcessor.SynchronousExecuteEnumerate (input, null, true);
				} finally {
					context.PopPipelineProcessor (false);
				}
			}
            finally
            {
                context.QuestionMarkVariableValue = !pipelineProcessor.ExecutionFailed;
                pipelineProcessor.Dispose();
            }
        }
 internal override bool BindParameter(CommandParameterInternal argument, ParameterBindingFlags flags)
 {
     base.DefaultParameterBinder.BindParameter(argument.ParameterName, argument.ArgumentValue);
     return true;
 }
        /// <summary>
        /// On Windows, just append <paramref name="arg"/>.
        /// On Unix, do globbing as appropriate, otherwise just append <paramref name="arg"/>.
        /// </summary>
        /// <param name="arg">The argument that possibly needs expansion.</param>
        /// <param name="parameter">The parameter associated with the operation.</param>
        /// <param name="usedQuotes">True if the argument was a quoted string (single or double).</param>
        private void PossiblyGlobArg(string arg, CommandParameterInternal parameter, bool usedQuotes)
        {
            var argExpanded = false;

#if UNIX
            // On UNIX systems, we expand arguments containing wildcard expressions against
            // the file system just like bash, etc.
            if (!usedQuotes && WildcardPattern.ContainsWildcardCharacters(arg))
            {
                // See if the current working directory is a filesystem provider location
                // We won't do the expansion if it isn't since native commands can only access the file system.
                var cwdinfo = Context.EngineSessionState.CurrentLocation;

                // If it's a filesystem location then expand the wildcards
                if (cwdinfo.Provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
                {
                    // On UNIX, paths starting with ~ or absolute paths are not normalized
                    bool normalizePath = arg.Length == 0 || !(arg[0] == '~' || arg[0] == '/');

                    // See if there are any matching paths otherwise just add the pattern as the argument
                    Collection <PSObject> paths = null;
                    try
                    {
                        paths = Context.EngineSessionState.InvokeProvider.ChildItem.Get(arg, false);
                    }
                    catch
                    {
                        // Fallthrough will append the pattern unchanged.
                    }

                    // Expand paths, but only from the file system.
                    if (paths?.Count > 0 && paths.All(p => p.BaseObject is FileSystemInfo))
                    {
                        var sep = string.Empty;
                        foreach (var path in paths)
                        {
                            _arguments.Append(sep);
                            sep = " ";
                            var expandedPath = (path.BaseObject as FileSystemInfo).FullName;
                            if (normalizePath)
                            {
                                expandedPath =
                                    Context.SessionState.Path.NormalizeRelativePath(expandedPath, cwdinfo.ProviderPath);
                            }
                            // If the path contains spaces, then add quotes around it.
                            if (NeedQuotes(expandedPath))
                            {
                                _arguments.Append('"');
                                _arguments.Append(expandedPath);
                                _arguments.Append('"');
                            }
                            else
                            {
                                _arguments.Append(expandedPath);
                            }

                            AddToArgumentList(parameter, expandedPath);
                            argExpanded = true;
                        }
                    }
                }
            }
            else if (!usedQuotes)
            {
                // Even if there are no wildcards, we still need to possibly
                // expand ~ into the filesystem provider home directory path
                ProviderInfo fileSystemProvider = Context.EngineSessionState.GetSingleProvider(FileSystemProvider.ProviderName);
                string       home = fileSystemProvider.Home;
                if (string.Equals(arg, "~"))
                {
                    _arguments.Append(home);
                    AddToArgumentList(parameter, home);
                    argExpanded = true;
                }
                else if (arg.StartsWith("~/", StringComparison.OrdinalIgnoreCase))
                {
                    var replacementString = string.Concat(home, arg.AsSpan(1));
                    _arguments.Append(replacementString);
                    AddToArgumentList(parameter, replacementString);
                    argExpanded = true;
                }
            }
#endif // UNIX

            if (!argExpanded)
            {
                _arguments.Append(arg);
                AddToArgumentList(parameter, arg);
            }
        }
Esempio n. 32
0
 /// <summary>
 /// Adds an unbound parameter.
 /// </summary>
 /// <param name="parameter">
 /// The parameter to add to the unbound arguments list
 /// </param>
 internal void AddParameter(CommandParameterInternal parameter)
 {
     Diagnostics.Assert(parameter != null, "Caller to verify parameter argument");
     arguments.Add(parameter);
 } // AddParameter
        /// <summary>
        /// Binds the specified argument to the specified parameter using the appropriate
        /// parameter binder.
        /// </summary>
        /// 
        /// <param name="argument">
        /// The argument to be bound.
        /// </param>
        /// 
        /// <param name="parameter">
        /// The metadata for the parameter to bind the argument to.
        /// </param>
        /// 
        /// <param name="flags">
        /// Flags for type coercion and validation.
        /// </param>
        /// 
        /// <returns>
        /// True if the parameter was successfully bound. False if <paramref name="flags"/> 
        /// has the flag <see cref="ParameterBindingFlags.ShouldCoerceType"/> set and the type does not match the parameter type.
        /// </returns>
        /// 
        private bool BindParameter(
            CommandParameterInternal argument,
            MergedCompiledCommandParameter parameter,
            ParameterBindingFlags flags)
        {
            bool result = false;

            switch (parameter.BinderAssociation)
            {
                case ParameterBinderAssociation.DeclaredFormalParameters:
                    result =
                        DefaultParameterBinder.BindParameter(
                            argument,
                            parameter.Parameter,
                            flags);
                    break;

                case ParameterBinderAssociation.CommonParameters:
                    result =
                        CommonParametersBinder.BindParameter(
                            argument,
                            parameter.Parameter,
                            flags);
                    break;

                case ParameterBinderAssociation.ShouldProcessParameters:
                    Diagnostics.Assert(
                        _commandMetadata.SupportsShouldProcess,
                        "The metadata for the ShouldProcessParameters should only be available if the command supports ShouldProcess");

                    result =
                        ShouldProcessParametersBinder.BindParameter(
                            argument,
                            parameter.Parameter,
                            flags);
                    break;

                case ParameterBinderAssociation.PagingParameters:
                    Diagnostics.Assert(
                        _commandMetadata.SupportsPaging,
                        "The metadata for the PagingParameters should only be available if the command supports paging");

                    result =
                        PagingParametersBinder.BindParameter(
                            argument,
                            parameter.Parameter,
                            flags);
                    break;

                case ParameterBinderAssociation.TransactionParameters:
                    Diagnostics.Assert(
                        _commandMetadata.SupportsTransactions,
                        "The metadata for the TransactionsParameters should only be available if the command supports transactions");

                    result =
                        TransactionParametersBinder.BindParameter(
                            argument,
                            parameter.Parameter,
                            flags);
                    break;

                case ParameterBinderAssociation.DynamicParameters:
                    Diagnostics.Assert(
                        _commandMetadata.ImplementsDynamicParameters,
                        "The metadata for the dynamic parameters should only be available if the command supports IDynamicParameters");

                    if (_dynamicParameterBinder != null)
                    {
                        result =
                            _dynamicParameterBinder.BindParameter(
                                argument,
                                parameter.Parameter,
                                flags);
                    }
                    break;
            }

            if (result && ((flags & ParameterBindingFlags.IsDefaultValue) == 0))
            {
                // Update the current valid parameter set flags

                if (parameter.Parameter.ParameterSetFlags != 0)
                {
                    _currentParameterSetFlag &= parameter.Parameter.ParameterSetFlags;
                }

                UnboundParameters.Remove(parameter);

                if (!BoundParameters.ContainsKey(parameter.Parameter.Name))
                {
                    BoundParameters.Add(parameter.Parameter.Name, parameter);
                }

                if (!BoundArguments.ContainsKey(parameter.Parameter.Name))
                {
                    BoundArguments.Add(parameter.Parameter.Name, argument);
                }

                if (parameter.Parameter.ObsoleteAttribute != null &&
                    (flags & ParameterBindingFlags.IsDefaultValue) == 0 &&
                    !BoundObsoleteParameterNames.Contains(parameter.Parameter.Name))
                {
                    string obsoleteWarning = String.Format(
                        CultureInfo.InvariantCulture,
                        ParameterBinderStrings.UseOfDeprecatedParameterWarning,
                        parameter.Parameter.Name,
                        parameter.Parameter.ObsoleteAttribute.Message);
                    var warningRecord = new WarningRecord(ParameterBinderBase.FQIDParameterObsolete, obsoleteWarning);

                    BoundObsoleteParameterNames.Add(parameter.Parameter.Name);

                    if (ObsoleteParameterWarningList == null)
                        ObsoleteParameterWarningList = new List<WarningRecord>();

                    ObsoleteParameterWarningList.Add(warningRecord);
                }
            }

            return result;
        }
        /// <summary>
        /// Restores the specified parameter to the original value.
        /// </summary>
        /// 
        /// <param name="argumentToBind">
        /// The argument containing the value to restore.
        /// </param>
        /// 
        /// <param name="parameter">
        /// The metadata for the parameter to restore.
        /// </param>
        /// 
        /// <returns>
        /// True if the parameter was restored correctly, or false otherwise.
        /// </returns>
        /// 
        private bool RestoreParameter(CommandParameterInternal argumentToBind, MergedCompiledCommandParameter parameter)
        {
            switch (parameter.BinderAssociation)
            {
                case ParameterBinderAssociation.DeclaredFormalParameters:
                    DefaultParameterBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter);
                    break;

                case ParameterBinderAssociation.CommonParameters:
                    CommonParametersBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter);
                    break;

                case ParameterBinderAssociation.ShouldProcessParameters:
                    Diagnostics.Assert(
                        _commandMetadata.SupportsShouldProcess,
                        "The metadata for the ShouldProcessParameters should only be available if the command supports ShouldProcess");

                    ShouldProcessParametersBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter);
                    break;

                case ParameterBinderAssociation.PagingParameters:
                    Diagnostics.Assert(
                        _commandMetadata.SupportsPaging,
                        "The metadata for the PagingParameters should only be available if the command supports paging");

                    PagingParametersBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter);
                    break;

                case ParameterBinderAssociation.TransactionParameters:
                    Diagnostics.Assert(
                        _commandMetadata.SupportsTransactions,
                        "The metadata for the TransactionParameters should only be available if the command supports Transactions");

                    TransactionParametersBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter);
                    break;

                case ParameterBinderAssociation.DynamicParameters:
                    Diagnostics.Assert(
                        _commandMetadata.ImplementsDynamicParameters,
                        "The metadata for the dynamic parameters should only be available if the command supports IDynamicParameters");

                    if (_dynamicParameterBinder != null)
                    {
                        _dynamicParameterBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter);
                    }
                    break;
            }

            return true;
        }
        private bool BindParameter(CommandParameterInternal argument, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags)
        {
            bool flag = false;
            switch (parameter.BinderAssociation)
            {
                case ParameterBinderAssociation.DeclaredFormalParameters:
                    flag = base.DefaultParameterBinder.BindParameter(argument, parameter.Parameter, flags);
                    break;

                case ParameterBinderAssociation.DynamicParameters:
                    if (this._dynamicParameterBinder != null)
                    {
                        flag = this._dynamicParameterBinder.BindParameter(argument, parameter.Parameter, flags);
                    }
                    break;

                case ParameterBinderAssociation.CommonParameters:
                    flag = this.CommonParametersBinder.BindParameter(argument, parameter.Parameter, flags);
                    break;

                case ParameterBinderAssociation.ShouldProcessParameters:
                    flag = this.ShouldProcessParametersBinder.BindParameter(argument, parameter.Parameter, flags);
                    break;

                case ParameterBinderAssociation.TransactionParameters:
                    flag = this.TransactionParametersBinder.BindParameter(argument, parameter.Parameter, flags);
                    break;

                case ParameterBinderAssociation.PagingParameters:
                    flag = this.PagingParametersBinder.BindParameter(argument, parameter.Parameter, flags);
                    break;
            }
            if (flag && ((flags & ParameterBindingFlags.IsDefaultValue) == ParameterBindingFlags.None))
            {
                if (parameter.Parameter.ParameterSetFlags != 0)
                {
                    base._currentParameterSetFlag &= parameter.Parameter.ParameterSetFlags;
                }
                base.UnboundParameters.Remove(parameter);
                if (!base.BoundParameters.ContainsKey(parameter.Parameter.Name))
                {
                    base.BoundParameters.Add(parameter.Parameter.Name, parameter);
                }
                if (!base.BoundArguments.ContainsKey(parameter.Parameter.Name))
                {
                    base.BoundArguments.Add(parameter.Parameter.Name, argument);
                }
            }
            return flag;
        }
Esempio n. 36
0
 private bool ShouldContinueUncoercedBind(CommandParameterInternal parameter, CompiledCommandParameter parameterMetadata, ParameterBindingFlags flags, ref object parameterValue)
 {
     bool flag = false;
     Type c = parameterMetadata.Type;
     if (parameterValue == null)
     {
         return (((c == null) || ((flags & ParameterBindingFlags.IsDefaultValue) != ParameterBindingFlags.None)) || (!c.IsValueType && (c != typeof(string))));
     }
     Type type = parameterValue.GetType();
     if (type == c)
     {
         return true;
     }
     if (type.IsSubclassOf(c))
     {
         return true;
     }
     if (c.IsAssignableFrom(type))
     {
         return true;
     }
     if ((parameterValue is PSObject) && !((PSObject) parameterValue).immediateBaseObjectIsEmpty)
     {
         parameterValue = ((PSObject) parameterValue).BaseObject;
         type = parameterValue.GetType();
         if (((type == c) || type.IsSubclassOf(c)) || c.IsAssignableFrom(type))
         {
             return true;
         }
     }
     if (parameterMetadata.CollectionTypeInformation.ParameterCollectionType != ParameterCollectionType.NotCollection)
     {
         bool coercionRequired = false;
         object obj2 = this.EncodeCollection(parameter, parameterMetadata.Name, parameterMetadata.CollectionTypeInformation, c, parameterValue, false, out coercionRequired);
         if ((obj2 != null) && !coercionRequired)
         {
             parameterValue = obj2;
             flag = true;
         }
     }
     return flag;
 }
Esempio n. 37
0
 private object HandleNullParameterForSpecialTypes(CommandParameterInternal argument, string parameterName, Type toType, object currentValue)
 {
     if (toType == typeof(bool))
     {
         bindingTracer.WriteLine("ERROR: No argument is specified for parameter and parameter type is BOOL", new object[0]);
         ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, null, "ParameterBinderStrings", "ParameterArgumentValidationErrorNullNotAllowed", new object[] { "" });
         throw exception;
     }
     if (toType == typeof(SwitchParameter))
     {
         bindingTracer.WriteLine("Arg is null or not present, parameter type is SWITCHPARAMTER, value is true.", new object[0]);
         return SwitchParameter.Present;
     }
     if (currentValue == UnboundParameter.Value)
     {
         bindingTracer.TraceError("ERROR: No argument was specified for the parameter and the parameter is not of type bool", new object[0]);
         ParameterBindingException exception2 = new ParameterBindingException(ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetParameterErrorExtent(argument), parameterName, toType, null, "ParameterBinderStrings", "MissingArgument", new object[0]);
         throw exception2;
     }
     bindingTracer.WriteLine("Arg is null, parameter type not bool or SwitchParameter, value is null.", new object[0]);
     return null;
 }
Esempio n. 38
0
 protected IScriptExtent GetParameterErrorExtent(CommandParameterInternal cpi)
 {
     IScriptExtent parameterExtent = cpi.ParameterExtent;
     if (parameterExtent == PositionUtilities.EmptyExtent)
     {
         parameterExtent = this.InvocationInfo.ScriptPosition;
     }
     return parameterExtent;
 }
Esempio n. 39
0
        private static CommandProcessorBase AddCommand(PipelineProcessor pipe, CommandParameterInternal[] commandElements, CommandBaseAst commandBaseAst, CommandRedirection[] redirections, System.Management.Automation.ExecutionContext context)
        {
            object parameterText;
            IScriptExtent parameterExtent;
            CommandProcessorBase base2;
            InternalCommand command;
            string str3;
            HelpCategory category;
            CommandAst ast = commandBaseAst as CommandAst;
            TokenKind kind = (ast != null) ? ast.InvocationOperator : TokenKind.Unknown;
            bool dotSource = kind == TokenKind.Dot;
            SessionStateInternal sessionState = null;
            int index = 0;
            PSModuleInfo info = PSObject.Base(commandElements[0].ArgumentValue) as PSModuleInfo;
            if (info != null)
            {
                if ((info.ModuleType == ModuleType.Binary) && (info.SessionState == null))
                {
                    throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "CantInvokeInBinaryModule", ParserStrings.CantInvokeInBinaryModule, new object[] { info.Name });
                }
                if (info.SessionState == null)
                {
                    throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "CantInvokeInNonImportedModule", ParserStrings.CantInvokeInNonImportedModule, new object[] { info.Name });
                }
                sessionState = info.SessionState.Internal;
                index++;
            }
            CommandParameterInternal internal3 = commandElements[index];
            if (internal3.ParameterNameSpecified)
            {
                parameterText = internal3.ParameterText;
                parameterExtent = internal3.ParameterExtent;
                if (!internal3.ArgumentSpecified)
                {
                }
            }
            else
            {
                parameterText = PSObject.Base(internal3.ArgumentValue);
                parameterExtent = internal3.ArgumentExtent;
            }
            string str = dotSource ? "." : ((kind == TokenKind.Ampersand) ? "&" : null);
            ScriptBlock scriptblock = parameterText as ScriptBlock;
            if (scriptblock != null)
            {
                base2 = CommandDiscovery.CreateCommandProcessorForScript(scriptblock, context, !dotSource, sessionState);
            }
            else
            {
                CommandInfo commandInfo = parameterText as CommandInfo;
                if (commandInfo != null)
                {
                    base2 = context.CommandDiscovery.LookupCommandProcessor(commandInfo, context.EngineSessionState.CurrentScope.ScopeOrigin, new bool?(!dotSource), sessionState);
                }
                else
                {
                    string str2 = (parameterText as string) ?? PSObject.ToStringParser(context, parameterText);
                    str = str ?? str2;
                    if (string.IsNullOrEmpty(str2))
                    {
                        throw InterpreterError.NewInterpreterException(parameterText, typeof(RuntimeException), parameterExtent, "BadExpression", ParserStrings.BadExpression, new object[] { dotSource ? "." : "&" });
                    }
                    try
                    {
                        if (sessionState != null)
                        {
                            SessionStateInternal engineSessionState = context.EngineSessionState;
                            try
                            {
                                context.EngineSessionState = sessionState;
                                base2 = context.CreateCommand(str2, dotSource);
                                goto Label_025D;
                            }
                            finally
                            {
                                context.EngineSessionState = engineSessionState;
                            }
                        }
                        base2 = context.CreateCommand(str2, dotSource);
                    }

                    catch (RuntimeException exception)
                    {
                        if (exception.ErrorRecord.InvocationInfo == null)
                        {
                            InvocationInfo invocationInfo = new InvocationInfo(null, parameterExtent, context) {
                                InvocationName = str
                            };
                            exception.ErrorRecord.SetInvocationInfo(invocationInfo);
                        }
                        throw;
                    }
                }
            }
        Label_025D:
            command = base2.Command;
            base2.UseLocalScope = !dotSource && ((command is ScriptCommand) || (command is PSScriptCmdlet));
            bool flag2 = base2 is NativeCommandProcessor;
            for (int i = index + 1; i < commandElements.Length; i++)
            {
                CommandParameterInternal parameter = commandElements[i];
                if ((!parameter.ParameterNameSpecified || !parameter.ParameterName.Equals("-", StringComparison.OrdinalIgnoreCase)) || flag2)
                {
                    if (parameter.ArgumentSplatted)
                    {
                        foreach (CommandParameterInternal internal6 in Splat(parameter.ArgumentValue, parameter.ArgumentExtent))
                        {
                            base2.AddParameter(internal6);
                        }
                    }
                    else
                    {
                        base2.AddParameter(parameter);
                    }
                }
            }
            if (base2.IsHelpRequested(out str3, out category))
            {
                base2 = CommandProcessorBase.CreateGetHelpCommandProcessor(context, str3, category);
            }
            base2.Command.InvocationExtent = commandBaseAst.Extent;
            base2.Command.MyInvocation.ScriptPosition = commandBaseAst.Extent;
            base2.Command.MyInvocation.InvocationName = str;
            pipe.Add(base2);
            bool flag3 = false;
            bool flag4 = false;
            bool flag5 = false;
            bool flag6 = false;
            if (redirections != null)
            {
                foreach (CommandRedirection redirection in redirections)
                {
                    redirection.Bind(pipe, base2, context);
                    switch (redirection.FromStream)
                    {
                        case RedirectionStream.All:
                            flag3 = true;
                            flag4 = true;
                            flag5 = true;
                            flag6 = true;
                            break;

                        case RedirectionStream.Error:
                            flag3 = true;
                            break;

                        case RedirectionStream.Warning:
                            flag4 = true;
                            break;

                        case RedirectionStream.Verbose:
                            flag5 = true;
                            break;

                        case RedirectionStream.Debug:
                            flag6 = true;
                            break;
                    }
                }
            }
            if (!flag3)
            {
                if (context.ShellFunctionErrorOutputPipe != null)
                {
                    base2.CommandRuntime.ErrorOutputPipe = context.ShellFunctionErrorOutputPipe;
                }
                else
                {
                    base2.CommandRuntime.ErrorOutputPipe.ExternalWriter = context.ExternalErrorOutput;
                }
            }
            if (!flag4 && (context.ExpressionWarningOutputPipe != null))
            {
                base2.CommandRuntime.WarningOutputPipe = context.ExpressionWarningOutputPipe;
                flag4 = true;
            }
            if (!flag5 && (context.ExpressionVerboseOutputPipe != null))
            {
                base2.CommandRuntime.VerboseOutputPipe = context.ExpressionVerboseOutputPipe;
                flag5 = true;
            }
            if (!flag6 && (context.ExpressionDebugOutputPipe != null))
            {
                base2.CommandRuntime.DebugOutputPipe = context.ExpressionDebugOutputPipe;
                flag6 = true;
            }
            if ((context.CurrentCommandProcessor != null) && (context.CurrentCommandProcessor.CommandRuntime != null))
            {
                if (!flag4 && (context.CurrentCommandProcessor.CommandRuntime.WarningOutputPipe != null))
                {
                    base2.CommandRuntime.WarningOutputPipe = context.CurrentCommandProcessor.CommandRuntime.WarningOutputPipe;
                }
                if (!flag5 && (context.CurrentCommandProcessor.CommandRuntime.VerboseOutputPipe != null))
                {
                    base2.CommandRuntime.VerboseOutputPipe = context.CurrentCommandProcessor.CommandRuntime.VerboseOutputPipe;
                }
                if (!flag6 && (context.CurrentCommandProcessor.CommandRuntime.DebugOutputPipe != null))
                {
                    base2.CommandRuntime.DebugOutputPipe = context.CurrentCommandProcessor.CommandRuntime.DebugOutputPipe;
                }
            }
            return base2;
        }
        /// <summary>
        /// Stringize a non-IEnum argument to a native command, adding quotes
        /// and trailing spaces as appropriate. An array gets added as multiple arguments
        /// each of which will be stringized.
        /// </summary>
        /// <param name="context">Execution context instance.</param>
        /// <param name="parameter">The parameter associated with the operation.</param>
        /// <param name="obj">The object to append.</param>
        /// <param name="argArrayAst">If the argument was an array literal, the Ast, otherwise null.</param>
        /// <param name="sawVerbatimArgumentMarker">True if the argument occurs after --%.</param>
        /// <param name="stringConstantType">Bare, SingleQuoted, or DoubleQuoted.</param>
        private void AppendOneNativeArgument(ExecutionContext context, CommandParameterInternal parameter, object obj, ArrayLiteralAst argArrayAst, bool sawVerbatimArgumentMarker, StringConstantType stringConstantType)
        {
            IEnumerator list = LanguagePrimitives.GetEnumerator(obj);

            Diagnostics.Assert((argArrayAst == null) || (obj is object[] && ((object[])obj).Length == argArrayAst.Elements.Count), "array argument and ArrayLiteralAst differ in number of elements");

            int    currentElement = -1;
            string separator      = string.Empty;

            do
            {
                string arg;
                object currentObj;
                if (list == null)
                {
                    arg        = PSObject.ToStringParser(context, obj);
                    currentObj = obj;
                }
                else
                {
                    if (!ParserOps.MoveNext(context, null, list))
                    {
                        break;
                    }

                    currentObj = ParserOps.Current(null, list);
                    arg        = PSObject.ToStringParser(context, currentObj);

                    currentElement += 1;
                    if (currentElement != 0)
                    {
                        separator = GetEnumerableArgSeparator(argArrayAst, currentElement);
                    }
                }

                if (!string.IsNullOrEmpty(arg))
                {
                    // Only add the separator to the argument string rather than adding a separator to the ArgumentList.
                    _arguments.Append(separator);

                    if (sawVerbatimArgumentMarker)
                    {
                        arg = Environment.ExpandEnvironmentVariables(arg);
                        _arguments.Append(arg);

                        // we need to split the argument on spaces
                        _argumentList.AddRange(arg.Split(' ', StringSplitOptions.RemoveEmptyEntries));
                    }
                    else
                    {
                        // We need to add quotes if the argument has unquoted spaces.  The
                        // quotes could appear anywhere inside the string, not just at the start,
                        // e.g.
                        //    $a = 'a"b c"d'
                        //    echoargs $a 'a"b c"d' a"b c"d
                        //
                        // The above should see 3 identical arguments in argv (the command line will
                        // actually have quotes in different places, but the Win32 command line=>argv parser
                        // erases those differences.
                        //
                        // We need to check quotes that the win32 argument parser checks which is currently
                        // just the normal double quotes, no other special quotes.  Also note that mismatched
                        // quotes are supported
                        if (NeedQuotes(arg))
                        {
                            _arguments.Append('"');

                            if (stringConstantType == StringConstantType.DoubleQuoted)
                            {
                                _arguments.Append(ResolvePath(arg, Context));
                                AddToArgumentList(parameter, ResolvePath(arg, Context));
                            }
                            else
                            {
                                _arguments.Append(arg);
                                AddToArgumentList(parameter, arg);
                            }

                            // need to escape all trailing backslashes so the native command receives it correctly
                            // according to http://www.daviddeley.com/autohotkey/parameters/parameters.htm#WINCRULESDOC
                            for (int i = arg.Length - 1; i >= 0 && arg[i] == '\\'; i--)
                            {
                                _arguments.Append('\\');
                            }

                            _arguments.Append('"');
                        }
                        else
                        {
                            if (argArrayAst != null && UseArgumentList)
                            {
                                // We have a literal array, so take the extent, break it on spaces and add them to the argument list.
                                foreach (string element in argArrayAst.Extent.Text.Split(' ', StringSplitOptions.RemoveEmptyEntries))
                                {
                                    PossiblyGlobArg(element, parameter, stringConstantType);
                                }

                                break;
                            }
                            else
                            {
                                PossiblyGlobArg(arg, parameter, stringConstantType);
                            }
                        }
                    }
                }
                else if (UseArgumentList && currentObj != null)
                {
                    // add empty strings to arglist, but not nulls
                    AddToArgumentList(parameter, arg);
                }
            }while (list != null);
        }
Esempio n. 41
0
 private object CoerceTypeAsNeeded(CommandParameterInternal argument, string parameterName, Type toType, ParameterCollectionTypeInformation collectionTypeInfo, object currentValue)
 {
     if (argument == null)
     {
         throw PSTraceSource.NewArgumentNullException("argument");
     }
     if (toType == null)
     {
         throw PSTraceSource.NewArgumentNullException("toType");
     }
     if (collectionTypeInfo == null)
     {
         collectionTypeInfo = new ParameterCollectionTypeInformation(toType);
     }
     object result = currentValue;
     using (bindingTracer.TraceScope("COERCE arg to [{0}]", new object[] { toType }))
     {
         Type c = null;
         try
         {
             if (IsNullParameterValue(currentValue))
             {
                 return this.HandleNullParameterForSpecialTypes(argument, parameterName, toType, currentValue);
             }
             c = currentValue.GetType();
             if (toType.IsAssignableFrom(c))
             {
                 bindingTracer.WriteLine("Parameter and arg types the same, no coercion is needed.", new object[0]);
                 return currentValue;
             }
             bindingTracer.WriteLine("Trying to convert argument value from {0} to {1}", new object[] { c, toType });
             if (toType == typeof(PSObject))
             {
                 if ((this.command != null) && (currentValue == this.command.CurrentPipelineObject.BaseObject))
                 {
                     currentValue = this.command.CurrentPipelineObject;
                 }
                 bindingTracer.WriteLine("The parameter is of type [{0}] and the argument is an PSObject, so the parameter value is the argument value wrapped into an PSObject.", new object[] { toType });
                 return LanguagePrimitives.AsPSObjectOrNull(currentValue);
             }
             if ((toType == typeof(string)) && (c == typeof(PSObject)))
             {
                 PSObject obj3 = (PSObject) currentValue;
                 if (obj3 == AutomationNull.Value)
                 {
                     bindingTracer.WriteLine("CONVERT a null PSObject to a null string.", new object[0]);
                     return null;
                 }
             }
             if (((toType == typeof(bool)) || (toType == typeof(SwitchParameter))) || (toType == typeof(bool?)))
             {
                 Type type = null;
                 if (c == typeof(PSObject))
                 {
                     PSObject obj4 = (PSObject) currentValue;
                     currentValue = obj4.BaseObject;
                     if (currentValue is SwitchParameter)
                     {
                         SwitchParameter parameter = (SwitchParameter) currentValue;
                         currentValue = parameter.IsPresent;
                     }
                     type = currentValue.GetType();
                 }
                 else
                 {
                     type = c;
                 }
                 if (type == typeof(bool))
                 {
                     if (LanguagePrimitives.IsBooleanType(toType))
                     {
                         return ParserOps.BoolToObject((bool) currentValue);
                     }
                     return new SwitchParameter((bool) currentValue);
                 }
                 if (type == typeof(int))
                 {
                     if (((int) LanguagePrimitives.ConvertTo(currentValue, typeof(int), CultureInfo.InvariantCulture)) != 0)
                     {
                         if (LanguagePrimitives.IsBooleanType(toType))
                         {
                             return ParserOps.BoolToObject(true);
                         }
                         return new SwitchParameter(true);
                     }
                     if (LanguagePrimitives.IsBooleanType(toType))
                     {
                         return ParserOps.BoolToObject(false);
                     }
                     return new SwitchParameter(false);
                 }
                 if (LanguagePrimitives.IsNumeric(Type.GetTypeCode(type)))
                 {
                     double num = (double) LanguagePrimitives.ConvertTo(currentValue, typeof(double), CultureInfo.InvariantCulture);
                     if (num == 0.0)
                     {
                         if (LanguagePrimitives.IsBooleanType(toType))
                         {
                             return ParserOps.BoolToObject(false);
                         }
                         return new SwitchParameter(false);
                     }
                     if (LanguagePrimitives.IsBooleanType(toType))
                     {
                         return ParserOps.BoolToObject(true);
                     }
                     return new SwitchParameter(true);
                 }
                 ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, c, "ParameterBinderStrings", "CannotConvertArgument", new object[] { type, "" });
                 throw exception;
             }
             if ((collectionTypeInfo.ParameterCollectionType == ParameterCollectionType.ICollectionGeneric) || (collectionTypeInfo.ParameterCollectionType == ParameterCollectionType.IList))
             {
                 object obj5 = PSObject.Base(currentValue);
                 if (obj5 != null)
                 {
                     ConversionRank conversionRank = LanguagePrimitives.GetConversionRank(obj5.GetType(), toType);
                     if ((((conversionRank == ConversionRank.Constructor) || (conversionRank == ConversionRank.ImplicitCast)) || (conversionRank == ConversionRank.ExplicitCast)) && LanguagePrimitives.TryConvertTo(currentValue, toType, Thread.CurrentThread.CurrentCulture, out result))
                     {
                         return result;
                     }
                 }
             }
             if (collectionTypeInfo.ParameterCollectionType != ParameterCollectionType.NotCollection)
             {
                 bindingTracer.WriteLine("ENCODING arg into collection", new object[0]);
                 bool coercionRequired = false;
                 return this.EncodeCollection(argument, parameterName, collectionTypeInfo, toType, currentValue, collectionTypeInfo.ElementType != null, out coercionRequired);
             }
             if (((((GetIList(currentValue) != null) && (toType != typeof(object))) && ((toType != typeof(PSObject)) && (toType != typeof(PSListModifier)))) && ((!toType.IsGenericType || (toType.GetGenericTypeDefinition() != typeof(PSListModifier<>))) && (!toType.IsGenericType || (toType.GetGenericTypeDefinition() != typeof(FlagsExpression<>))))) && !toType.IsEnum)
             {
                 throw new NotSupportedException();
             }
             bindingTracer.WriteLine("CONVERT arg type to param type using LanguagePrimitives.ConvertTo", new object[0]);
             bool flag2 = false;
             if (this.context.LanguageMode == PSLanguageMode.ConstrainedLanguage)
             {
                 object obj6 = PSObject.Base(currentValue);
                 bool flag3 = obj6 is PSObject;
                 bool flag4 = (obj6 != null) && typeof(IDictionary).IsAssignableFrom(obj6.GetType());
                 flag2 = ((((PSLanguageMode) this.Command.CommandInfo.DefiningLanguageMode) == PSLanguageMode.FullLanguage) && !flag3) && !flag4;
             }
             try
             {
                 if (flag2)
                 {
                     this.context.LanguageMode = PSLanguageMode.FullLanguage;
                 }
                 result = LanguagePrimitives.ConvertTo(currentValue, toType, Thread.CurrentThread.CurrentCulture);
             }
             finally
             {
                 if (flag2)
                 {
                     this.context.LanguageMode = PSLanguageMode.ConstrainedLanguage;
                 }
             }
             bindingTracer.WriteLine("CONVERT SUCCESSFUL using LanguagePrimitives.ConvertTo: [{0}]", new object[] { (result == null) ? "null" : result.ToString() });
             return result;
         }
         catch (NotSupportedException exception2)
         {
             bindingTracer.TraceError("ERROR: COERCE FAILED: arg [{0}] could not be converted to the parameter type [{1}]", new object[] { (result == null) ? "null" : result, toType });
             ParameterBindingException exception3 = new ParameterBindingException(exception2, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, c, "ParameterBinderStrings", "CannotConvertArgument", new object[] { (result == null) ? "null" : result, exception2.Message });
             throw exception3;
         }
         catch (PSInvalidCastException exception4)
         {
             object[] args = new object[] { result ?? "null", toType };
             bindingTracer.TraceError("ERROR: COERCE FAILED: arg [{0}] could not be converted to the parameter type [{1}]", args);
             ParameterBindingException exception5 = new ParameterBindingException(exception4, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, c, "ParameterBinderStrings", "CannotConvertArgumentNoMessage", new object[] { exception4.Message });
             throw exception5;
         }
     }
     return result;
 }
Esempio n. 42
0
        } // ReparseUnboundArgumentsForBinder

        private static bool IsSwitchAndSetValue(
            String argumentName,
            CommandParameterInternal argument,
            CompiledCommandParameter matchingParameter)
        {
            bool result = false;

            if (matchingParameter.Type == typeof(SwitchParameter))
            {
                argument.ParameterName = argumentName;
                argument.SetArgumentValue(PositionUtilities.EmptyExtent, SwitchParameter.Present);
                result = true;
            }

            return result;
        } // EnsureBoolOrSwitchAndSetValue
 internal override bool BindParameter(int parameterSets, CommandParameterInternal argument, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags)
 {
     bool flag = true;
     if ((((flags & ParameterBindingFlags.DelayBindScriptBlock) != ParameterBindingFlags.None) && parameter.Parameter.DoesParameterSetTakePipelineInput(parameterSets)) && argument.ArgumentSpecified)
     {
         object argumentValue = argument.ArgumentValue;
         if (((argumentValue is ScriptBlock) || (argumentValue is DelayedScriptBlockArgument)) && !IsParameterScriptBlockBindable(parameter))
         {
             if (this._commandRuntime.IsClosed && this._commandRuntime.InputPipe.Empty)
             {
                 ParameterBindingException exception = new ParameterBindingException(ErrorCategory.MetadataError, this.Command.MyInvocation, base.GetErrorExtent(argument), parameter.Parameter.Name, parameter.Parameter.Type, null, "ParameterBinderStrings", "ScriptBlockArgumentNoInput", new object[0]);
                 throw exception;
             }
             ParameterBinderBase.bindingTracer.WriteLine("Adding ScriptBlock to delay-bind list for parameter '{0}'", new object[] { parameter.Parameter.Name });
             DelayedScriptBlockArgument argument2 = argumentValue as DelayedScriptBlockArgument;
             if (argument2 == null)
             {
                 argument2 = new DelayedScriptBlockArgument
                 {
                     _argument = argument,
                     _parameterBinder = this
                 };
             }
             if (!this._delayBindScriptBlocks.ContainsKey(parameter))
             {
                 this._delayBindScriptBlocks.Add(parameter, argument2);
             }
             if (parameter.Parameter.ParameterSetFlags != 0)
             {
                 base._currentParameterSetFlag &= parameter.Parameter.ParameterSetFlags;
             }
             base.UnboundParameters.Remove(parameter);
             if (!base.BoundParameters.ContainsKey(parameter.Parameter.Name))
             {
                 base.BoundParameters.Add(parameter.Parameter.Name, parameter);
             }
             if (!base.BoundArguments.ContainsKey(parameter.Parameter.Name))
             {
                 base.BoundArguments.Add(parameter.Parameter.Name, argument);
             }
             if (base.DefaultParameterBinder.RecordBoundParameters && !base.DefaultParameterBinder.CommandLineParameters.ContainsKey(parameter.Parameter.Name))
             {
                 base.DefaultParameterBinder.CommandLineParameters.Add(parameter.Parameter.Name, argument2);
             }
             flag = false;
         }
     }
     bool flag2 = false;
     if (flag)
     {
         try
         {
             flag2 = this.BindParameter(argument, parameter, flags);
         }
         catch (Exception innerException)
         {
             bool flag3 = true;
             if ((flags & ParameterBindingFlags.ShouldCoerceType) == ParameterBindingFlags.None)
             {
                 while (innerException != null)
                 {
                     if (innerException is PSInvalidCastException)
                     {
                         flag3 = false;
                         break;
                     }
                     innerException = innerException.InnerException;
                 }
             }
             if (flag3)
             {
                 throw;
             }
         }
     }
     return flag2;
 }
Esempio n. 44
0
 private void ValidateNullOrEmptyArgument(CommandParameterInternal parameter, CompiledCommandParameter parameterMetadata, Type argumentType, object parameterValue, bool recurseIntoCollections)
 {
     if ((parameterValue == null) && (argumentType != typeof(bool?)))
     {
         if (!parameterMetadata.AllowsNullArgument)
         {
             bindingTracer.WriteLine("ERROR: Argument cannot be null", new object[0]);
             ParameterBindingValidationException exception = new ParameterBindingValidationException(ErrorCategory.InvalidData, this.InvocationInfo, this.GetErrorExtent(parameter), parameterMetadata.Name, argumentType, (parameterValue == null) ? null : parameterValue.GetType(), "ParameterBinderStrings", "ParameterArgumentValidationErrorNullNotAllowed", new object[0]);
             throw exception;
         }
     }
     else if (argumentType == typeof(string))
     {
         string str = parameterValue as string;
         if ((str.Length == 0) && !parameterMetadata.AllowsEmptyStringArgument)
         {
             bindingTracer.WriteLine("ERROR: Argument cannot be an empty string", new object[0]);
             ParameterBindingValidationException exception2 = new ParameterBindingValidationException(ErrorCategory.InvalidData, this.InvocationInfo, this.GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, (parameterValue == null) ? null : parameterValue.GetType(), "ParameterBinderStrings", "ParameterArgumentValidationErrorEmptyStringNotAllowed", new object[0]);
             throw exception2;
         }
     }
     else if (recurseIntoCollections)
     {
         switch (parameterMetadata.CollectionTypeInformation.ParameterCollectionType)
         {
             case ParameterCollectionType.IList:
             case ParameterCollectionType.Array:
             case ParameterCollectionType.ICollectionGeneric:
             {
                 IEnumerator enumerator = LanguagePrimitives.GetEnumerator(parameterValue);
                 bool flag = true;
                 while (ParserOps.MoveNext(null, null, enumerator))
                 {
                     object obj2 = ParserOps.Current(null, enumerator);
                     flag = false;
                     this.ValidateNullOrEmptyArgument(parameter, parameterMetadata, parameterMetadata.CollectionTypeInformation.ElementType, obj2, false);
                 }
                 if (flag && !parameterMetadata.AllowsEmptyCollectionArgument)
                 {
                     bindingTracer.WriteLine("ERROR: Argument cannot be an empty collection", new object[0]);
                     ParameterBindingValidationException exception3 = new ParameterBindingValidationException(ErrorCategory.InvalidData, this.InvocationInfo, this.GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, (parameterValue == null) ? null : parameterValue.GetType(), "ParameterBinderStrings", (parameterMetadata.CollectionTypeInformation.ParameterCollectionType == ParameterCollectionType.Array) ? "ParameterArgumentValidationErrorEmptyArrayNotAllowed" : "ParameterArgumentValidationErrorEmptyCollectionNotAllowed", new object[0]);
                     throw exception3;
                 }
                 return;
             }
         }
     }
 }
        private bool RestoreParameter(CommandParameterInternal argumentToBind, MergedCompiledCommandParameter parameter)
        {
            switch (parameter.BinderAssociation)
            {
                case ParameterBinderAssociation.DeclaredFormalParameters:
                    base.DefaultParameterBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue);
                    break;

                case ParameterBinderAssociation.DynamicParameters:
                    if (this._dynamicParameterBinder != null)
                    {
                        this._dynamicParameterBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue);
                    }
                    break;

                case ParameterBinderAssociation.CommonParameters:
                    this.CommonParametersBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue);
                    break;

                case ParameterBinderAssociation.ShouldProcessParameters:
                    this.ShouldProcessParametersBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue);
                    break;

                case ParameterBinderAssociation.TransactionParameters:
                    this.TransactionParametersBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue);
                    break;

                case ParameterBinderAssociation.PagingParameters:
                    this.PagingParametersBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue);
                    break;
            }
            return true;
        }
Esempio n. 46
0
 private void ValidatePSTypeName(CommandParameterInternal parameter, CompiledCommandParameter parameterMetadata, bool retryOtherBindingAfterFailure, object parameterValue)
 {
     if (parameterValue != null)
     {
         IEnumerable<string> internalTypeNames = PSObject.AsPSObject(parameterValue).InternalTypeNames;
         string pSTypeName = parameterMetadata.PSTypeName;
         if (!internalTypeNames.Contains<string>(pSTypeName, StringComparer.OrdinalIgnoreCase))
         {
             ParameterBindingException exception2;
             object[] arguments = new object[] { ((this.invocationInfo != null) && (this.invocationInfo.MyCommand != null)) ? this.invocationInfo.MyCommand.Name : string.Empty, parameterMetadata.Name, parameterMetadata.Type, parameterValue.GetType(), 0, 0, pSTypeName };
             PSInvalidCastException innerException = new PSInvalidCastException(ErrorCategory.InvalidArgument.ToString(), null, ResourceManagerCache.GetResourceString("ParameterBinderStrings", "MismatchedPSTypeName"), arguments);
             if (!retryOtherBindingAfterFailure)
             {
                 exception2 = new ParameterBindingArgumentTransformationException(innerException, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, parameterValue.GetType(), "ParameterBinderStrings", "MismatchedPSTypeName", new object[] { pSTypeName });
             }
             else
             {
                 exception2 = new ParameterBindingException(innerException, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, parameterValue.GetType(), "ParameterBinderStrings", "MismatchedPSTypeName", new object[] { pSTypeName });
             }
             throw exception2;
         }
     }
 }
        /// <summary>
        /// Binds the specified argument to the specified parameter using the appropriate
        /// parameter binder. If the argument is of type ScriptBlock and the parameter takes
        /// pipeline input, then the ScriptBlock is saved off in the delay-bind ScriptBlock
        /// container for further processing of pipeline input and is not bound as the argument
        /// to the parameter.
        /// </summary>
        /// 
        /// <param name="parameterSets">
        /// The parameter set used to bind the arguments.
        /// </param>
        /// 
        /// <param name="argument">
        /// The argument to be bound.
        /// </param>
        /// 
        /// <param name="parameter">
        /// The metadata for the parameter to bind the argument to.
        /// </param>
        /// 
        /// <param name="flags">
        /// Flags for type coercion, validation, and script block binding.
        /// 
        /// ParameterBindingFlags.DelayBindScriptBlock:
        /// If set, arguments that are of type ScriptBlock where the parameter is not of type ScriptBlock,
        /// Object, or PSObject will be stored for execution during pipeline input and not bound as
        /// an argument to the parameter.
        /// </param>
        /// 
        /// <returns>
        /// True if the parameter was successfully bound. False if <paramref name="flags"/> 
        /// has the flag <see cref="ParameterBindingFlags.ShouldCoerceType"/> set and the type does not match the parameter type.
        /// </returns>
        /// 
        internal override bool BindParameter(
            uint parameterSets,
            CommandParameterInternal argument,
            MergedCompiledCommandParameter parameter,
            ParameterBindingFlags flags)
        {
            // Now we need to check to see if the argument value is
            // a ScriptBlock.  If it is and the parameter type is
            // not ScriptBlock and not Object, then we need to delay 
            // binding until a pipeline object is provided to invoke 
            // the ScriptBlock.

            // Note: we haven't yet determined that only a single parameter
            // set is valid, so we have to take a best guess on pipeline input
            // based on the current valid parameter sets.

            bool continueWithBinding = true;

            if ((flags & ParameterBindingFlags.DelayBindScriptBlock) != 0 &&
                parameter.Parameter.DoesParameterSetTakePipelineInput(parameterSets) &&
                argument.ArgumentSpecified)
            {
                object argumentValue = argument.ArgumentValue;
                if ((argumentValue is ScriptBlock || argumentValue is DelayedScriptBlockArgument) &&
                    !IsParameterScriptBlockBindable(parameter))
                {
                    // Now check to see if the command expects to have pipeline input.
                    // If not, we should throw an exception now to inform the
                    // user with more information than they would get if it was
                    // considered an unbound mandatory parameter.

                    if (_commandRuntime.IsClosed && _commandRuntime.InputPipe.Empty)
                    {
                        ParameterBindingException bindingException =
                            new ParameterBindingException(
                                    ErrorCategory.MetadataError,
                                    this.Command.MyInvocation,
                                    GetErrorExtent(argument),
                                    parameter.Parameter.Name,
                                    parameter.Parameter.Type,
                                    null,
                                    ParameterBinderStrings.ScriptBlockArgumentNoInput,
                                    "ScriptBlockArgumentNoInput");

                        throw bindingException;
                    }

                    ParameterBinderBase.bindingTracer.WriteLine(
                        "Adding ScriptBlock to delay-bind list for parameter '{0}'",
                        parameter.Parameter.Name);

                    // We need to delay binding of this argument to the parameter

                    DelayedScriptBlockArgument delayedArg = argumentValue as DelayedScriptBlockArgument ??
                                                            new DelayedScriptBlockArgument { _argument = argument, _parameterBinder = this };
                    if (!_delayBindScriptBlocks.ContainsKey(parameter))
                    {
                        _delayBindScriptBlocks.Add(parameter, delayedArg);
                    }

                    // We treat the parameter as bound, but really the
                    // script block gets run for each pipeline object and
                    // the result is bound.

                    if (parameter.Parameter.ParameterSetFlags != 0)
                    {
                        _currentParameterSetFlag &= parameter.Parameter.ParameterSetFlags;
                    }

                    UnboundParameters.Remove(parameter);

                    BoundParameters[parameter.Parameter.Name] = parameter;
                    BoundArguments[parameter.Parameter.Name] = argument;

                    if (DefaultParameterBinder.RecordBoundParameters &&
                        !DefaultParameterBinder.CommandLineParameters.ContainsKey(parameter.Parameter.Name))
                    {
                        DefaultParameterBinder.CommandLineParameters.Add(parameter.Parameter.Name, delayedArg);
                    }

                    continueWithBinding = false;
                }
            }

            bool result = false;
            if (continueWithBinding)
            {
                try
                {
                    result = BindParameter(argument, parameter, flags);
                }
                catch (Exception e)
                {
                    bool rethrow = true;
                    if ((flags & ParameterBindingFlags.ShouldCoerceType) == 0)
                    {
                        // Attributes are used to do type coercion and result in various exceptions.
                        // We assume that if we aren't trying to do type coercion, we should avoid
                        // propagating type conversion exceptions.
                        while (e != null)
                        {
                            if (e is PSInvalidCastException)
                            {
                                rethrow = false;
                                break;
                            }
                            e = e.InnerException;
                        }
                    }
                    if (rethrow)
                    {
                        throw;
                    }
                }
            }

            return result;
        }
Esempio n. 48
0
 protected IScriptExtent GetParameterErrorExtent(CommandParameterInternal cpi)
 {
     var result = cpi.ParameterExtent;
     if (result == PositionUtilities.EmptyExtent)
         result = InvocationInfo.ScriptPosition;
     // Can't use this assertion - we don't have useful positions when invoked via PowerShell API
     //Diagnostics.Assert(result != PositionUtilities.EmptyExtent, "We are missing a valid position somewhere");
     return result;
 }
Esempio n. 49
0
 internal void AddParameter(CommandParameterInternal parameter)
 {
     this.arguments.Add(parameter);
 }
 /// <summary>
 /// Passes the binding directly through to the parameter binder.
 /// It does no verification against metadata.
 /// </summary>
 /// <param name="argument">
 /// The name and value of the variable to bind.
 /// </param>
 /// <param name="flags">
 /// Ignored.
 /// </param>
 /// <returns>
 /// True if the parameter was successfully bound. Any error condition
 /// produces an exception.
 /// </returns>
 internal override bool BindParameter(CommandParameterInternal argument, ParameterBindingFlags flags)
 {
     // Just pass the binding straight through.  No metadata to verify the parameter against.
     DefaultParameterBinder.BindParameter(argument.ParameterName, argument.ArgumentValue, parameterMetadata: null);
     return(true);
 }
Esempio n. 51
0
        private bool BindPositionalParametersInSet(
            uint validParameterSets,
            Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter> nextPositionalParameters,
            CommandParameterInternal argument,
            ParameterBindingFlags flags,
            out ParameterBindingException bindingException
            )
        {
            bool result = false;
            bindingException = null;

            foreach (PositionalCommandParameter parameter in nextPositionalParameters.Values)
            {
                foreach (ParameterSetSpecificMetadata parameterSetData in parameter.ParameterSetData)
                {
                    // if the parameter is not in the specified parameter set, don't consider it

                    if ((validParameterSets & parameterSetData.ParameterSetFlag) == 0 &&
                        !parameterSetData.IsInAllSets)
                    {
                        continue;
                    }

                    bool bindResult = false;
                    string parameterName = parameter.Parameter.Parameter.Name;

                    ParameterBindingException parameterBindingExceptionToThrown = null;
                    try
                    {
                        CommandParameterInternal bindableArgument =
                            CommandParameterInternal.CreateParameterWithArgument(
                                PositionUtilities.EmptyExtent, parameterName, "-" + parameterName + ":",
                                argument.ArgumentExtent, argument.ArgumentValue,
                                false);

                        bindResult =
                            BindParameter(
                                validParameterSets,
                                bindableArgument,
                                parameter.Parameter,
                                flags);
                    }
                    catch (ParameterBindingArgumentTransformationException pbex)
                    {
                        parameterBindingExceptionToThrown = pbex;
                    }
                    catch (ParameterBindingValidationException pbex)
                    {
                        if (pbex.SwallowException)
                        {
                            // Just ignore and continue
                            bindResult = false;
                            bindingException = pbex;
                        }
                        else
                        {
                            parameterBindingExceptionToThrown = pbex;
                        }
                    }
                    catch (ParameterBindingParameterDefaultValueException pbex)
                    {
                        parameterBindingExceptionToThrown = pbex;
                    }
                    catch (ParameterBindingException e)
                    {
                        // Just ignore and continue;
                        bindResult = false;
                        bindingException = e;
                    }

                    if (parameterBindingExceptionToThrown != null)
                    {
                        if (!DefaultParameterBindingInUse)
                        {
                            throw parameterBindingExceptionToThrown;
                        }
                        else
                        {
                            ThrowElaboratedBindingException(parameterBindingExceptionToThrown);
                        }
                    }

                    if (bindResult)
                    {
                        result = true;
                        this.CommandLineParameters.MarkAsBoundPositionally(parameterName);
                        break;
                    }
                }
            }
            return result;
        }
Esempio n. 52
0
        /// <summary>
        /// Bind the argument to the specified parameter
        /// </summary>
        /// 
        /// <param name="argument">
        /// The argument to be bound.
        /// </param>
        /// 
        /// <param name="flags">
        /// The flags for type coercion, validation, and script block binding.
        /// </param>
        /// 
        /// <returns>
        /// True if the parameter was successfully bound. False if <paramref name="flags"/> does not have the
        /// flag <see>ParameterBindingFlags.ShouldCoerceType</see> and the type does not match the parameter type.
        /// </returns>
        /// 
        /// <exception cref="ParameterBindingException">
        /// If argument transformation fails.
        /// or
        /// The argument could not be coerced to the appropriate type for the parameter.
        /// or
        /// The parameter argument transformation, prerequisite, or validation failed.
        /// or
        /// If the binding to the parameter fails.
        /// or
        /// The parameter has already been bound.
        /// </exception>
        /// 
        internal virtual bool BindParameter(
            CommandParameterInternal argument,
            ParameterBindingFlags flags)
        {
            bool result = false;

            MergedCompiledCommandParameter matchingParameter =
                BindableParameters.GetMatchingParameter(
                    argument.ParameterName,
                    (flags & ParameterBindingFlags.ThrowOnParameterNotFound) != 0,
                    true,
                    new InvocationInfo(this.InvocationInfo.MyCommand, argument.ParameterExtent));

            if (matchingParameter != null)
            {
                // Now check to make sure it hasn't already been
                // bound by looking in the boundParameters collection

                if (BoundParameters.ContainsKey(matchingParameter.Parameter.Name))
                {
                    ParameterBindingException bindingException =
                        new ParameterBindingException(
                            ErrorCategory.InvalidArgument,
                            this.InvocationInfo,
                            GetParameterErrorExtent(argument),
                            argument.ParameterName,
                            null,
                            null,
                            ParameterBinderStrings.ParameterAlreadyBound,
                            "ParameterAlreadyBound");


                    throw bindingException;
                }

                flags = flags & ~ParameterBindingFlags.DelayBindScriptBlock;
                result = BindParameter(_currentParameterSetFlag, argument, matchingParameter, flags);
            }

            return result;
        }
Esempio n. 53
0
        /// <summary>
        /// Binds the specified parameters to the native command
        /// </summary>
        /// <param name="parameters">
        /// The parameters to bind.
        /// </param>
        /// <param name="outputRedirected">
        /// true if minishell output is redirected.
        /// </param>
        /// <param name="hostName">
        /// name of the calling host.
        /// </param>
        /// <remarks>
        /// For any parameters that do not have a name, they are added to the command
        /// line arguments for the command
        /// </remarks>
        internal Collection <CommandParameterInternal> BindParameters(Collection <CommandParameterInternal> parameters, bool outputRedirected, string hostName)
        {
            MinishellParameters seen = 0;
            string inputFormat       = null;
            string outputFormat      = null;

            for (int i = 0; i < parameters.Count; i++)
            {
                var parameter = parameters[i];

                if (parameter.ParameterNameSpecified)
                {
                    var parameterName = parameter.ParameterName;

                    if (CommandParameter.StartsWith(parameterName, StringComparison.OrdinalIgnoreCase))
                    {
                        HandleSeenParameter(ref seen, MinishellParameters.Command, CommandParameter);

                        // Value must be specified for -Command parameter.
                        if (i + 1 >= parameters.Count)
                        {
                            throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, CommandParameter,
                                                               typeof(ScriptBlock), null,
                                                               NativeCP.NoValueForCommandParameter,
                                                               "NoValueForCommandParameter");
                        }

                        i += 1;

                        // Value of -Command parameter must be scriptblock
                        var scriptBlockArgument = parameters[i];
                        var argumentValue       = PSObject.Base(scriptBlockArgument.ArgumentValue);
                        if (!scriptBlockArgument.ArgumentSpecified || !(argumentValue is ScriptBlock))
                        {
                            throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, CommandParameter,
                                                               typeof(ScriptBlock), argumentValue.GetType(),
                                                               NativeCP.IncorrectValueForCommandParameter,
                                                               "IncorrectValueForCommandParameter");
                        }

                        // Replace the parameters with -EncodedCommand <base64 encoded scriptblock>
                        parameters[i - 1] = CommandParameterInternal.CreateParameter(EncodedCommandParameter, "-" + EncodedCommandParameter, parameter.ParameterAst);
                        string encodedScript = StringToBase64Converter.StringToBase64String(argumentValue.ToString());
                        parameters[i] = CommandParameterInternal.CreateArgument(encodedScript, scriptBlockArgument.ArgumentAst);
                    }
                    else if (InputFormatParameter.StartsWith(parameterName, StringComparison.OrdinalIgnoreCase))
                    {
                        HandleSeenParameter(ref seen, MinishellParameters.InputFormat, InputFormatParameter);

                        // Value for -Inputformat must be specified
                        if (i + 1 >= parameters.Count)
                        {
                            throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, InputFormatParameter,
                                                               typeof(string), null,
                                                               NativeCP.NoValueForInputFormatParameter,
                                                               "NoValueForInputFormatParameter");
                        }

                        // Update the argument (partial arguments are allowed)
                        i += 1;
                        var inputFormatArg = parameters[i];
                        inputFormat       = ProcessFormatParameterValue(InputFormatParameter, inputFormatArg.ArgumentValue);
                        parameters[i - 1] = CommandParameterInternal.CreateParameter(InputFormatParameter, "-" + InputFormatParameter, parameter.ParameterAst);
                        parameters[i]     = CommandParameterInternal.CreateArgument(inputFormat, inputFormatArg.ArgumentAst);
                    }
                    else if (OutputFormatParameter.StartsWith(parameterName, StringComparison.OrdinalIgnoreCase))
                    {
                        HandleSeenParameter(ref seen, MinishellParameters.OutputFormat, OutputFormatParameter);

                        // Value for -Inputformat must be specified
                        if (i + 1 >= parameters.Count)
                        {
                            throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, OutputFormatParameter,
                                                               typeof(string), null,
                                                               NativeCP.NoValueForOutputFormatParameter,
                                                               "NoValueForInputFormatParameter");
                        }

                        // Update the argument (partial arguments are allowed)
                        i += 1;
                        var outputFormatArg = parameters[i];
                        outputFormat      = ProcessFormatParameterValue(OutputFormatParameter, outputFormatArg.ArgumentValue);
                        parameters[i - 1] = CommandParameterInternal.CreateParameter(OutputFormatParameter, "-" + OutputFormatParameter, parameter.ParameterAst);
                        parameters[i]     = CommandParameterInternal.CreateArgument(outputFormat, outputFormatArg.ArgumentAst);
                    }
                    else if (ArgsParameter.StartsWith(parameterName, StringComparison.OrdinalIgnoreCase))
                    {
                        HandleSeenParameter(ref seen, MinishellParameters.Arguments, ArgsParameter);

                        // Value for -Args parameter must be specified
                        if (i + 1 >= parameters.Count)
                        {
                            throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, ArgsParameter,
                                                               typeof(string), null, NativeCP.NoValuesSpecifiedForArgs,
                                                               "NoValuesSpecifiedForArgs");
                        }

                        // Get the encoded value for -args parameter
                        i += 1;
                        var argsArg     = parameters[i];
                        var encodedArgs = ConvertArgsValueToEncodedString(argsArg.ArgumentValue);
                        parameters[i - 1] = CommandParameterInternal.CreateParameter(EncodedArgsParameter, "-" + EncodedArgsParameter, parameter.ParameterAst);
                        // NOTE: do not pass the ArgumentAst; it will fail validation in BindParameters if there
                        // are multiple arguments (array) but encodedArgs is an encoded string.
                        parameters[i] = CommandParameterInternal.CreateArgument(encodedArgs);
                    }
                }
                else
                {
                    // -Command is positional parameter. Bind first scriptblock to it, others are errors.
                    var scriptBlockArgument = parameters[i];
                    var argumentValue       = PSObject.Base(scriptBlockArgument.ArgumentValue);
                    if (argumentValue is ScriptBlock)
                    {
                        HandleSeenParameter(ref seen, MinishellParameters.Command, CommandParameter);

                        // Replace the argument with -EncodedCommand <base64 encoded scriptblock>
                        string encodedScript = StringToBase64Converter.StringToBase64String(argumentValue.ToString());
                        parameters[i] = CommandParameterInternal.CreateParameterWithArgument(
                            parameter.ArgumentAst, EncodedCommandParameter, "-" + EncodedCommandParameter,
                            parameter.ArgumentAst, encodedScript,
                            spaceAfterParameter: true);
                    }
                }
            }

            // Add InputFormat and OutputFormat parameter if not specified
            if (inputFormat == null)
            {
                // For minishell default input format is xml
                parameters.Add(CommandParameterInternal.CreateParameter(InputFormatParameter, "-" + InputFormatParameter));
                parameters.Add(CommandParameterInternal.CreateArgument(XmlFormatValue));
                inputFormat = XmlFormatValue;
            }

            if (outputFormat == null)
            {
                // If output is redirected, output format should be xml
                outputFormat = outputRedirected ? XmlFormatValue : TextFormatValue;
                parameters.Add(CommandParameterInternal.CreateParameter(OutputFormatParameter, "-" + OutputFormatParameter));
                parameters.Add(CommandParameterInternal.CreateArgument(outputFormat));
            }

            // Set the output and input format class variable
            InputFormat = XmlFormatValue.StartsWith(inputFormat, StringComparison.OrdinalIgnoreCase)
                ? NativeCommandIOFormat.Xml
                : NativeCommandIOFormat.Text;
            OutputFormat = XmlFormatValue.StartsWith(outputFormat, StringComparison.OrdinalIgnoreCase)
                ? NativeCommandIOFormat.Xml
                : NativeCommandIOFormat.Text;

            // Note if a minishell is invoked from a non-console host, we need to
            // pass -nonInteractive flag. Our console host's name is "ConsoleHost".
            // Correct check would be see if current host has access to console and
            // pass noninteractive flag if doesn't.
            if (string.IsNullOrEmpty(hostName) || !hostName.Equals("ConsoleHost", StringComparison.OrdinalIgnoreCase))
            {
                NonInteractive = true;
                parameters.Insert(0, CommandParameterInternal.CreateParameter(NonInteractiveParameter, "-" + NonInteractiveParameter));
            }

            ((NativeCommandParameterBinder)DefaultParameterBinder).BindParameters(parameters);

            Diagnostics.Assert(s_emptyReturnCollection.Count == 0, "This list shouldn't be used for anything as it's shared.");

            return(s_emptyReturnCollection);
        } // BindParameters
 /// <summary>
 /// Passes the binding directly through to the parameter binder.
 /// It does no verification against metadata.
 /// </summary>
 /// 
 /// <param name="argument">
 /// The name and value of the variable to bind.
 /// </param>
 /// 
 /// <param name="flags">
 /// Ignored.
 /// </param>
 /// 
 /// <returns>
 /// True if the parameter was successfully bound. Any error condition
 /// produces an exception.
 /// </returns>
 /// 
 internal override bool BindParameter(CommandParameterInternal argument, ParameterBindingFlags flags)
 {
     // Just pass the binding straight through.  No metadata to verify the parameter against.
     DefaultParameterBinder.BindParameter(argument.ParameterName, argument.ArgumentValue, parameterMetadata: null);
     return true;
 }
Esempio n. 55
0
 /// <summary>
 /// Adds an unbound parameter.
 /// </summary>
 /// <param name="parameter">
 /// The parameter to add to the unbound arguments list
 /// </param>
 internal void AddParameter(CommandParameterInternal parameter)
 {
     Diagnostics.Assert(parameter != null, "Caller to verify parameter argument");
     arguments.Add(parameter);
 } // AddParameter
Esempio n. 56
0
 internal void AddParameter(CommandParameterInternal parameter)
 {
     this.arguments.Add(parameter);
 }
Esempio n. 57
0
        private static CommandProcessorBase AddCommand(PipelineProcessor pipe, CommandParameterInternal[] commandElements, CommandBaseAst commandBaseAst, CommandRedirection[] redirections, System.Management.Automation.ExecutionContext context)
        {
            object               parameterText;
            IScriptExtent        parameterExtent;
            CommandProcessorBase base2;
            InternalCommand      command;
            string               str3;
            HelpCategory         category;
            CommandAst           ast          = commandBaseAst as CommandAst;
            TokenKind            kind         = (ast != null) ? ast.InvocationOperator : TokenKind.Unknown;
            bool dotSource                    = kind == TokenKind.Dot;
            SessionStateInternal sessionState = null;
            int          index                = 0;
            PSModuleInfo info                 = PSObject.Base(commandElements[0].ArgumentValue) as PSModuleInfo;

            if (info != null)
            {
                if ((info.ModuleType == ModuleType.Binary) && (info.SessionState == null))
                {
                    throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "CantInvokeInBinaryModule", ParserStrings.CantInvokeInBinaryModule, new object[] { info.Name });
                }
                if (info.SessionState == null)
                {
                    throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "CantInvokeInNonImportedModule", ParserStrings.CantInvokeInNonImportedModule, new object[] { info.Name });
                }
                sessionState = info.SessionState.Internal;
                index++;
            }
            CommandParameterInternal internal3 = commandElements[index];

            if (internal3.ParameterNameSpecified)
            {
                parameterText   = internal3.ParameterText;
                parameterExtent = internal3.ParameterExtent;
                if (!internal3.ArgumentSpecified)
                {
                }
            }
            else
            {
                parameterText   = PSObject.Base(internal3.ArgumentValue);
                parameterExtent = internal3.ArgumentExtent;
            }
            string      str         = dotSource ? "." : ((kind == TokenKind.Ampersand) ? "&" : null);
            ScriptBlock scriptblock = parameterText as ScriptBlock;

            if (scriptblock != null)
            {
                base2 = CommandDiscovery.CreateCommandProcessorForScript(scriptblock, context, !dotSource, sessionState);
            }
            else
            {
                CommandInfo commandInfo = parameterText as CommandInfo;
                if (commandInfo != null)
                {
                    base2 = context.CommandDiscovery.LookupCommandProcessor(commandInfo, context.EngineSessionState.CurrentScope.ScopeOrigin, new bool?(!dotSource), sessionState);
                }
                else
                {
                    string str2 = (parameterText as string) ?? PSObject.ToStringParser(context, parameterText);
                    str = str ?? str2;
                    if (string.IsNullOrEmpty(str2))
                    {
                        throw InterpreterError.NewInterpreterException(parameterText, typeof(RuntimeException), parameterExtent, "BadExpression", ParserStrings.BadExpression, new object[] { dotSource ? "." : "&" });
                    }
                    try
                    {
                        if (sessionState != null)
                        {
                            SessionStateInternal engineSessionState = context.EngineSessionState;
                            try
                            {
                                context.EngineSessionState = sessionState;
                                base2 = context.CreateCommand(str2, dotSource);
                                goto Label_025D;
                            }
                            finally
                            {
                                context.EngineSessionState = engineSessionState;
                            }
                        }
                        base2 = context.CreateCommand(str2, dotSource);
                    }

                    catch (RuntimeException exception)
                    {
                        if (exception.ErrorRecord.InvocationInfo == null)
                        {
                            InvocationInfo invocationInfo = new InvocationInfo(null, parameterExtent, context)
                            {
                                InvocationName = str
                            };
                            exception.ErrorRecord.SetInvocationInfo(invocationInfo);
                        }
                        throw;
                    }
                }
            }
Label_025D:
            command             = base2.Command;
            base2.UseLocalScope = !dotSource && ((command is ScriptCommand) || (command is PSScriptCmdlet));
            bool flag2 = base2 is NativeCommandProcessor;

            for (int i = index + 1; i < commandElements.Length; i++)
            {
                CommandParameterInternal parameter = commandElements[i];
                if ((!parameter.ParameterNameSpecified || !parameter.ParameterName.Equals("-", StringComparison.OrdinalIgnoreCase)) || flag2)
                {
                    if (parameter.ArgumentSplatted)
                    {
                        foreach (CommandParameterInternal internal6 in Splat(parameter.ArgumentValue, parameter.ArgumentExtent))
                        {
                            base2.AddParameter(internal6);
                        }
                    }
                    else
                    {
                        base2.AddParameter(parameter);
                    }
                }
            }
            if (base2.IsHelpRequested(out str3, out category))
            {
                base2 = CommandProcessorBase.CreateGetHelpCommandProcessor(context, str3, category);
            }
            base2.Command.InvocationExtent            = commandBaseAst.Extent;
            base2.Command.MyInvocation.ScriptPosition = commandBaseAst.Extent;
            base2.Command.MyInvocation.InvocationName = str;
            pipe.Add(base2);
            bool flag3 = false;
            bool flag4 = false;
            bool flag5 = false;
            bool flag6 = false;

            if (redirections != null)
            {
                foreach (CommandRedirection redirection in redirections)
                {
                    redirection.Bind(pipe, base2, context);
                    switch (redirection.FromStream)
                    {
                    case RedirectionStream.All:
                        flag3 = true;
                        flag4 = true;
                        flag5 = true;
                        flag6 = true;
                        break;

                    case RedirectionStream.Error:
                        flag3 = true;
                        break;

                    case RedirectionStream.Warning:
                        flag4 = true;
                        break;

                    case RedirectionStream.Verbose:
                        flag5 = true;
                        break;

                    case RedirectionStream.Debug:
                        flag6 = true;
                        break;
                    }
                }
            }
            if (!flag3)
            {
                if (context.ShellFunctionErrorOutputPipe != null)
                {
                    base2.CommandRuntime.ErrorOutputPipe = context.ShellFunctionErrorOutputPipe;
                }
                else
                {
                    base2.CommandRuntime.ErrorOutputPipe.ExternalWriter = context.ExternalErrorOutput;
                }
            }
            if (!flag4 && (context.ExpressionWarningOutputPipe != null))
            {
                base2.CommandRuntime.WarningOutputPipe = context.ExpressionWarningOutputPipe;
                flag4 = true;
            }
            if (!flag5 && (context.ExpressionVerboseOutputPipe != null))
            {
                base2.CommandRuntime.VerboseOutputPipe = context.ExpressionVerboseOutputPipe;
                flag5 = true;
            }
            if (!flag6 && (context.ExpressionDebugOutputPipe != null))
            {
                base2.CommandRuntime.DebugOutputPipe = context.ExpressionDebugOutputPipe;
                flag6 = true;
            }
            if ((context.CurrentCommandProcessor != null) && (context.CurrentCommandProcessor.CommandRuntime != null))
            {
                if (!flag4 && (context.CurrentCommandProcessor.CommandRuntime.WarningOutputPipe != null))
                {
                    base2.CommandRuntime.WarningOutputPipe = context.CurrentCommandProcessor.CommandRuntime.WarningOutputPipe;
                }
                if (!flag5 && (context.CurrentCommandProcessor.CommandRuntime.VerboseOutputPipe != null))
                {
                    base2.CommandRuntime.VerboseOutputPipe = context.CurrentCommandProcessor.CommandRuntime.VerboseOutputPipe;
                }
                if (!flag6 && (context.CurrentCommandProcessor.CommandRuntime.DebugOutputPipe != null))
                {
                    base2.CommandRuntime.DebugOutputPipe = context.CurrentCommandProcessor.CommandRuntime.DebugOutputPipe;
                }
            }
            return(base2);
        }
Esempio n. 58
0
        /// <summary>
        /// Bind the argument to the specified parameter
        /// </summary>
        /// 
        /// <param name="parameterSets">
        /// The parameter set used to bind the arguments.
        /// </param>
        /// 
        /// <param name="argument">
        /// The argument to be bound.
        /// </param>
        /// 
        /// <param name="parameter">
        /// The metadata for the parameter to bind the argument to.
        /// </param>
        /// 
        /// <param name="flags">
        /// Flags for type coercion and validation of the arguments.
        /// </param>
        /// 
        /// <returns>
        /// True if the parameter was successfully bound. False if <paramref name="flags"/> 
        /// specifies no type coercion and the type does not match the parameter type.
        /// </returns>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="parameter"/> or <paramref name="argument"/> is null.
        /// </exception>
        /// 
        /// <exception cref="ParameterBindingException">
        /// If argument transformation fails.
        /// or
        /// The argument could not be coerced to the appropriate type for the parameter.
        /// or
        /// The parameter argument transformation, prerequisite, or validation failed.
        /// or
        /// If the binding to the parameter fails.
        /// </exception>
        /// 
        internal virtual bool BindParameter(
            uint parameterSets,
            CommandParameterInternal argument,
            MergedCompiledCommandParameter parameter,
            ParameterBindingFlags flags)
        {
            bool result = false;

            switch (parameter.BinderAssociation)
            {
                case ParameterBinderAssociation.DeclaredFormalParameters:
                    result =
                        this.DefaultParameterBinder.BindParameter(
                            argument,
                            parameter.Parameter,
                            flags);
                    break;

                default:
                    Diagnostics.Assert(
                        false,
                        "Only the formal parameters are available for this type of command");
                    break;
            }

            if (result && ((flags & ParameterBindingFlags.IsDefaultValue) == 0))
            {
                UnboundParameters.Remove(parameter);
                BoundParameters.Add(parameter.Parameter.Name, parameter);
            }
            return result;
        }
Esempio n. 59
0
 private object EncodeCollection(CommandParameterInternal argument, string parameterName, ParameterCollectionTypeInformation collectionTypeInformation, Type toType, object currentValue, bool coerceElementTypeIfNeeded, out bool coercionRequired)
 {
     object obj2 = null;
     coercionRequired = false;
     bindingTracer.WriteLine("Binding collection parameter {0}: argument type [{1}], parameter type [{2}], collection type {3}, element type [{4}], {5}", new object[] { parameterName, (currentValue == null) ? "null" : currentValue.GetType().Name, toType, collectionTypeInformation.ParameterCollectionType, collectionTypeInformation.ElementType, coerceElementTypeIfNeeded ? "coerceElementType" : "no coerceElementType" });
     if (currentValue != null)
     {
         int length = 1;
         Type elementType = collectionTypeInformation.ElementType;
         IList iList = GetIList(currentValue);
         if (iList != null)
         {
             length = iList.Count;
             tracer.WriteLine("current value is an IList with {0} elements", new object[] { length });
             bindingTracer.WriteLine("Arg is IList with {0} elements", new object[] { length });
         }
         object obj3 = null;
         IList list2 = null;
         MethodInfo info = null;
         bool flag = toType == typeof(Array);
         if ((collectionTypeInformation.ParameterCollectionType == ParameterCollectionType.Array) || flag)
         {
             if (flag)
             {
                 elementType = typeof(object);
             }
             bindingTracer.WriteLine("Creating array with element type [{0}] and {1} elements", new object[] { elementType, length });
             obj3 = list2 = Array.CreateInstance(elementType, length);
         }
         else
         {
             if ((collectionTypeInformation.ParameterCollectionType != ParameterCollectionType.IList) && (collectionTypeInformation.ParameterCollectionType != ParameterCollectionType.ICollectionGeneric))
             {
                 return obj2;
             }
             bindingTracer.WriteLine("Creating collection [{0}]", new object[] { toType });
             bool flag2 = false;
             Exception innerException = null;
             try
             {
                 obj3 = Activator.CreateInstance(toType, BindingFlags.Default, null, new object[0], CultureInfo.InvariantCulture);
                 if (collectionTypeInformation.ParameterCollectionType == ParameterCollectionType.IList)
                 {
                     list2 = (IList) obj3;
                 }
                 else
                 {
                     Type type2 = collectionTypeInformation.ElementType;
                     BindingFlags bindingAttr = BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance;
                     Exception exception2 = null;
                     try
                     {
                         info = toType.GetMethod("Add", bindingAttr, null, new Type[] { type2 }, null);
                     }
                     catch (AmbiguousMatchException exception3)
                     {
                         bindingTracer.WriteLine("Ambiguous match to Add(T) for type " + toType.FullName + ": " + exception3.Message, new object[0]);
                         exception2 = exception3;
                     }
                     catch (ArgumentException exception4)
                     {
                         bindingTracer.WriteLine("ArgumentException matching Add(T) for type " + toType.FullName + ": " + exception4.Message, new object[0]);
                         exception2 = exception4;
                     }
                     if (null == info)
                     {
                         ParameterBindingException exception5 = new ParameterBindingException(exception2, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, (currentValue == null) ? null : currentValue.GetType(), "ParameterBinderStrings", "CannotExtractAddMethod", new object[] { (exception2 == null) ? "" : exception2.Message });
                         throw exception5;
                     }
                 }
             }
             catch (ArgumentException exception6)
             {
                 flag2 = true;
                 innerException = exception6;
             }
             catch (NotSupportedException exception7)
             {
                 flag2 = true;
                 innerException = exception7;
             }
             catch (TargetInvocationException exception8)
             {
                 flag2 = true;
                 innerException = exception8;
             }
             catch (MethodAccessException exception9)
             {
                 flag2 = true;
                 innerException = exception9;
             }
             catch (MemberAccessException exception10)
             {
                 flag2 = true;
                 innerException = exception10;
             }
             catch (InvalidComObjectException exception11)
             {
                 flag2 = true;
                 innerException = exception11;
             }
             catch (COMException exception12)
             {
                 flag2 = true;
                 innerException = exception12;
             }
             catch (TypeLoadException exception13)
             {
                 flag2 = true;
                 innerException = exception13;
             }
             if (flag2)
             {
                 ParameterBindingException exception14 = new ParameterBindingException(innerException, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, currentValue.GetType(), "ParameterBinderStrings", "CannotConvertArgument", new object[] { (obj2 == null) ? "null" : obj2, (innerException == null) ? "" : innerException.Message });
                 throw exception14;
             }
         }
         if (iList != null)
         {
             int num2 = 0;
             bindingTracer.WriteLine("Argument type {0} is IList", new object[] { currentValue.GetType() });
             foreach (object obj4 in iList)
             {
                 object obj5 = PSObject.Base(obj4);
                 if (coerceElementTypeIfNeeded)
                 {
                     bindingTracer.WriteLine("COERCE collection element from type {0} to type {1}", new object[] { (obj4 == null) ? "null" : obj4.GetType().Name, elementType });
                     obj5 = this.CoerceTypeAsNeeded(argument, parameterName, elementType, null, obj4);
                 }
                 else if ((null != elementType) && (obj5 != null))
                 {
                     Type type = obj5.GetType();
                     Type c = elementType;
                     if ((type != c) && !type.IsSubclassOf(c))
                     {
                         bindingTracer.WriteLine("COERCION REQUIRED: Did not attempt to coerce collection element from type {0} to type {1}", new object[] { (obj4 == null) ? "null" : obj4.GetType().Name, elementType });
                         coercionRequired = true;
                         break;
                     }
                 }
                 try
                 {
                     if ((collectionTypeInformation.ParameterCollectionType == ParameterCollectionType.Array) || flag)
                     {
                         bindingTracer.WriteLine("Adding element of type {0} to array position {1}", new object[] { (obj5 == null) ? "null" : obj5.GetType().Name, num2 });
                         list2[num2++] = obj5;
                     }
                     else if (collectionTypeInformation.ParameterCollectionType == ParameterCollectionType.IList)
                     {
                         bindingTracer.WriteLine("Adding element of type {0} via IList.Add", new object[] { (obj5 == null) ? "null" : obj5.GetType().Name });
                         list2.Add(obj5);
                     }
                     else
                     {
                         bindingTracer.WriteLine("Adding element of type {0} via ICollection<T>::Add()", new object[] { (obj5 == null) ? "null" : obj5.GetType().Name });
                         info.Invoke(obj3, new object[] { obj5 });
                     }
                 }
                 catch (Exception exception15)
                 {
                     CommandProcessorBase.CheckForSevereException(exception15);
                     if ((exception15 is TargetInvocationException) && (exception15.InnerException != null))
                     {
                         exception15 = exception15.InnerException;
                     }
                     ParameterBindingException exception16 = new ParameterBindingException(exception15, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, (obj5 == null) ? null : obj5.GetType(), "ParameterBinderStrings", "CannotConvertArgument", new object[] { (obj5 == null) ? "null" : obj5, exception15.Message });
                     throw exception16;
                 }
             }
         }
         else
         {
             bindingTracer.WriteLine("Argument type {0} is not IList, treating this as scalar", new object[] { (currentValue == null) ? "null" : currentValue.GetType().Name });
             if (elementType != null)
             {
                 if (coerceElementTypeIfNeeded)
                 {
                     bindingTracer.WriteLine("Coercing scalar arg value to type {0}", new object[] { elementType });
                     currentValue = this.CoerceTypeAsNeeded(argument, parameterName, elementType, null, currentValue);
                 }
                 else
                 {
                     Type type5 = currentValue.GetType();
                     Type type6 = elementType;
                     if ((type5 != type6) && !type5.IsSubclassOf(type6))
                     {
                         bindingTracer.WriteLine("COERCION REQUIRED: Did not coerce scalar arg value to type {1}", new object[] { elementType });
                         coercionRequired = true;
                         return obj2;
                     }
                 }
             }
             try
             {
                 if ((collectionTypeInformation.ParameterCollectionType == ParameterCollectionType.Array) || flag)
                 {
                     bindingTracer.WriteLine("Adding scalar element of type {0} to array position {1}", new object[] { (currentValue == null) ? "null" : currentValue.GetType().Name, 0 });
                     list2[0] = currentValue;
                 }
                 else if (collectionTypeInformation.ParameterCollectionType == ParameterCollectionType.IList)
                 {
                     bindingTracer.WriteLine("Adding scalar element of type {0} via IList.Add", new object[] { (currentValue == null) ? "null" : currentValue.GetType().Name });
                     list2.Add(currentValue);
                 }
                 else
                 {
                     bindingTracer.WriteLine("Adding scalar element of type {0} via ICollection<T>::Add()", new object[] { (currentValue == null) ? "null" : currentValue.GetType().Name });
                     info.Invoke(obj3, new object[] { currentValue });
                 }
             }
             catch (Exception exception17)
             {
                 CommandProcessorBase.CheckForSevereException(exception17);
                 if ((exception17 is TargetInvocationException) && (exception17.InnerException != null))
                 {
                     exception17 = exception17.InnerException;
                 }
                 ParameterBindingException exception18 = new ParameterBindingException(exception17, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, (currentValue == null) ? null : currentValue.GetType(), "ParameterBinderStrings", "CannotConvertArgument", new object[] { (currentValue == null) ? "null" : currentValue, exception17.Message });
                 throw exception18;
             }
         }
         if (!coercionRequired)
         {
             obj2 = obj3;
         }
     }
     return obj2;
 }
Esempio n. 60
0
 internal virtual bool BindParameter(CommandParameterInternal parameter, CompiledCommandParameter parameterMetadata, ParameterBindingFlags flags)
 {
     bool flag = false;
     bool flag2 = (flags & ParameterBindingFlags.ShouldCoerceType) != ParameterBindingFlags.None;
     if (parameter == null)
     {
         throw PSTraceSource.NewArgumentNullException("parameter");
     }
     if (parameterMetadata == null)
     {
         throw PSTraceSource.NewArgumentNullException("parameterMetadata");
     }
     using (bindingTracer.TraceScope("BIND arg [{0}] to parameter [{1}]", new object[] { parameter.ArgumentValue, parameterMetadata.Name }))
     {
         parameter.ParameterName = parameterMetadata.Name;
         object argumentValue = parameter.ArgumentValue;
         ScriptParameterBinder binder = this as ScriptParameterBinder;
         bool bindingScriptCmdlet = false;
         if (binder != null)
         {
             bindingScriptCmdlet = binder.Script.UsesCmdletBinding;
         }
         foreach (ArgumentTransformationAttribute attribute in parameterMetadata.ArgumentTransformationAttributes)
         {
             using (bindingTracer.TraceScope("Executing DATA GENERATION metadata: [{0}]", new object[] { attribute.GetType() }))
             {
                 try
                 {
                     ArgumentTypeConverterAttribute attribute2 = attribute as ArgumentTypeConverterAttribute;
                     if (attribute2 != null)
                     {
                         if (flag2)
                         {
                             argumentValue = attribute2.Transform(this.engine, argumentValue, true, bindingScriptCmdlet);
                         }
                     }
                     else
                     {
                         argumentValue = attribute.Transform(this.engine, argumentValue);
                     }
                     bindingTracer.WriteLine("result returned from DATA GENERATION: {0}", new object[] { argumentValue });
                 }
                 catch (Exception exception)
                 {
                     CommandProcessorBase.CheckForSevereException(exception);
                     bindingTracer.WriteLine("ERROR: DATA GENERATION: {0}", new object[] { exception.Message });
                     ParameterBindingException exception2 = new ParameterBindingArgumentTransformationException(exception, ErrorCategory.InvalidData, this.InvocationInfo, this.GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, (argumentValue == null) ? null : argumentValue.GetType(), "ParameterBinderStrings", "ParameterArgumentTransformationError", new object[] { exception.Message });
                     throw exception2;
                 }
             }
         }
         if (flag2)
         {
             argumentValue = this.CoerceTypeAsNeeded(parameter, parameterMetadata.Name, parameterMetadata.Type, parameterMetadata.CollectionTypeInformation, argumentValue);
         }
         else if (!this.ShouldContinueUncoercedBind(parameter, parameterMetadata, flags, ref argumentValue))
         {
             goto Label_040E;
         }
         if ((parameterMetadata.PSTypeName != null) && (argumentValue != null))
         {
             IEnumerable enumerable = LanguagePrimitives.GetEnumerable(argumentValue);
             if (enumerable != null)
             {
                 foreach (object obj3 in enumerable)
                 {
                     this.ValidatePSTypeName(parameter, parameterMetadata, !flag2, obj3);
                 }
             }
             else
             {
                 this.ValidatePSTypeName(parameter, parameterMetadata, !flag2, argumentValue);
             }
         }
         if ((flags & ParameterBindingFlags.IsDefaultValue) == ParameterBindingFlags.None)
         {
             foreach (ValidateArgumentsAttribute attribute3 in parameterMetadata.ValidationAttributes)
             {
                 using (bindingTracer.TraceScope("Executing VALIDATION metadata: [{0}]", new object[] { attribute3.GetType() }))
                 {
                     try
                     {
                         attribute3.InternalValidate(argumentValue, this.engine);
                     }
                     catch (Exception exception3)
                     {
                         CommandProcessorBase.CheckForSevereException(exception3);
                         bindingTracer.WriteLine("ERROR: VALIDATION FAILED: {0}", new object[] { exception3.Message });
                         ParameterBindingValidationException exception4 = new ParameterBindingValidationException(exception3, ErrorCategory.InvalidData, this.InvocationInfo, this.GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, (argumentValue == null) ? null : argumentValue.GetType(), "ParameterBinderStrings", "ParameterArgumentValidationError", new object[] { exception3.Message });
                         throw exception4;
                     }
                     tracer.WriteLine("Validation attribute on {0} returned {1}.", new object[] { parameterMetadata.Name, flag });
                 }
             }
             if (IsParameterMandatory(parameterMetadata))
             {
                 this.ValidateNullOrEmptyArgument(parameter, parameterMetadata, parameterMetadata.Type, argumentValue, true);
             }
         }
         Exception innerException = null;
         try
         {
             this.BindParameter(parameter.ParameterName, argumentValue);
             flag = true;
         }
         catch (SetValueException exception6)
         {
             innerException = exception6;
         }
         if (innerException != null)
         {
             Type typeSpecified = (argumentValue == null) ? null : argumentValue.GetType();
             ParameterBindingException exception7 = new ParameterBindingException(innerException, ErrorCategory.WriteError, this.InvocationInfo, this.GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, typeSpecified, "ParameterBinderStrings", "ParameterBindingFailed", new object[] { innerException.Message });
             throw exception7;
         }
     Label_040E:;
         bindingTracer.WriteLine("BIND arg [{0}] to param [{1}] {2}", new object[] { argumentValue, parameter.ParameterName, flag ? "SUCCESSFUL" : "SKIPPED" });
         if (flag)
         {
             if (this.RecordBoundParameters)
             {
                 this.CommandLineParameters.Add(parameter.ParameterName, argumentValue);
             }
             MshCommandRuntime commandRuntime = this.Command.commandRuntime as MshCommandRuntime;
             if ((commandRuntime != null) && commandRuntime.LogPipelineExecutionDetail)
             {
                 IEnumerable source = LanguagePrimitives.GetEnumerable(argumentValue);
                 if (source != null)
                 {
                     string parameterValue = string.Join(", ", source.Cast<object>().ToArray<object>());
                     commandRuntime.PipelineProcessor.LogExecutionParameterBinding(this.InvocationInfo, parameter.ParameterName, parameterValue);
                 }
                 else
                 {
                     commandRuntime.PipelineProcessor.LogExecutionParameterBinding(this.InvocationInfo, parameter.ParameterName, (argumentValue == null) ? "" : argumentValue.ToString());
                 }
             }
         }
         return flag;
     }
 }