Пример #1
0
        /// <summary>
        /// Writes an ErrorRecord to the commands error pipe because the specified
        /// input object was not bound to the command.
        /// </summary>
        /// <param name="inputObject">
        /// The pipeline input object that was not bound.
        /// </param>
        /// <param name="resourceString">
        /// The error message.
        /// </param>
        /// <param name="errorId">
        /// The resource ID of the error message is also used as error ID
        /// of the ErrorRecord.
        /// </param>
        /// <param name="args">
        /// Additional arguments to be formatted into the error message that represented in <paramref name="resourceString"/>.
        /// </param>
        private void WriteInputObjectError(
            object inputObject,
            string resourceString,
            string errorId,
            params object[] args)
        {
            Type inputObjectType = inputObject?.GetType();

            ParameterBindingException bindingException = new ParameterBindingException(
                ErrorCategory.InvalidArgument,
                this.Command.MyInvocation,
                null,
                null,
                null,
                inputObjectType,
                resourceString,
                errorId,
                args);

            ErrorRecord errorRecord =
                new ErrorRecord(
                    bindingException,
                    errorId,
                    ErrorCategory.InvalidArgument,
                    inputObject);

            errorRecord.SetInvocationInfo(this.Command.MyInvocation);

            this.commandRuntime._WriteErrorSkipAllowCheck(errorRecord);
        }
Пример #2
0
        /// <summary>
        /// Constructs the parameter binder with the specified type metadata. The binder is only valid
        /// for a single instance of a bindable runtime-defined parameter collection and only for the duration of a command.
        /// </summary>
        /// 
        /// <param name="target">
        /// The target runtime-defined parameter collection that the parameter values will be bound to.
        /// </param>
        /// 
        /// <param name="command">
        /// An instance of the command so that attributes can access the context.
        /// </param>
        /// 
        /// <param name="commandLineParameters">
        /// The Command line parameter collection to update...
        /// </param>
        /// 
        internal RuntimeDefinedParameterBinder(
            RuntimeDefinedParameterDictionary target,
            InternalCommand command,
            CommandLineParameters commandLineParameters)
            : base(target, command.MyInvocation, command.Context, command)
        {
            // NTRAID#Windows Out Of Band Releases-927103-2006/01/25-JonN
            foreach (var pair in target)
            {
                string key = pair.Key;
                RuntimeDefinedParameter pp = pair.Value;
                string ppName = (null == pp) ? null : pp.Name;
                if (null == pp || key != ppName)
                {
                    ParameterBindingException bindingException =
                        new ParameterBindingException(
                            ErrorCategory.InvalidArgument,
                            command.MyInvocation,
                            null,
                            ppName,
                            null,
                            null,
                            ParameterBinderStrings.RuntimeDefinedParameterNameMismatch,
                            "RuntimeDefinedParameterNameMismatch",
                            key);

                    throw bindingException;
                }
            }
            this.CommandLineParameters = commandLineParameters;
        }
Пример #3
0
        internal override Collection <CommandParameterInternal> BindParameters(Collection <CommandParameterInternal> arguments)
        {
            Collection <CommandParameterInternal> collection = new Collection <CommandParameterInternal>();

            foreach (CommandParameterInternal internal2 in arguments)
            {
                if (!internal2.ParameterNameSpecified)
                {
                    collection.Add(internal2);
                }
                else
                {
                    MergedCompiledCommandParameter parameter = base.BindableParameters.GetMatchingParameter(internal2.ParameterName, false, true, new InvocationInfo(base.InvocationInfo.MyCommand, internal2.ParameterExtent));
                    if (parameter != null)
                    {
                        if (base.BoundParameters.ContainsKey(parameter.Parameter.Name))
                        {
                            ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, base.InvocationInfo, base.GetParameterErrorExtent(internal2), internal2.ParameterName, null, null, "ParameterBinderStrings", "ParameterAlreadyBound", new object[0]);
                            throw exception;
                        }
                        this.BindParameter(int.MaxValue, internal2, parameter, ParameterBindingFlags.ShouldCoerceType);
                    }
                    else if (internal2.ParameterName.Equals("-%", StringComparison.Ordinal))
                    {
                        base.DefaultParameterBinder.CommandLineParameters.SetImplicitUsingParameters(internal2.ArgumentValue);
                    }
                    else
                    {
                        collection.Add(internal2);
                    }
                }
            }
            return(collection);
        }
        /// <summary>
        /// Constructs the parameter binder with the specified type metadata. The binder is only valid
        /// for a single instance of a bindable runtime-defined parameter collection and only for the duration of a command.
        /// </summary>
        ///
        /// <param name="target">
        /// The target runtime-defined parameter collection that the parameter values will be bound to.
        /// </param>
        ///
        /// <param name="command">
        /// An instance of the command so that attributes can access the context.
        /// </param>
        ///
        /// <param name="commandLineParameters">
        /// The Command line parameter collection to update...
        /// </param>
        ///
        internal RuntimeDefinedParameterBinder(
            RuntimeDefinedParameterDictionary target,
            InternalCommand command,
            CommandLineParameters commandLineParameters)
            : base(target, command.MyInvocation, command.Context, command)
        {
            // NTRAID#Windows Out Of Band Releases-927103-2006/01/25-JonN
            foreach (var pair in target)
            {
                string key = pair.Key;
                RuntimeDefinedParameter pp = pair.Value;
                string ppName = (null == pp) ? null : pp.Name;
                if (null == pp || key != ppName)
                {
                    ParameterBindingException bindingException =
                        new ParameterBindingException(
                            ErrorCategory.InvalidArgument,
                            command.MyInvocation,
                            null,
                            ppName,
                            null,
                            null,
                            ParameterBinderStrings.RuntimeDefinedParameterNameMismatch,
                            "RuntimeDefinedParameterNameMismatch",
                            key);

                    throw bindingException;
                }
            }
            this.CommandLineParameters = commandLineParameters;
        }
        /// <summary>
        /// Binds the specified parameters to the shell function
        /// </summary>
        ///
        /// <param name="arguments">
        /// The arguments to bind.
        /// </param>
        ///
        internal override Collection <CommandParameterInternal> BindParameters(Collection <CommandParameterInternal> arguments)
        {
            Collection <CommandParameterInternal> result = new Collection <CommandParameterInternal>();

            foreach (CommandParameterInternal argument in arguments)
            {
                if (!argument.ParameterNameSpecified)
                {
                    result.Add(argument);
                    continue;
                }

                // We don't want to throw an exception yet because
                // the parameter might be a positional argument

                MergedCompiledCommandParameter parameter =
                    BindableParameters.GetMatchingParameter(
                        argument.ParameterName,
                        false, true,
                        new InvocationInfo(this.InvocationInfo.MyCommand, argument.ParameterExtent));

                // If the parameter is not in the specified parameter set,
                // throw a binding exception

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

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

                        throw bindingException;
                    }
                    BindParameter(uint.MaxValue, argument, parameter, ParameterBindingFlags.ShouldCoerceType);
                }
                else if (argument.ParameterName.Equals(Language.Parser.VERBATIM_PARAMETERNAME, StringComparison.Ordinal))
                {
                    // We sometimes send a magic parameter from a remote machine with the values referenced via
                    // a using expression ($using:x).  We then access these values via PSBoundParameters, so
                    // "bind" them here.
                    DefaultParameterBinder.CommandLineParameters.SetImplicitUsingParameters(argument.ArgumentValue);
                }
                else
                {
                    result.Add(argument);
                }
            }
            return(result);
        }
 internal override Collection<CommandParameterInternal> BindParameters(Collection<CommandParameterInternal> arguments)
 {
     Collection<CommandParameterInternal> collection = new Collection<CommandParameterInternal>();
     foreach (CommandParameterInternal internal2 in arguments)
     {
         if (!internal2.ParameterNameSpecified)
         {
             collection.Add(internal2);
         }
         else
         {
             MergedCompiledCommandParameter parameter = base.BindableParameters.GetMatchingParameter(internal2.ParameterName, false, true, new InvocationInfo(base.InvocationInfo.MyCommand, internal2.ParameterExtent));
             if (parameter != null)
             {
                 if (base.BoundParameters.ContainsKey(parameter.Parameter.Name))
                 {
                     ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, base.InvocationInfo, base.GetParameterErrorExtent(internal2), internal2.ParameterName, null, null, "ParameterBinderStrings", "ParameterAlreadyBound", new object[0]);
                     throw exception;
                 }
                 this.BindParameter(int.MaxValue, internal2, parameter, ParameterBindingFlags.ShouldCoerceType);
             }
             else if (internal2.ParameterName.Equals("-%", StringComparison.Ordinal))
             {
                 base.DefaultParameterBinder.CommandLineParameters.SetImplicitUsingParameters(internal2.ArgumentValue);
             }
             else
             {
                 collection.Add(internal2);
             }
         }
     }
     return collection;
 }
Пример #7
0
        internal MergedCompiledCommandParameter GetMatchingParameter(string name, bool throwOnParameterNotFound, bool tryExactMatching, InvocationInfo invocationInfo)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw PSTraceSource.NewArgumentException("name");
            }
            Collection <MergedCompiledCommandParameter> collection = new Collection <MergedCompiledCommandParameter>();

            if ((name.Length > 0) && SpecialCharacters.IsDash(name[0]))
            {
                name = name.Substring(1);
            }
            foreach (string str in this.bindableParameters.Keys)
            {
                if (nameCompareInfo.IsPrefix(str, name, CompareOptions.IgnoreCase))
                {
                    if (tryExactMatching && string.Equals(str, name, StringComparison.OrdinalIgnoreCase))
                    {
                        return(this.bindableParameters[str]);
                    }
                    collection.Add(this.bindableParameters[str]);
                }
            }
            foreach (string str2 in this.aliasedParameters.Keys)
            {
                if (nameCompareInfo.IsPrefix(str2, name, CompareOptions.IgnoreCase))
                {
                    if (tryExactMatching && string.Equals(str2, name, StringComparison.OrdinalIgnoreCase))
                    {
                        return(this.aliasedParameters[str2]);
                    }
                    if (!collection.Contains(this.aliasedParameters[str2]))
                    {
                        collection.Add(this.aliasedParameters[str2]);
                    }
                }
            }
            if (collection.Count > 1)
            {
                StringBuilder builder = new StringBuilder();
                foreach (MergedCompiledCommandParameter parameter in collection)
                {
                    builder.AppendFormat(" -{0}", parameter.Parameter.Name);
                }
                ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, invocationInfo, null, name, null, null, "ParameterBinderStrings", "AmbiguousParameter", new object[] { builder });
                throw exception;
            }
            if ((collection.Count == 0) && throwOnParameterNotFound)
            {
                ParameterBindingException exception2 = new ParameterBindingException(ErrorCategory.InvalidArgument, invocationInfo, null, name, null, null, "ParameterBinderStrings", "NamedParameterNotFound", new object[0]);
                throw exception2;
            }
            MergedCompiledCommandParameter parameter2 = null;

            if (collection.Count > 0)
            {
                parameter2 = collection[0];
            }
            return(parameter2);
        }
 internal RuntimeDefinedParameterBinder(
     RuntimeDefinedParameterDictionary target,
     InternalCommand command,
     CommandLineParameters commandLineParameters)
     : base((object)target, command.MyInvocation, command.Context, command)
 {
     using (RuntimeDefinedParameterBinder.tracer.TraceConstructor((object)this))
     {
         foreach (string key in target.Keys)
         {
             RuntimeDefinedParameter definedParameter = target[key];
             string parameterName = definedParameter == null ? (string)null : definedParameter.Name;
             if (definedParameter == null || key != parameterName)
             {
                 ParameterBindingException bindingException = new ParameterBindingException(ErrorCategory.InvalidArgument, command.MyInvocation, (Token)null, parameterName, (Type)null, (Type)null, "ParameterBinderStrings", "RuntimeDefinedParameterNameMismatch", new object[1]
                 {
                     (object)key
                 });
                 RuntimeDefinedParameterBinder.tracer.TraceException((Exception)bindingException);
                 throw bindingException;
             }
         }
         this.CommandLineParameters = commandLineParameters;
     }
 }
Пример #9
0
        private void WriteInputObjectError(object inputObject, string resourceAndErrorId, params object[] args)
        {
            Type typeSpecified = (inputObject == null) ? null : inputObject.GetType();
            ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, base.Command.MyInvocation, null, null, null, typeSpecified, "ParameterBinderStrings", resourceAndErrorId, args);
            ErrorRecord errorRecord             = new ErrorRecord(exception, resourceAndErrorId, ErrorCategory.InvalidArgument, inputObject);

            errorRecord.SetInvocationInfo(base.Command.MyInvocation);
            base.commandRuntime._WriteErrorSkipAllowCheck(errorRecord, null);
        }
Пример #10
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;
        }
        /// <summary>
        /// </summary>
        /// <param name="innerException"></param>
        /// <param name="pbex"></param>
        /// <param name="resourceString"></param>
        /// <param name="args"></param>
        internal ParameterBindingException(
            Exception innerException,
            ParameterBindingException pbex,
            string resourceString,
            params object[] args)
            : base(string.Empty, innerException)
        {
            if (pbex == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(pbex));
            }

            if (string.IsNullOrEmpty(resourceString))
            {
                throw PSTraceSource.NewArgumentException(nameof(resourceString));
            }

            _invocationInfo = pbex.CommandInvocation;
            if (_invocationInfo != null)
            {
                _commandName = _invocationInfo.MyCommand.Name;
            }

            IScriptExtent errorPosition = null;

            if (_invocationInfo != null)
            {
                errorPosition = _invocationInfo.ScriptPosition;
            }

            _line   = pbex.Line;
            _offset = pbex.Offset;

            _parameterName = pbex.ParameterName;
            _parameterType = pbex.ParameterType;
            _typeSpecified = pbex.TypeSpecified;
            _errorId       = pbex.ErrorId;

            _resourceString = resourceString;

            if (args != null)
            {
                _args = args;
            }

            base.SetErrorCategory(pbex.ErrorRecord._category);
            base.SetErrorId(_errorId);
            if (_invocationInfo != null)
            {
                base.ErrorRecord.SetInvocationInfo(new InvocationInfo(_invocationInfo.MyCommand, errorPosition));
            }
        }
Пример #12
0
 internal RuntimeDefinedParameterBinder(RuntimeDefinedParameterDictionary target, InternalCommand command, CommandLineParameters commandLineParameters) : base(target, command.MyInvocation, command.Context, command)
 {
     foreach (string str in target.Keys)
     {
         RuntimeDefinedParameter parameter = target[str];
         string parameterName = (parameter == null) ? null : parameter.Name;
         if ((parameter == null) || (str != parameterName))
         {
             ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, command.MyInvocation, null, parameterName, null, null, "ParameterBinderStrings", "RuntimeDefinedParameterNameMismatch", new object[] { str });
             throw exception;
         }
     }
     base.CommandLineParameters = commandLineParameters;
 }
 internal RuntimeDefinedParameterBinder(RuntimeDefinedParameterDictionary target, InternalCommand command, CommandLineParameters commandLineParameters) : base(target, command.MyInvocation, command.Context, command)
 {
     foreach (string str in target.Keys)
     {
         RuntimeDefinedParameter parameter = target[str];
         string parameterName = (parameter == null) ? null : parameter.Name;
         if ((parameter == null) || (str != parameterName))
         {
             ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, command.MyInvocation, null, parameterName, null, null, "ParameterBinderStrings", "RuntimeDefinedParameterNameMismatch", new object[] { str });
             throw exception;
         }
     }
     base.CommandLineParameters = commandLineParameters;
 }
        internal ParameterBindingException(Exception innerException, ParameterBindingException pbex, string resourceBaseName, string resourceId, params object[] args) : base(string.Empty, innerException)
        {
            this.parameterName = string.Empty;
            this.line          = -9223372036854775808L;
            this.offset        = -9223372036854775808L;
            this.args          = new object[0];
            if (pbex == null)
            {
                throw PSTraceSource.NewArgumentNullException("pbex");
            }
            if (string.IsNullOrEmpty(resourceBaseName))
            {
                throw PSTraceSource.NewArgumentException("resourceBaseName");
            }
            if (string.IsNullOrEmpty(resourceId))
            {
                throw PSTraceSource.NewArgumentException("resourceId");
            }
            this.invocationInfo = pbex.CommandInvocation;
            if (this.invocationInfo != null)
            {
                this.commandName = this.invocationInfo.MyCommand.Name;
            }
            IScriptExtent scriptPosition = null;

            if (this.invocationInfo != null)
            {
                scriptPosition = this.invocationInfo.ScriptPosition;
            }
            this.line             = pbex.Line;
            this.offset           = pbex.Offset;
            this.parameterName    = pbex.ParameterName;
            this.parameterType    = pbex.ParameterType;
            this.typeSpecified    = pbex.TypeSpecified;
            this.errorId          = pbex.ErrorId;
            this.resourceBaseName = resourceBaseName;
            this.resourceId       = resourceId;
            if (args != null)
            {
                this.args = args;
            }
            base.SetErrorCategory(pbex.ErrorRecord._category);
            base.SetErrorId(this.errorId);
            if (this.invocationInfo != null)
            {
                base.ErrorRecord.SetInvocationInfo(new InvocationInfo(this.invocationInfo.MyCommand, scriptPosition));
            }
        }
Пример #15
0
 internal ParameterBindingException(Exception innerException, ParameterBindingException pbex, string resourceBaseName, string resourceId, params object[] args) : base(string.Empty, innerException)
 {
     this.parameterName = string.Empty;
     this.line = -9223372036854775808L;
     this.offset = -9223372036854775808L;
     this.args = new object[0];
     if (pbex == null)
     {
         throw PSTraceSource.NewArgumentNullException("pbex");
     }
     if (string.IsNullOrEmpty(resourceBaseName))
     {
         throw PSTraceSource.NewArgumentException("resourceBaseName");
     }
     if (string.IsNullOrEmpty(resourceId))
     {
         throw PSTraceSource.NewArgumentException("resourceId");
     }
     this.invocationInfo = pbex.CommandInvocation;
     if (this.invocationInfo != null)
     {
         this.commandName = this.invocationInfo.MyCommand.Name;
     }
     IScriptExtent scriptPosition = null;
     if (this.invocationInfo != null)
     {
         scriptPosition = this.invocationInfo.ScriptPosition;
     }
     this.line = pbex.Line;
     this.offset = pbex.Offset;
     this.parameterName = pbex.ParameterName;
     this.parameterType = pbex.ParameterType;
     this.typeSpecified = pbex.TypeSpecified;
     this.errorId = pbex.ErrorId;
     this.resourceBaseName = resourceBaseName;
     this.resourceId = resourceId;
     if (args != null)
     {
         this.args = args;
     }
     base.SetErrorCategory(pbex.ErrorRecord._category);
     base.SetErrorId(this.errorId);
     if (this.invocationInfo != null)
     {
         base.ErrorRecord.SetInvocationInfo(new InvocationInfo(this.invocationInfo.MyCommand, scriptPosition));
     }
 }
Пример #16
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));
        }
Пример #17
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);
 }
Пример #18
0
        protected void ThrowElaboratedBindingException(ParameterBindingException pbex)
        {
            if (pbex == null)
            {
                throw PSTraceSource.NewArgumentNullException("pbex");
            }
            string        message = pbex.Message;
            StringBuilder builder = new StringBuilder();

            foreach (string str2 in this.BoundDefaultParameters)
            {
                builder.AppendFormat(CultureInfo.InvariantCulture, " -{0}", new object[] { str2 });
            }
            string resourceId = "DefaultBindingErrorElaborationSingle";

            if (this.BoundDefaultParameters.Count > 1)
            {
                resourceId = "DefaultBindingErrorElaborationMultiple";
            }
            ParameterBindingException exception = new ParameterBindingException(pbex.InnerException, pbex, "ParameterBinderStrings", resourceId, new object[] { message, builder });

            throw exception;
        }
Пример #19
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;
         }
     }
 }
 internal bool HandleUnboundMandatoryParameters(int validParameterSetCount, bool promptForMandatory, bool isPipelineInputExpected, out Collection<MergedCompiledCommandParameter> missingMandatoryParameters)
 {
     bool flag = true;
     missingMandatoryParameters = this.GetMissingMandatoryParameters(validParameterSetCount, isPipelineInputExpected);
     if (missingMandatoryParameters.Count <= 0)
     {
         return flag;
     }
     if (promptForMandatory)
     {
         if (base.Context.EngineHostInterface == null)
         {
             ParameterBinderBase.bindingTracer.WriteLine("ERROR: host does not support prompting for missing mandatory parameters", new object[0]);
             string parameterName = BuildMissingParamsString(missingMandatoryParameters);
             ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, this.Command.MyInvocation, null, parameterName, null, null, "ParameterBinderStrings", "MissingMandatoryParameter", new object[0]);
             throw exception;
         }
         Collection<FieldDescription> fieldDescriptionList = this.CreatePromptDataStructures(missingMandatoryParameters);
         Dictionary<string, PSObject> dictionary = this.PromptForMissingMandatoryParameters(fieldDescriptionList, missingMandatoryParameters);
         using (ParameterBinderBase.bindingTracer.TraceScope("BIND PROMPTED mandatory parameter args", new object[0]))
         {
             foreach (KeyValuePair<string, PSObject> pair in dictionary)
             {
                 CommandParameterInternal argument = CommandParameterInternal.CreateParameterWithArgument(PositionUtilities.EmptyExtent, pair.Key, "-" + pair.Key + ":", PositionUtilities.EmptyExtent, pair.Value, false);
                 flag = this.BindParameter(argument, ParameterBindingFlags.ThrowOnParameterNotFound | ParameterBindingFlags.ShouldCoerceType);
             }
             return true;
         }
     }
     return false;
 }
        /// <summary>
        /// Binds the specified parameters to the shell function
        /// </summary>
        /// 
        /// <param name="arguments">
        /// The arguments to bind.
        /// </param>
        /// 
        internal override Collection<CommandParameterInternal> BindParameters(Collection<CommandParameterInternal> arguments)
        {
            Collection<CommandParameterInternal> result = new Collection<CommandParameterInternal>();

            foreach (CommandParameterInternal argument in arguments)
            {
                if (!argument.ParameterNameSpecified)
                {
                    result.Add(argument);
                    continue;
                }

                // We don't want to throw an exception yet because
                // the parameter might be a positional argument 

                MergedCompiledCommandParameter parameter =
                    BindableParameters.GetMatchingParameter(
                        argument.ParameterName,
                        false, true,
                        new InvocationInfo(this.InvocationInfo.MyCommand, argument.ParameterExtent));

                // If the parameter is not in the specified parameter set,
                // throw a binding exception

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

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

                        throw bindingException;
                    }
                    BindParameter(uint.MaxValue, argument, parameter, ParameterBindingFlags.ShouldCoerceType);
                }
                else if (argument.ParameterName.Equals(Language.Parser.VERBATIM_PARAMETERNAME, StringComparison.Ordinal))
                {
                    // We sometimes send a magic parameter from a remote machine with the values referenced via
                    // a using expression ($using:x).  We then access these values via PSBoundParameters, so
                    // "bind" them here.
                    DefaultParameterBinder.CommandLineParameters.SetImplicitUsingParameters(argument.ArgumentValue);
                }
                else
                {
                    result.Add(argument);
                }
            }
            return result;
        }
        /// <summary>
        /// Verify if all arguments from the command line are bound.
        /// </summary>
        /// <param name="originalBindingException">
        /// Previous binding exceptions that possibly causes the failure
        /// </param>
        private void VerifyArgumentsProcessed(ParameterBindingException originalBindingException)
        {
            // Now verify that all the arguments that were passed in were processed.

            if (UnboundArguments.Count > 0)
            {
                ParameterBindingException bindingException;
                CommandParameterInternal parameter = UnboundArguments[0];

                // Get the argument type that was specified

                Type specifiedType = null;
                object argumentValue = parameter.ArgumentValue;
                if (argumentValue != null && argumentValue != UnboundParameter.Value)
                {
                    specifiedType = argumentValue.GetType();
                }

                if (parameter.ParameterNameSpecified)
                {
                    bindingException =
                        new ParameterBindingException(
                            ErrorCategory.InvalidArgument,
                            this.Command.MyInvocation,
                            GetParameterErrorExtent(parameter),
                            parameter.ParameterName,
                            null,
                            specifiedType,
                            ParameterBinderStrings.NamedParameterNotFound,
                            "NamedParameterNotFound");
                }
                else
                {
                    // If this was a positional parameter, and we have the original exception,
                    // report on the original error
                    if (originalBindingException != null)
                    {
                        bindingException = originalBindingException;
                    }
                    // Otherwise, give a generic error.
                    else
                    {
                        string argument = StringLiterals.DollarNull;
                        if (null != parameter.ArgumentValue)
                        {
                            try
                            {
                                argument = parameter.ArgumentValue.ToString();
                            }
                            catch (Exception e)
                            {
                                CommandProcessorBase.CheckForSevereException(e);
                                bindingException =
                                    new ParameterBindingArgumentTransformationException(
                                        e,
                                        ErrorCategory.InvalidData,
                                        this.InvocationInfo,
                                        null,
                                        null,
                                        null,
                                        parameter.ArgumentValue.GetType(),
                                        ParameterBinderStrings.ParameterArgumentTransformationErrorMessageOnly,
                                        "ParameterArgumentTransformationErrorMessageOnly",
                                        e.Message);

                                if (!DefaultParameterBindingInUse)
                                {
                                    throw bindingException;
                                }
                                else
                                {
                                    ThrowElaboratedBindingException(bindingException);
                                }
                            }
                        }

                        bindingException =
                            new ParameterBindingException(
                                ErrorCategory.InvalidArgument,
                                this.Command.MyInvocation,
                                null,
                                argument,
                                null,
                                specifiedType,
                                ParameterBinderStrings.PositionalParameterNotFound,
                                "PositionalParameterNotFound");
                    }
                }
                if (!DefaultParameterBindingInUse)
                {
                    throw bindingException;
                }
                else
                {
                    ThrowElaboratedBindingException(bindingException);
                }
            }
        }
Пример #23
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);
            }
        }
        /// <summary>
        /// Checks for unbound mandatory parameters. If any are found and promptForMandatory is true,
        /// the user will be prompted for the missing mandatory parameters.
        /// </summary>
        /// 
        /// <param name="validParameterSetCount">
        /// The number of valid parameter sets.
        /// </param>
        /// 
        /// <param name="processMissingMandatory">
        /// If true, unbound mandatory parameters will be processed via user prompting (if allowed by promptForMandatory).
        /// If false, unbound mandatory parameters will cause false to be returned.
        /// </param>
        ///
        /// <param name="promptForMandatory">
        /// If true, unbound mandatory parameters will cause the user to be prompted. If false, unbound
        /// mandatory parameters will cause an exception to be thrown.
        /// </param>
        /// 
        /// <param name="isPipelineInputExpected">
        /// If true, then only parameters that don't take pipeline input will be prompted for.
        /// If false, any mandatory parameter that has not been specified will be prompted for.
        /// </param>
        /// 
        /// <param name="missingMandatoryParameters">
        /// Returns the missing mandatory parameters, if any.
        /// </param>
        /// 
        /// <returns>
        /// True if there are no unbound mandatory parameters. False if there are unbound mandatory parameters
        /// and promptForMandatory if false.
        /// </returns>
        /// 
        /// <exception cref="ParameterBindingException">
        /// If prompting didn't result in a value for the parameter (only when <paramref name="promptForMandatory"/> is true.)
        /// </exception>
        /// 
        internal bool HandleUnboundMandatoryParameters(
            int validParameterSetCount,
            bool processMissingMandatory,
            bool promptForMandatory,
            bool isPipelineInputExpected,
            out Collection<MergedCompiledCommandParameter> missingMandatoryParameters)
        {
            bool result = true;

            missingMandatoryParameters = GetMissingMandatoryParameters(validParameterSetCount, isPipelineInputExpected);

            if (missingMandatoryParameters.Count > 0)
            {
                if (processMissingMandatory)
                {
                    // If the host interface wasn't specified or we were instructed not to prmopt, then throw
                    // an exception instead
                    if ((Context.EngineHostInterface == null) || (!promptForMandatory))
                    {
                        Diagnostics.Assert(
                            Context.EngineHostInterface != null,
                            "The EngineHostInterface should never be null");

                        ParameterBinderBase.bindingTracer.WriteLine(
                            "ERROR: host does not support prompting for missing mandatory parameters");

                        string missingParameters = BuildMissingParamsString(missingMandatoryParameters);

                        ParameterBindingException bindingException =
                            new ParameterBindingException(
                                ErrorCategory.InvalidArgument,
                                this.Command.MyInvocation,
                                null,
                                missingParameters,
                                null,
                                null,
                                ParameterBinderStrings.MissingMandatoryParameter,
                                "MissingMandatoryParameter");

                        throw bindingException;
                    }

                    // Create a collection to store the prompt descriptions of unbound mandatory parameters


                    Collection<FieldDescription> fieldDescriptionList = CreatePromptDataStructures(missingMandatoryParameters);


                    Dictionary<String, PSObject> parameters =
                        PromptForMissingMandatoryParameters(
                            fieldDescriptionList,
                            missingMandatoryParameters);

                    using (ParameterBinderBase.bindingTracer.TraceScope(
                        "BIND PROMPTED mandatory parameter args"))
                    {
                        // Now bind any parameters that were retrieved.

                        foreach (KeyValuePair<string, PSObject> entry in parameters)
                        {
                            var argument =
                                CommandParameterInternal.CreateParameterWithArgument(
                                PositionUtilities.EmptyExtent, entry.Key, "-" + entry.Key + ":",
                                PositionUtilities.EmptyExtent, entry.Value,
                                false);

                            // Ignore the result since any failure should cause an exception
                            result =
                                BindParameter(argument, ParameterBindingFlags.ShouldCoerceType | ParameterBindingFlags.ThrowOnParameterNotFound);

                            Diagnostics.Assert(
                                result,
                                "Any error in binding the parameter with type coercion should result in an exception");
                        }
                        result = true;
                    }
                }
                else
                {
                    result = false;
                }
            }

            return result;
        } // HandleUnboundMandatoryParameters
        /// <summary>
        /// Invokes any delay bind script blocks and binds the resulting value
        /// to the appropriate parameter.
        /// </summary>
        /// 
        /// <param name="inputToOperateOn">
        /// The input to the script block.
        /// </param>
        /// 
        /// <param name="thereWasSomethingToBind">
        /// Returns True if there was a ScriptBlock to invoke and bind, or false if there
        /// are no ScriptBlocks to invoke.
        /// </param>
        /// 
        /// <returns>
        /// True if the binding succeeds, or false otherwise.
        /// </returns>
        /// 
        /// <exception cref="ArgumentNullException">
        /// if <paramref name="inputToOperateOn"/> is null.
        /// </exception>
        /// 
        /// <exception cref="ParameterBindingException">
        /// If execution of the script block throws an exception or if it doesn't produce
        /// any output.
        /// </exception>
        /// 
        private bool InvokeAndBindDelayBindScriptBlock(PSObject inputToOperateOn, out bool thereWasSomethingToBind)
        {
            thereWasSomethingToBind = false;
            bool result = true;

            // NOTE: we are not doing backup and restore of default parameter
            // values here.  It is not needed because each script block will be
            // invoked and each delay bind parameter bound for each pipeline object.
            // This is unlike normal pipeline object processing which may bind
            // different parameters depending on the type of the incoming pipeline
            // object.


            // Loop through each of the delay bind script blocks and invoke them.
            // Bind the result to the associated parameter

            foreach (KeyValuePair<MergedCompiledCommandParameter, DelayedScriptBlockArgument> delayedScriptBlock in _delayBindScriptBlocks)
            {
                thereWasSomethingToBind = true;

                CommandParameterInternal argument = delayedScriptBlock.Value._argument;
                MergedCompiledCommandParameter parameter = delayedScriptBlock.Key;

                ScriptBlock script = argument.ArgumentValue as ScriptBlock;

                Diagnostics.Assert(
                    script != null,
                    "An argument should only be put in the delayBindScriptBlocks collection if it is a ScriptBlock");

                Collection<PSObject> output = null;

                Exception error = null;
                using (ParameterBinderBase.bindingTracer.TraceScope(
                    "Invoking delay-bind ScriptBlock"))
                {
                    if (delayedScriptBlock.Value._parameterBinder == this)
                    {
                        try
                        {
                            output = script.DoInvoke(inputToOperateOn, inputToOperateOn, Utils.EmptyArray<object>());
                            delayedScriptBlock.Value._evaluatedArgument = output;
                        }
                        catch (RuntimeException runtimeException)
                        {
                            error = runtimeException;
                        }
                    }
                    else
                    {
                        output = delayedScriptBlock.Value._evaluatedArgument;
                    }
                }

                if (error != null)
                {
                    ParameterBindingException bindingException =
                        new ParameterBindingException(
                            error,
                            ErrorCategory.InvalidArgument,
                            this.Command.MyInvocation,
                            GetErrorExtent(argument),
                            parameter.Parameter.Name,
                            null,
                            null,
                            ParameterBinderStrings.ScriptBlockArgumentInvocationFailed,
                            "ScriptBlockArgumentInvocationFailed",
                            error.Message);

                    throw bindingException;
                }

                if (output == null || output.Count == 0)
                {
                    ParameterBindingException bindingException =
                        new ParameterBindingException(
                            null,
                            ErrorCategory.InvalidArgument,
                            this.Command.MyInvocation,
                            GetErrorExtent(argument),
                            parameter.Parameter.Name,
                            null,
                            null,
                            ParameterBinderStrings.ScriptBlockArgumentNoOutput,
                            "ScriptBlockArgumentNoOutput");

                    throw bindingException;
                }

                // Check the output.  If it is only a single value, just pass the single value,
                // if not, pass in the whole collection.

                object newValue = output;
                if (output.Count == 1)
                {
                    newValue = output[0];
                }


                // Create a new CommandParameterInternal for the output of the script block.
                var newArgument = CommandParameterInternal.CreateParameterWithArgument(
                    argument.ParameterExtent, argument.ParameterName, "-" + argument.ParameterName + ":",
                    argument.ArgumentExtent, newValue,
                    false);

                if (!BindParameter(newArgument, parameter, ParameterBindingFlags.ShouldCoerceType))
                {
                    result = false;
                }
            }

            return result;
        } // InvokeAndBindDelayBindScriptBlock
        /// <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;
        }
        } // HandleRemainingArguments


        /// <summary>
        /// Determines if the cmdlet supports dynamic parameters. If it does,
        /// the dynamic parameter bindable object is retrieved and the unbound
        /// arguments are bound to it.
        /// </summary>
        /// 
        /// <param name="outgoingBindingException">
        /// Returns the underlying parameter binding exception if any was generated.
        /// </param>
        /// 
        /// <exception cref="MetadataException">
        /// If there was an error compiling the parameter metadata.
        /// </exception>
        /// 
        /// <exception cref="ParameterBindingException">
        /// If there was an error binding the arguments to the parameters.
        /// </exception>
        /// 
        private void HandleCommandLineDynamicParameters(out ParameterBindingException outgoingBindingException)
        {
            outgoingBindingException = null;

            if (_commandMetadata.ImplementsDynamicParameters)
            {
                using (ParameterBinderBase.bindingTracer.TraceScope(
                    "BIND cmd line args to DYNAMIC parameters."))
                {
                    s_tracer.WriteLine("The Cmdlet supports the dynamic parameter interface");

                    IDynamicParameters dynamicParameterCmdlet = this.Command as IDynamicParameters;

                    if (dynamicParameterCmdlet != null)
                    {
                        if (_dynamicParameterBinder == null)
                        {
                            s_tracer.WriteLine("Getting the bindable object from the Cmdlet");

                            var psCompiledScriptCmdlet = this.Command as PSScriptCmdlet;
                            if (psCompiledScriptCmdlet != null)
                            {
                                psCompiledScriptCmdlet.PrepareForBinding(
                                    ((ScriptParameterBinder)this.DefaultParameterBinder).LocalScope,
                                    this.CommandLineParameters);
                            }

                            // Now get the dynamic parameter bindable object.
                            object dynamicParamBindableObject;

                            try
                            {
                                dynamicParamBindableObject = dynamicParameterCmdlet.GetDynamicParameters();
                            }
                            catch (Exception e) // Catch-all OK, this is a third-party callout
                            {
                                CommandProcessorBase.CheckForSevereException(e);

                                if (e is ProviderInvocationException) { throw; }

                                ParameterBindingException bindingException =
                                    new ParameterBindingException(
                                        e,
                                        ErrorCategory.InvalidArgument,
                                        this.Command.MyInvocation,
                                        null,
                                        null,
                                        null,
                                        null,
                                        ParameterBinderStrings.GetDynamicParametersException,
                                        "GetDynamicParametersException",
                                        e.Message);

                                // This exception is caused because failure happens when retrieving the dynamic parameters,
                                // this is not caused by introducing the default parameter binding.
                                throw bindingException;
                            }

                            if (dynamicParamBindableObject != null)
                            {
                                ParameterBinderBase.bindingTracer.WriteLine(
                                    "DYNAMIC parameter object: [{0}]",
                                    dynamicParamBindableObject.GetType());

                                s_tracer.WriteLine("Creating a new parameter binder for the dynamic parameter object");

                                InternalParameterMetadata dynamicParameterMetadata;

                                RuntimeDefinedParameterDictionary runtimeParamDictionary = dynamicParamBindableObject as RuntimeDefinedParameterDictionary;
                                if (runtimeParamDictionary != null)
                                {
                                    // Generate the type metadata for the runtime-defined parameters
                                    dynamicParameterMetadata =
                                        InternalParameterMetadata.Get(runtimeParamDictionary, true, true);

                                    _dynamicParameterBinder =
                                        new RuntimeDefinedParameterBinder(
                                            runtimeParamDictionary,
                                            this.Command,
                                            this.CommandLineParameters);
                                }
                                else
                                {
                                    // Generate the type metadata or retrieve it from the cache
                                    dynamicParameterMetadata =
                                        InternalParameterMetadata.Get(dynamicParamBindableObject.GetType(), Context, true);

                                    // Create the parameter binder for the dynamic parameter object

                                    _dynamicParameterBinder =
                                        new ReflectionParameterBinder(
                                            dynamicParamBindableObject,
                                            this.Command,
                                            this.CommandLineParameters);
                                }

                                // Now merge the metadata with other metadata for the command

                                var dynamicParams =
                                    BindableParameters.AddMetadataForBinder(
                                        dynamicParameterMetadata,
                                        ParameterBinderAssociation.DynamicParameters);
                                foreach (var param in dynamicParams)
                                {
                                    UnboundParameters.Add(param);
                                }

                                // Now set the parameter set flags for the new type metadata.
                                _commandMetadata.DefaultParameterSetFlag =
                                    this.BindableParameters.GenerateParameterSetMappingFromMetadata(_commandMetadata.DefaultParameterSetName);
                            }
                        }

                        if (_dynamicParameterBinder == null)
                        {
                            s_tracer.WriteLine("No dynamic parameter object was returned from the Cmdlet");
                            return;
                        }

                        if (UnboundArguments.Count > 0)
                        {
                            using (ParameterBinderBase.bindingTracer.TraceScope(
                                    "BIND NAMED args to DYNAMIC parameters"))
                            {
                                // Try to bind the unbound arguments as static parameters to the 
                                // dynamic parameter object.

                                ReparseUnboundArguments();

                                UnboundArguments = BindParameters(_currentParameterSetFlag, UnboundArguments);
                            }

                            using (ParameterBinderBase.bindingTracer.TraceScope(
                                    "BIND POSITIONAL args to DYNAMIC parameters"))
                            {
                                UnboundArguments =
                                    BindPositionalParameters(
                                    UnboundArguments,
                                    _currentParameterSetFlag,
                                    _commandMetadata.DefaultParameterSetFlag,
                                    out outgoingBindingException);
                            }
                        }
                    } // dynamicParameterCmdlet != null
                }
            }
        } // HandleCommandLineDynamicParameters
 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;
 }
Пример #29
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);
        }
 private void VerifyArgumentsProcessed(ParameterBindingException originalBindingException)
 {
     if (base.UnboundArguments.Count > 0)
     {
         ParameterBindingException exception;
         CommandParameterInternal cpi = base.UnboundArguments[0];
         Type typeSpecified = null;
         object argumentValue = cpi.ArgumentValue;
         if ((argumentValue != null) && (argumentValue != UnboundParameter.Value))
         {
             typeSpecified = argumentValue.GetType();
         }
         if (cpi.ParameterNameSpecified)
         {
             exception = new ParameterBindingException(ErrorCategory.InvalidArgument, this.Command.MyInvocation, base.GetParameterErrorExtent(cpi), cpi.ParameterName, null, typeSpecified, "ParameterBinderStrings", "NamedParameterNotFound", new object[0]);
         }
         else if (originalBindingException != null)
         {
             exception = originalBindingException;
         }
         else
         {
             string parameterName = "$null";
             if (cpi.ArgumentValue != null)
             {
                 try
                 {
                     parameterName = cpi.ArgumentValue.ToString();
                 }
                 catch (Exception exception2)
                 {
                     CommandProcessorBase.CheckForSevereException(exception2);
                     exception = new ParameterBindingArgumentTransformationException(exception2, ErrorCategory.InvalidData, base.InvocationInfo, null, null, null, cpi.ArgumentValue.GetType(), "ParameterBinderStrings", "ParameterArgumentTransformationErrorMessageOnly", new object[] { exception2.Message });
                     if (!base.DefaultParameterBindingInUse)
                     {
                         throw exception;
                     }
                     base.ThrowElaboratedBindingException(exception);
                 }
             }
             exception = new ParameterBindingException(ErrorCategory.InvalidArgument, this.Command.MyInvocation, null, parameterName, null, typeSpecified, "ParameterBinderStrings", "PositionalParameterNotFound", new object[0]);
         }
         if (!base.DefaultParameterBindingInUse)
         {
             throw exception;
         }
         base.ThrowElaboratedBindingException(exception);
     }
 }
 private void ThrowAmbiguousParameterSetException(int parameterSetFlags, MergedCommandParameterMetadata bindableParameters)
 {
     ParameterBindingException pbex = new ParameterBindingException(ErrorCategory.InvalidArgument, this.Command.MyInvocation, null, null, null, null, "ParameterBinderStrings", "AmbiguousParameterSet", new object[0]);
     for (int i = 1; parameterSetFlags != 0; i = i << 1)
     {
         int num2 = parameterSetFlags & 1;
         if (num2 == 1)
         {
             string parameterSetName = bindableParameters.GetParameterSetName(i);
             if (!string.IsNullOrEmpty(parameterSetName))
             {
                 ParameterBinderBase.bindingTracer.WriteLine("Remaining valid parameter set: {0}", new object[] { parameterSetName });
             }
         }
         parameterSetFlags = parameterSetFlags >> 1;
     }
     if (!base.DefaultParameterBindingInUse)
     {
         throw pbex;
     }
     base.ThrowElaboratedBindingException(pbex);
 }
 private void RestoreDefaultParameterValues(IEnumerable<MergedCompiledCommandParameter> parameters)
 {
     if (parameters == null)
     {
         throw PSTraceSource.NewArgumentNullException("parameters");
     }
     foreach (MergedCompiledCommandParameter parameter in parameters)
     {
         if (parameter == null)
         {
             continue;
         }
         CommandParameterInternal argumentToBind = null;
         foreach (CommandParameterInternal internal3 in this._defaultParameterValues.Values)
         {
             if (string.Equals(parameter.Parameter.Name, internal3.ParameterName, StringComparison.OrdinalIgnoreCase))
             {
                 argumentToBind = internal3;
                 break;
             }
         }
         if (argumentToBind != null)
         {
             Exception innerException = null;
             try
             {
                 this.RestoreParameter(argumentToBind, parameter);
             }
             catch (SetValueException exception2)
             {
                 innerException = exception2;
             }
             if (innerException != null)
             {
                 Type typeSpecified = (argumentToBind.ArgumentValue == null) ? null : argumentToBind.ArgumentValue.GetType();
                 ParameterBindingException exception3 = new ParameterBindingException(innerException, ErrorCategory.WriteError, base.InvocationInfo, base.GetErrorExtent(argumentToBind), parameter.Parameter.Name, parameter.Parameter.Type, typeSpecified, "ParameterBinderStrings", "ParameterBindingFailed", new object[] { innerException.Message });
                 throw exception3;
             }
             if (base.BoundParameters.ContainsKey(parameter.Parameter.Name))
             {
                 base.BoundParameters.Remove(parameter.Parameter.Name);
             }
             if (!base.UnboundParameters.Contains(parameter))
             {
                 base.UnboundParameters.Add(parameter);
             }
             if (base.BoundArguments.ContainsKey(parameter.Parameter.Name))
             {
                 base.BoundArguments.Remove(parameter.Parameter.Name);
             }
         }
         else
         {
             if (!base.BoundParameters.ContainsKey(parameter.Parameter.Name))
             {
                 base.BoundParameters.Add(parameter.Parameter.Name, parameter);
             }
             base.UnboundParameters.Remove(parameter);
         }
     }
 }
 private Dictionary<string, PSObject> PromptForMissingMandatoryParameters(Collection<FieldDescription> fieldDescriptionList, Collection<MergedCompiledCommandParameter> missingMandatoryParameters)
 {
     Dictionary<string, PSObject> dictionary = null;
     Exception exception = null;
     try
     {
         ParameterBinderBase.bindingTracer.WriteLine("PROMPTING for missing mandatory parameters using the host", new object[0]);
         string promptMessage = ParameterBinderStrings.PromptMessage;
         InvocationInfo myInvocation = this.Command.MyInvocation;
         string caption = StringUtil.Format(ParameterBinderStrings.PromptCaption, myInvocation.MyCommand.Name, myInvocation.PipelinePosition);
         dictionary = base.Context.EngineHostInterface.UI.Prompt(caption, promptMessage, fieldDescriptionList);
     }
     catch (NotImplementedException exception2)
     {
         exception = exception2;
     }
     catch (HostException exception3)
     {
         exception = exception3;
     }
     catch (PSInvalidOperationException exception4)
     {
         exception = exception4;
     }
     if (exception != null)
     {
         ParameterBinderBase.bindingTracer.WriteLine("ERROR: host does not support prompting for missing mandatory parameters", new object[0]);
         string str3 = BuildMissingParamsString(missingMandatoryParameters);
         ParameterBindingException exception5 = new ParameterBindingException(ErrorCategory.InvalidArgument, this.Command.MyInvocation, null, str3, null, null, "ParameterBinderStrings", "MissingMandatoryParameter", new object[0]);
         throw exception5;
     }
     if ((dictionary != null) && (dictionary.Count != 0))
     {
         return dictionary;
     }
     ParameterBinderBase.bindingTracer.WriteLine("ERROR: still missing mandatory parameters after PROMPTING", new object[0]);
     string parameterName = BuildMissingParamsString(missingMandatoryParameters);
     ParameterBindingException exception6 = new ParameterBindingException(ErrorCategory.InvalidArgument, this.Command.MyInvocation, null, parameterName, null, null, "ParameterBinderStrings", "MissingMandatoryParameter", new object[0]);
     throw exception6;
 }
 private bool InvokeAndBindDelayBindScriptBlock(PSObject inputToOperateOn, out bool thereWasSomethingToBind)
 {
     thereWasSomethingToBind = false;
     bool flag = true;
     foreach (KeyValuePair<MergedCompiledCommandParameter, DelayedScriptBlockArgument> pair in this._delayBindScriptBlocks)
     {
         thereWasSomethingToBind = true;
         CommandParameterInternal cpi = pair.Value._argument;
         MergedCompiledCommandParameter key = pair.Key;
         ScriptBlock argumentValue = cpi.ArgumentValue as ScriptBlock;
         Collection<PSObject> collection = null;
         Exception innerException = null;
         using (ParameterBinderBase.bindingTracer.TraceScope("Invoking delay-bind ScriptBlock", new object[0]))
         {
             if (pair.Value._parameterBinder == this)
             {
                 try
                 {
                     collection = argumentValue.DoInvoke(inputToOperateOn, inputToOperateOn, new object[0]);
                     pair.Value._evaluatedArgument = collection;
                 }
                 catch (RuntimeException exception2)
                 {
                     innerException = exception2;
                 }
             }
             else
             {
                 collection = pair.Value._evaluatedArgument;
             }
         }
         if (innerException != null)
         {
             ParameterBindingException exception3 = new ParameterBindingException(innerException, ErrorCategory.InvalidArgument, this.Command.MyInvocation, base.GetErrorExtent(cpi), key.Parameter.Name, null, null, "ParameterBinderStrings", "ScriptBlockArgumentInvocationFailed", new object[] { innerException.Message });
             throw exception3;
         }
         if ((collection == null) || (collection.Count == 0))
         {
             ParameterBindingException exception4 = new ParameterBindingException(innerException, ErrorCategory.InvalidArgument, this.Command.MyInvocation, base.GetErrorExtent(cpi), key.Parameter.Name, null, null, "ParameterBinderStrings", "ScriptBlockArgumentNoOutput", new object[0]);
             throw exception4;
         }
         object obj2 = collection;
         if (collection.Count == 1)
         {
             obj2 = collection[0];
         }
         CommandParameterInternal argument = CommandParameterInternal.CreateParameterWithArgument(cpi.ParameterExtent, cpi.ParameterName, "-" + cpi.ParameterName + ":", cpi.ArgumentExtent, obj2, false);
         if (!this.BindParameter(argument, key, ParameterBindingFlags.ShouldCoerceType))
         {
             flag = false;
         }
     }
     return flag;
 }
        /// <summary>
        /// Binds the actual arguments to only the formal parameters
        /// for only the parameters in the specified parameter set
        /// </summary>
        /// 
        /// <param name="parameterSets">
        ///     The parameter set used to bind the arguments.
        /// </param>
        /// <param name="arguments">
        ///     The arguments that should be attempted to bind to the parameters of the specified
        ///     parameter binder.
        /// </param>
        /// 
        /// <exception cref="ParameterBindingException">
        /// if multiple parameters are found matching the name.
        /// or
        /// if no match could be found.
        /// or
        /// 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>
        private Collection<CommandParameterInternal> BindParameters(uint parameterSets, Collection<CommandParameterInternal> arguments)
        {
            Collection<CommandParameterInternal> result = new Collection<CommandParameterInternal>();

            foreach (CommandParameterInternal argument in arguments)
            {
                if (!argument.ParameterNameSpecified)
                {
                    result.Add(argument);
                    continue;
                }

                // We don't want to throw an exception yet because
                // the parameter might be a positional argument or it
                // might match up to a dynamic parameter

                MergedCompiledCommandParameter parameter =
                    BindableParameters.GetMatchingParameter(
                        argument.ParameterName,
                        false, true,
                        new InvocationInfo(this.InvocationInfo.MyCommand, argument.ParameterExtent));

                // If the parameter is not in the specified parameter set,
                // throw a binding exception

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

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

                        // Multiple values assigned to the same parameter.
                        // Not caused by default parameter binding
                        throw bindingException;
                    }

                    if ((parameter.Parameter.ParameterSetFlags & parameterSets) == 0 &&
                        !parameter.Parameter.IsInAllSets)
                    {
                        string parameterSetName = BindableParameters.GetParameterSetName(parameterSets);

                        ParameterBindingException bindingException =
                            new ParameterBindingException(
                                ErrorCategory.InvalidArgument,
                                this.Command.MyInvocation,
                                null,
                                argument.ParameterName,
                                null,
                                null,
                                ParameterBinderStrings.ParameterNotInParameterSet,
                                "ParameterNotInParameterSet",
                                parameterSetName);

                        // Might be caused by default parameter binding
                        if (!DefaultParameterBindingInUse)
                        {
                            throw bindingException;
                        }
                        else
                        {
                            ThrowElaboratedBindingException(bindingException);
                        }
                    }

                    try
                    {
                        BindParameter(parameterSets, argument, parameter,
                            ParameterBindingFlags.ShouldCoerceType | ParameterBindingFlags.DelayBindScriptBlock);
                    }
                    catch (ParameterBindingException pbex)
                    {
                        if (!DefaultParameterBindingInUse)
                        {
                            throw;
                        }

                        ThrowElaboratedBindingException(pbex);
                    }
                }
                else if (argument.ParameterName.Equals(Parser.VERBATIM_PARAMETERNAME, StringComparison.Ordinal))
                {
                    // We sometimes send a magic parameter from a remote machine with the values referenced via
                    // a using expression ($using:x).  We then access these values via PSBoundParameters, so
                    // "bind" them here.
                    DefaultParameterBinder.CommandLineParameters.SetImplicitUsingParameters(argument.ArgumentValue);
                }
                else
                {
                    result.Add(argument);
                }
            }
            return result;
        } // BindParameters
Пример #36
0
        private bool BindPositionalParametersInSet(int validParameterSets, Dictionary <MergedCompiledCommandParameter, PositionalCommandParameter> nextPositionalParameters, CommandParameterInternal argument, ParameterBindingFlags flags, out ParameterBindingException bindingException)
        {
            bool flag = false;

            bindingException = null;
            foreach (PositionalCommandParameter parameter in nextPositionalParameters.Values)
            {
                foreach (ParameterSetSpecificMetadata metadata in parameter.ParameterSetData)
                {
                    if (((validParameterSets & metadata.ParameterSetFlag) != 0) || metadata.IsInAllSets)
                    {
                        bool   flag2 = false;
                        string name  = parameter.Parameter.Parameter.Name;
                        ParameterBindingException pbex = null;
                        try
                        {
                            CommandParameterInternal internal2 = CommandParameterInternal.CreateParameterWithArgument(PositionUtilities.EmptyExtent, name, "-" + name + ":", argument.ArgumentExtent, argument.ArgumentValue, false);
                            flag2 = this.BindParameter(validParameterSets, internal2, parameter.Parameter, flags);
                        }
                        catch (ParameterBindingArgumentTransformationException exception2)
                        {
                            pbex = exception2;
                        }
                        catch (ParameterBindingValidationException exception3)
                        {
                            if (exception3.SwallowException)
                            {
                                flag2            = false;
                                bindingException = exception3;
                            }
                            else
                            {
                                pbex = exception3;
                            }
                        }
                        catch (ParameterBindingParameterDefaultValueException exception4)
                        {
                            pbex = exception4;
                        }
                        catch (ParameterBindingException exception5)
                        {
                            flag2            = false;
                            bindingException = exception5;
                        }
                        if (pbex != null)
                        {
                            if (!this.DefaultParameterBindingInUse)
                            {
                                throw pbex;
                            }
                            this.ThrowElaboratedBindingException(pbex);
                        }
                        if (flag2)
                        {
                            flag = true;
                            this.CommandLineParameters.MarkAsBoundPositionally(name);
                            break;
                        }
                    }
                }
            }
            return(flag);
        }
        /// <summary>
        /// Binds the remaining arguments to an unbound ValueFromRemainingArguments parameter (Varargs)
        /// </summary>
        /// 
        /// <exception cref="ParameterBindingException">
        /// If there was an error binding the arguments to the parameters.
        /// </exception>
        /// 
        private void HandleRemainingArguments()
        {
            if (UnboundArguments.Count > 0)
            {
                // Find the parameters that take the remaining args, if there are more
                // than one and the parameter set has not been defined, this is an error

                MergedCompiledCommandParameter varargsParameter = null;

                foreach (MergedCompiledCommandParameter parameter in UnboundParameters)
                {
                    ParameterSetSpecificMetadata parameterSetData = parameter.Parameter.GetParameterSetData(_currentParameterSetFlag);

                    if (parameterSetData == null)
                    {
                        continue;
                    }

                    // If the parameter takes the remaining arguments, bind them.

                    if (parameterSetData.ValueFromRemainingArguments)
                    {
                        if (varargsParameter != null)
                        {
                            ParameterBindingException bindingException =
                                new ParameterBindingException(
                                        ErrorCategory.MetadataError,
                                        this.Command.MyInvocation,
                                        null,
                                        parameter.Parameter.Name,
                                        parameter.Parameter.Type,
                                        null,
                                        ParameterBinderStrings.AmbiguousParameterSet,
                                        "AmbiguousParameterSet");

                            // Might be caused by the default parameter binding
                            if (!DefaultParameterBindingInUse)
                            {
                                throw bindingException;
                            }
                            else
                            {
                                ThrowElaboratedBindingException(bindingException);
                            }
                        }
                        varargsParameter = parameter;
                    }
                }

                if (varargsParameter != null)
                {
                    using (ParameterBinderBase.bindingTracer.TraceScope(
                        "BIND REMAININGARGUMENTS cmd line args to param: [{0}]",
                        varargsParameter.Parameter.Name))
                    {
                        // Accumulate the unbound arguments in to an list and then bind it to the parameter

                        List<object> valueFromRemainingArguments = new List<object>();

                        foreach (CommandParameterInternal argument in UnboundArguments)
                        {
                            if (argument.ParameterNameSpecified)
                            {
                                Diagnostics.Assert(!string.IsNullOrEmpty(argument.ParameterText), "Don't add a null argument");
                                valueFromRemainingArguments.Add(argument.ParameterText);
                            }

                            if (argument.ArgumentSpecified)
                            {
                                object argumentValue = argument.ArgumentValue;
                                if (argumentValue != AutomationNull.Value && argumentValue != UnboundParameter.Value)
                                {
                                    valueFromRemainingArguments.Add(argumentValue);
                                }
                            }
                        }

                        // If there are multiple arguments, it's not clear how best to represent the extent as the extent
                        // may be disjoint, as in 'echo a -verbose b', we have 'a' and 'b' in UnboundArguments.
                        IScriptExtent argumentExtent = UnboundArguments.Count == 1
                                                           ? UnboundArguments[0].ArgumentExtent
                                                           : PositionUtilities.EmptyExtent;
                        var cpi = CommandParameterInternal.CreateParameterWithArgument(
                            PositionUtilities.EmptyExtent, varargsParameter.Parameter.Name, "-" + varargsParameter.Parameter.Name + ":",
                            argumentExtent, valueFromRemainingArguments, false);
                        try
                        {
                            BindParameter(cpi, varargsParameter, ParameterBindingFlags.ShouldCoerceType);
                        }
                        catch (ParameterBindingException pbex)
                        {
                            // To make all of the following work similarly (the first is handled elsewhere, but second and third are
                            // handled here):
                            //     Set-ClusterOwnerNode -Owners foo,bar
                            //     Set-ClusterOwnerNode foo bar
                            //     Set-ClusterOwnerNode foo,bar
                            // we make one additional attempt at converting, but only if there is a single argument of type object[].
                            if (valueFromRemainingArguments.Count == 1 && valueFromRemainingArguments[0] is object[])
                            {
                                cpi.SetArgumentValue(UnboundArguments[0].ArgumentExtent, valueFromRemainingArguments[0]);
                                BindParameter(cpi, varargsParameter, ParameterBindingFlags.ShouldCoerceType);
                            }
                            else
                            {
                                if (!DefaultParameterBindingInUse)
                                {
                                    throw;
                                }
                                else
                                {
                                    ThrowElaboratedBindingException(pbex);
                                }
                            }
                        }
                        UnboundArguments.Clear();
                    }
                }
            }
        } // HandleRemainingArguments
 internal MergedCompiledCommandParameter GetMatchingParameter(string name, bool throwOnParameterNotFound, bool tryExactMatching, InvocationInfo invocationInfo)
 {
     if (string.IsNullOrEmpty(name))
     {
         throw PSTraceSource.NewArgumentException("name");
     }
     Collection<MergedCompiledCommandParameter> collection = new Collection<MergedCompiledCommandParameter>();
     if ((name.Length > 0) && SpecialCharacters.IsDash(name[0]))
     {
         name = name.Substring(1);
     }
     foreach (string str in this.bindableParameters.Keys)
     {
         if (nameCompareInfo.IsPrefix(str, name, CompareOptions.IgnoreCase))
         {
             if (tryExactMatching && string.Equals(str, name, StringComparison.OrdinalIgnoreCase))
             {
                 return this.bindableParameters[str];
             }
             collection.Add(this.bindableParameters[str]);
         }
     }
     foreach (string str2 in this.aliasedParameters.Keys)
     {
         if (nameCompareInfo.IsPrefix(str2, name, CompareOptions.IgnoreCase))
         {
             if (tryExactMatching && string.Equals(str2, name, StringComparison.OrdinalIgnoreCase))
             {
                 return this.aliasedParameters[str2];
             }
             if (!collection.Contains(this.aliasedParameters[str2]))
             {
                 collection.Add(this.aliasedParameters[str2]);
             }
         }
     }
     if (collection.Count > 1)
     {
         StringBuilder builder = new StringBuilder();
         foreach (MergedCompiledCommandParameter parameter in collection)
         {
             builder.AppendFormat(" -{0}", parameter.Parameter.Name);
         }
         ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, invocationInfo, null, name, null, null, "ParameterBinderStrings", "AmbiguousParameter", new object[] { builder });
         throw exception;
     }
     if ((collection.Count == 0) && throwOnParameterNotFound)
     {
         ParameterBindingException exception2 = new ParameterBindingException(ErrorCategory.InvalidArgument, invocationInfo, null, name, null, null, "ParameterBinderStrings", "NamedParameterNotFound", new object[0]);
         throw exception2;
     }
     MergedCompiledCommandParameter parameter2 = null;
     if (collection.Count > 0)
     {
         parameter2 = collection[0];
     }
     return parameter2;
 }
        private void ThrowAmbiguousParameterSetException(uint parameterSetFlags, MergedCommandParameterMetadata bindableParameters)
        {
            ParameterBindingException bindingException =
                new ParameterBindingException(
                    ErrorCategory.InvalidArgument,
                    this.Command.MyInvocation,
                    null,
                    null,
                    null,
                    null,
                    ParameterBinderStrings.AmbiguousParameterSet,
                    "AmbiguousParameterSet");


            // Trace the parameter sets still active
            uint currentParameterSet = 1;

            while (parameterSetFlags != 0)
            {
                uint currentParameterSetActive = parameterSetFlags & 0x1;

                if (currentParameterSetActive == 1)
                {
                    string parameterSetName = bindableParameters.GetParameterSetName(currentParameterSet);
                    if (!String.IsNullOrEmpty(parameterSetName))
                    {
                        ParameterBinderBase.bindingTracer.WriteLine("Remaining valid parameter set: {0}", parameterSetName);
                    }
                }

                parameterSetFlags >>= 1;
                currentParameterSet <<= 1;
            }

            if (!DefaultParameterBindingInUse)
            {
                throw bindingException;
            }
            else
            {
                ThrowElaboratedBindingException(bindingException);
            }
        }
Пример #40
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;
 }
        } // HandleUnboundMandatoryParameters

        private Dictionary<string, PSObject> PromptForMissingMandatoryParameters(
            Collection<FieldDescription> fieldDescriptionList,
            Collection<MergedCompiledCommandParameter> missingMandatoryParameters)
        {
            Dictionary<string, PSObject> parameters = null;

            Exception error = null;

            // Prompt
            try
            {
                ParameterBinderBase.bindingTracer.WriteLine(
                    "PROMPTING for missing mandatory parameters using the host");
                string msg = ParameterBinderStrings.PromptMessage;
                InvocationInfo invoInfo = Command.MyInvocation;
                string caption = StringUtil.Format(ParameterBinderStrings.PromptCaption,
                    invoInfo.MyCommand.Name,
                    invoInfo.PipelinePosition);

                parameters = Context.EngineHostInterface.UI.Prompt(caption, msg, fieldDescriptionList);
            }
            catch (NotImplementedException notImplemented)
            {
                error = notImplemented;
            }
            catch (HostException hostException)
            {
                error = hostException;
            }
            catch (PSInvalidOperationException invalidOperation)
            {
                error = invalidOperation;
            }

            if (error != null)
            {
                ParameterBinderBase.bindingTracer.WriteLine(
                    "ERROR: host does not support prompting for missing mandatory parameters");

                string missingParameters = BuildMissingParamsString(missingMandatoryParameters);

                ParameterBindingException bindingException =
                    new ParameterBindingException(
                        ErrorCategory.InvalidArgument,
                        this.Command.MyInvocation,
                        null,
                        missingParameters,
                        null,
                        null,
                        ParameterBinderStrings.MissingMandatoryParameter,
                        "MissingMandatoryParameter");

                throw bindingException;
            }

            if ((parameters == null) || (parameters.Count == 0))
            {
                ParameterBinderBase.bindingTracer.WriteLine(
                    "ERROR: still missing mandatory parameters after PROMPTING");

                string missingParameters = BuildMissingParamsString(missingMandatoryParameters);

                ParameterBindingException bindingException =
                    new ParameterBindingException(
                        ErrorCategory.InvalidArgument,
                        this.Command.MyInvocation,
                        null,
                        missingParameters,
                        null,
                        null,
                        ParameterBinderStrings.MissingMandatoryParameter,
                        "MissingMandatoryParameter");

                throw bindingException;
            }

            return parameters;
        }
Пример #42
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);
        }
        /// <summary>
        /// Replaces the values of the parameters with their initial value for the
        /// parameters specified.
        /// </summary>
        /// 
        /// <param name="parameters">
        /// The parameters that should have their default values restored.
        /// </param>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="parameters"/> is null.
        /// </exception>
        /// 
        private void RestoreDefaultParameterValues(IEnumerable<MergedCompiledCommandParameter> parameters)
        {
            if (parameters == null)
            {
                throw PSTraceSource.NewArgumentNullException("parameters");
            }

            // Get all the matching arguments from the defaultParameterValues collection
            // and bind those that had parameters that were bound via pipeline input

            foreach (MergedCompiledCommandParameter parameter in parameters)
            {
                if (parameter == null)
                {
                    continue;
                }

                CommandParameterInternal argumentToBind = null;

                // If the argument was found then bind it to the parameter
                // and manage the bound and unbound parameter list

                if (_defaultParameterValues.TryGetValue(parameter.Parameter.Name, out argumentToBind))
                {
                    // Don't go through the normal binding routine to run data generation,
                    // type coercion, validation, or prerequisites since we know the
                    // type is already correct, and we don't want data generation to
                    // run when resetting the default value.

                    Exception error = null;
                    try
                    {
                        // We shouldn't have to coerce the type here so its
                        // faster to pass false

                        bool bindResult = RestoreParameter(argumentToBind, parameter);

                        Diagnostics.Assert(
                            bindResult,
                            "Restoring the default value should not require type coercion");
                    }
                    catch (SetValueException setValueException)
                    {
                        error = setValueException;
                    }

                    if (error != null)
                    {
                        Type specifiedType = (argumentToBind.ArgumentValue == null) ? null : argumentToBind.ArgumentValue.GetType();
                        ParameterBindingException bindingException =
                            new ParameterBindingException(
                                error,
                                ErrorCategory.WriteError,
                                this.InvocationInfo,
                                GetErrorExtent(argumentToBind),
                                parameter.Parameter.Name,
                                parameter.Parameter.Type,
                                specifiedType,
                                ParameterBinderStrings.ParameterBindingFailed,
                                "ParameterBindingFailed",
                                error.Message);
                        throw bindingException;
                    }

                    // Since the parameter was returned to its original value,
                    // ensure that it is not in the boundParameters list but
                    // is in the unboundParameters list

                    BoundParameters.Remove(parameter.Parameter.Name);

                    if (!UnboundParameters.Contains(parameter))
                    {
                        UnboundParameters.Add(parameter);
                    }

                    BoundArguments.Remove(parameter.Parameter.Name);
                }
                else
                {
                    // Since the parameter was not reset, ensure that the parameter
                    // is in the bound parameters list and not in the unbound
                    // parameters list

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

                    // Ensure the parameter is not in the unboundParameters list

                    UnboundParameters.Remove(parameter);
                }
            }
        }
Пример #44
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;
 }
Пример #45
0
        internal Collection <CommandParameterInternal> BindPositionalParameters(Collection <CommandParameterInternal> unboundArguments, int validParameterSets, int defaultParameterSet, out ParameterBindingException outgoingBindingException)
        {
            Collection <CommandParameterInternal> nonPositionalArguments = new Collection <CommandParameterInternal>();

            outgoingBindingException = null;
            if (unboundArguments.Count > 0)
            {
                SortedDictionary <int, Dictionary <MergedCompiledCommandParameter, PositionalCommandParameter> > dictionary;
                List <CommandParameterInternal> unboundArgumentsCollection = new List <CommandParameterInternal>(unboundArguments);
                try
                {
                    dictionary = EvaluateUnboundPositionalParameters(this.UnboundParameters, this._currentParameterSetFlag);
                }
                catch (InvalidOperationException)
                {
                    ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, this.InvocationInfo, null, null, null, null, "ParameterBinderStrings", "AmbiguousPositionalParameterNoName", new object[0]);
                    throw exception;
                }
                if (dictionary.Count <= 0)
                {
                    return(unboundArguments);
                }
                int unboundArgumentsIndex = 0;
                foreach (Dictionary <MergedCompiledCommandParameter, PositionalCommandParameter> dictionary2 in dictionary.Values)
                {
                    if (dictionary2.Count != 0)
                    {
                        CommandParameterInternal argument = GetNextPositionalArgument(unboundArgumentsCollection, nonPositionalArguments, ref unboundArgumentsIndex);
                        if (argument == null)
                        {
                            break;
                        }
                        bool flag = false;
                        if ((defaultParameterSet != 0) && ((validParameterSets & defaultParameterSet) != 0))
                        {
                            flag = this.BindPositionalParametersInSet(defaultParameterSet, dictionary2, argument, ParameterBindingFlags.DelayBindScriptBlock, out outgoingBindingException);
                        }
                        if (!flag)
                        {
                            flag = this.BindPositionalParametersInSet(validParameterSets, dictionary2, argument, ParameterBindingFlags.DelayBindScriptBlock, out outgoingBindingException);
                        }
                        if ((!flag && (defaultParameterSet != 0)) && ((validParameterSets & defaultParameterSet) != 0))
                        {
                            flag = this.BindPositionalParametersInSet(defaultParameterSet, dictionary2, argument, ParameterBindingFlags.DelayBindScriptBlock | ParameterBindingFlags.ShouldCoerceType, out outgoingBindingException);
                        }
                        if (!flag)
                        {
                            flag = this.BindPositionalParametersInSet(validParameterSets, dictionary2, argument, ParameterBindingFlags.DelayBindScriptBlock | ParameterBindingFlags.ShouldCoerceType, out outgoingBindingException);
                        }
                        if (!flag)
                        {
                            nonPositionalArguments.Add(argument);
                        }
                        else if (validParameterSets != this._currentParameterSetFlag)
                        {
                            validParameterSets = this._currentParameterSetFlag;
                            UpdatePositionalDictionary(dictionary, validParameterSets);
                        }
                    }
                }
                for (int i = unboundArgumentsIndex; i < unboundArgumentsCollection.Count; i++)
                {
                    nonPositionalArguments.Add(unboundArgumentsCollection[i]);
                }
            }
            return(nonPositionalArguments);
        }
Пример #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;
         }
     }
 }
Пример #47
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;
 }
 private void HandleRemainingArguments()
 {
     if (base.UnboundArguments.Count > 0)
     {
         MergedCompiledCommandParameter parameter = null;
         foreach (MergedCompiledCommandParameter parameter2 in base.UnboundParameters)
         {
             ParameterSetSpecificMetadata parameterSetData = parameter2.Parameter.GetParameterSetData(base._currentParameterSetFlag);
             if ((parameterSetData != null) && parameterSetData.ValueFromRemainingArguments)
             {
                 if (parameter != null)
                 {
                     ParameterBindingException pbex = new ParameterBindingException(ErrorCategory.MetadataError, this.Command.MyInvocation, null, parameter2.Parameter.Name, parameter2.Parameter.Type, null, "ParameterBinderStrings", "AmbiguousParameterSet", new object[0]);
                     if (!base.DefaultParameterBindingInUse)
                     {
                         throw pbex;
                     }
                     base.ThrowElaboratedBindingException(pbex);
                 }
                 parameter = parameter2;
             }
         }
         if (parameter != null)
         {
             using (ParameterBinderBase.bindingTracer.TraceScope("BIND REMAININGARGUMENTS cmd line args to param: [{0}]", new object[] { parameter.Parameter.Name }))
             {
                 ArrayList list = new ArrayList();
                 foreach (CommandParameterInternal internal2 in base.UnboundArguments)
                 {
                     if (internal2.ParameterNameSpecified)
                     {
                         list.Add(internal2.ParameterText);
                     }
                     if (internal2.ArgumentSpecified)
                     {
                         object argumentValue = internal2.ArgumentValue;
                         if ((argumentValue != AutomationNull.Value) && (argumentValue != UnboundParameter.Value))
                         {
                             list.Add(argumentValue);
                         }
                     }
                 }
                 IScriptExtent argumentExtent = (base.UnboundArguments.Count == 1) ? base.UnboundArguments[0].ArgumentExtent : PositionUtilities.EmptyExtent;
                 CommandParameterInternal argument = CommandParameterInternal.CreateParameterWithArgument(PositionUtilities.EmptyExtent, parameter.Parameter.Name, "-" + parameter.Parameter.Name + ":", argumentExtent, list, false);
                 try
                 {
                     this.BindParameter(argument, parameter, ParameterBindingFlags.ShouldCoerceType);
                 }
                 catch (ParameterBindingException exception2)
                 {
                     if ((list.Count == 1) && (list[0] is object[]))
                     {
                         argument.SetArgumentValue(base.UnboundArguments[0].ArgumentExtent, list[0]);
                         this.BindParameter(argument, parameter, ParameterBindingFlags.ShouldCoerceType);
                     }
                     else
                     {
                         if (!base.DefaultParameterBindingInUse)
                         {
                             throw;
                         }
                         base.ThrowElaboratedBindingException(exception2);
                     }
                 }
                 base.UnboundArguments.Clear();
             }
         }
     }
 }
 private Collection<CommandParameterInternal> BindParameters(int parameterSets, Collection<CommandParameterInternal> arguments)
 {
     Collection<CommandParameterInternal> collection = new Collection<CommandParameterInternal>();
     foreach (CommandParameterInternal internal2 in arguments)
     {
         if (!internal2.ParameterNameSpecified)
         {
             collection.Add(internal2);
         }
         else
         {
             MergedCompiledCommandParameter parameter = base.BindableParameters.GetMatchingParameter(internal2.ParameterName, false, true, new InvocationInfo(base.InvocationInfo.MyCommand, internal2.ParameterExtent));
             if (parameter != null)
             {
                 if (base.BoundParameters.ContainsKey(parameter.Parameter.Name))
                 {
                     ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, base.InvocationInfo, base.GetParameterErrorExtent(internal2), internal2.ParameterName, null, null, "ParameterBinderStrings", "ParameterAlreadyBound", new object[0]);
                     throw exception;
                 }
                 if (((parameter.Parameter.ParameterSetFlags & parameterSets) == 0) && !parameter.Parameter.IsInAllSets)
                 {
                     string parameterSetName = base.BindableParameters.GetParameterSetName(parameterSets);
                     ParameterBindingException pbex = new ParameterBindingException(ErrorCategory.InvalidArgument, this.Command.MyInvocation, null, internal2.ParameterName, null, null, "ParameterBinderStrings", "ParameterNotInParameterSet", new object[] { parameterSetName });
                     if (!base.DefaultParameterBindingInUse)
                     {
                         throw pbex;
                     }
                     base.ThrowElaboratedBindingException(pbex);
                 }
                 try
                 {
                     this.BindParameter(parameterSets, internal2, parameter, ParameterBindingFlags.DelayBindScriptBlock | ParameterBindingFlags.ShouldCoerceType);
                 }
                 catch (ParameterBindingException exception3)
                 {
                     if (!base.DefaultParameterBindingInUse)
                     {
                         throw;
                     }
                     base.ThrowElaboratedBindingException(exception3);
                 }
             }
             else if (internal2.ParameterName.Equals("-%", StringComparison.Ordinal))
             {
                 base.DefaultParameterBinder.CommandLineParameters.SetImplicitUsingParameters(internal2.ArgumentValue);
             }
             else
             {
                 collection.Add(internal2);
             }
         }
     }
     return collection;
 }
Пример #50
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;
     }
 }
        /// <summary>
        /// Gets the parameters by matching its name.
        /// </summary>
        /// <param name="name">
        /// The name of the parameter.
        /// </param>
        /// <param name="throwOnParameterNotFound">
        /// If true and a matching parameter is not found, an exception will be
        /// throw. If false and a matching parameter is not found, null is returned.
        /// </param>
        /// <param name="tryExactMatching">
        /// If true we do exact matching, otherwise we do not.
        /// </param>
        /// <param name="invocationInfo">
        /// The invocation information about the code being run.
        /// </param>
        /// <returns>
        /// The a collection of the metadata associated with the parameters that
        /// match the specified name. If no matches were found, an empty collection
        /// is returned.
        /// </returns>
        /// <exception cref="ArgumentException">
        /// If <paramref name="name"/> is null or empty.
        /// </exception>
        internal MergedCompiledCommandParameter GetMatchingParameter(
            string name,
            bool throwOnParameterNotFound,
            bool tryExactMatching,
            InvocationInfo invocationInfo)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw PSTraceSource.NewArgumentException("name");
            }

            Collection <MergedCompiledCommandParameter> matchingParameters =
                new Collection <MergedCompiledCommandParameter>();

            // Skip the leading '-' if present
            if (name.Length > 0 && CharExtensions.IsDash(name[0]))
            {
                name = name.Substring(1);
            }

            // First try to match the bindable parameters

            foreach (string parameterName in _bindableParameters.Keys)
            {
                if (CultureInfo.InvariantCulture.CompareInfo.IsPrefix(parameterName, name, CompareOptions.IgnoreCase))
                {
                    // If it is an exact match then only return the exact match
                    // as the result

                    if (tryExactMatching && string.Equals(parameterName, name, StringComparison.OrdinalIgnoreCase))
                    {
                        return(_bindableParameters[parameterName]);
                    }
                    else
                    {
                        matchingParameters.Add(_bindableParameters[parameterName]);
                    }
                }
            }

            // Now check the aliases

            foreach (string parameterName in _aliasedParameters.Keys)
            {
                if (CultureInfo.InvariantCulture.CompareInfo.IsPrefix(parameterName, name, CompareOptions.IgnoreCase))
                {
                    // If it is an exact match then only return the exact match
                    // as the result

                    if (tryExactMatching && string.Equals(parameterName, name, StringComparison.OrdinalIgnoreCase))
                    {
                        return(_aliasedParameters[parameterName]);
                    }
                    else
                    {
                        if (!matchingParameters.Contains(_aliasedParameters[parameterName]))
                        {
                            matchingParameters.Add(_aliasedParameters[parameterName]);
                        }
                    }
                }
            }

            if (matchingParameters.Count > 1)
            {
                // Prefer parameters in the cmdlet over common parameters
                Collection <MergedCompiledCommandParameter> filteredParameters =
                    new Collection <MergedCompiledCommandParameter>();

                foreach (MergedCompiledCommandParameter matchingParameter in matchingParameters)
                {
                    if ((matchingParameter.BinderAssociation == ParameterBinderAssociation.DeclaredFormalParameters) ||
                        (matchingParameter.BinderAssociation == ParameterBinderAssociation.DynamicParameters))
                    {
                        filteredParameters.Add(matchingParameter);
                    }
                }

                if (tryExactMatching && filteredParameters.Count == 1)
                {
                    matchingParameters = filteredParameters;
                }
                else
                {
                    StringBuilder possibleMatches = new StringBuilder();

                    foreach (MergedCompiledCommandParameter matchingParameter in matchingParameters)
                    {
                        possibleMatches.Append(" -");
                        possibleMatches.Append(matchingParameter.Parameter.Name);
                    }

                    ParameterBindingException exception =
                        new ParameterBindingException(
                            ErrorCategory.InvalidArgument,
                            invocationInfo,
                            null,
                            name,
                            null,
                            null,
                            ParameterBinderStrings.AmbiguousParameter,
                            "AmbiguousParameter",
                            possibleMatches);

                    throw exception;
                }
            }
            else if (matchingParameters.Count == 0)
            {
                if (throwOnParameterNotFound)
                {
                    ParameterBindingException exception =
                        new ParameterBindingException(
                            ErrorCategory.InvalidArgument,
                            invocationInfo,
                            null,
                            name,
                            null,
                            null,
                            ParameterBinderStrings.NamedParameterNotFound,
                            "NamedParameterNotFound");

                    throw exception;
                }
            }

            MergedCompiledCommandParameter result = null;

            if (matchingParameters.Count > 0)
            {
                result = matchingParameters[0];
            }

            return(result);
        }
Пример #52
0
        internal MergedCompiledCommandParameter GetMatchingParameter(
            string name,
            bool throwOnParameterNotFound,
            InvocationInfo invocationInfo)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw MergedCommandParameterMetadata.tracer.NewArgumentException(nameof(name));
            }
            Collection <MergedCompiledCommandParameter> collection = new Collection <MergedCompiledCommandParameter>();

            if (name.Length > 0 && SpecialCharacters.IsDash(name[0]))
            {
                name = name.Substring(1);
            }
            foreach (string key in this.bindableParameters.Keys)
            {
                if (this.nameCompareInfo.IsPrefix(key, name, CompareOptions.IgnoreCase))
                {
                    MergedCommandParameterMetadata.tracer.WriteLine("Found match: {0}", (object)key);
                    if (string.Equals(key, name, StringComparison.OrdinalIgnoreCase))
                    {
                        return(this.bindableParameters[key]);
                    }
                    collection.Add(this.bindableParameters[key]);
                }
            }
            foreach (string key in this.aliasedParameters.Keys)
            {
                if (this.nameCompareInfo.IsPrefix(key, name, CompareOptions.IgnoreCase))
                {
                    MergedCommandParameterMetadata.tracer.WriteLine("Found match: {0}", (object)key);
                    if (string.Equals(key, name, StringComparison.OrdinalIgnoreCase))
                    {
                        return(this.aliasedParameters[key]);
                    }
                    if (!collection.Contains(this.aliasedParameters[key]))
                    {
                        collection.Add(this.aliasedParameters[key]);
                    }
                }
            }
            if (collection.Count > 1)
            {
                StringBuilder stringBuilder = new StringBuilder();
                foreach (MergedCompiledCommandParameter commandParameter in collection)
                {
                    stringBuilder.AppendFormat(" -{0}", (object)commandParameter.Parameter.Name);
                }
                ParameterBindingException bindingException = new ParameterBindingException(ErrorCategory.InvalidArgument, invocationInfo, (Token)null, name, (Type)null, (Type)null, "ParameterBinderStrings", "AmbiguousParameter", new object[1]
                {
                    (object)stringBuilder
                });
                MergedCommandParameterMetadata.tracer.TraceException((Exception)bindingException);
                throw bindingException;
            }
            if (collection.Count == 0 && throwOnParameterNotFound)
            {
                ParameterBindingException bindingException = new ParameterBindingException(ErrorCategory.InvalidArgument, invocationInfo, (Token)null, name, (Type)null, (Type)null, "ParameterBinderStrings", "NamedParameterNotFound", new object[0]);
                MergedCommandParameterMetadata.tracer.TraceException((Exception)bindingException);
                throw bindingException;
            }
            MergedCompiledCommandParameter commandParameter1 = (MergedCompiledCommandParameter)null;

            if (collection.Count > 0)
            {
                commandParameter1 = collection[0];
            }
            return(commandParameter1);
        }