Exemple #1
0
        internal static PSReference GetVariableAsRef(VariablePath variablePath, ExecutionContext executionContext, Type staticType)
        {
            Diagnostics.Assert(variablePath.IsVariable, "calller to verify varpath is a variable.");

            SessionStateInternal sessionState = executionContext.EngineSessionState;
            CommandOrigin        origin       = sessionState.CurrentScope.ScopeOrigin;

            SessionStateScope scope;
            PSVariable        var = sessionState.GetVariableItem(variablePath, out scope, origin);

            if (var == null)
            {
                throw InterpreterError.NewInterpreterException(variablePath, typeof(RuntimeException), null,
                                                               "NonExistingVariableReference",
                                                               ParserStrings.NonExistingVariableReference);
            }

            object value = var.Value;

            if (staticType == null && value != null)
            {
                value = PSObject.Base(value);
                if (value != null)
                {
                    staticType = value.GetType();
                }
            }

            if (staticType == null)
            {
                var declaredType = var.Attributes.OfType <ArgumentTypeConverterAttribute>().FirstOrDefault();
                staticType = declaredType != null ? declaredType.TargetType : typeof(LanguagePrimitives.Null);
            }

            return(PSReference.CreateInstance(var, staticType));
        }
Exemple #2
0
        internal static object IsOperator(System.Management.Automation.ExecutionContext context, IScriptExtent errorPosition, object left, object right)
        {
            object o    = PSObject.Base(left);
            object obj3 = PSObject.Base(right);
            Type   type = obj3 as Type;

            if (type == null)
            {
                type = ConvertTo <Type>(obj3, errorPosition);
                if (type == null)
                {
                    throw InterpreterError.NewInterpreterException(obj3, typeof(RuntimeException), errorPosition, "IsOperatorRequiresType", ParserStrings.IsOperatorRequiresType, new object[0]);
                }
            }
            if ((type == typeof(PSCustomObject)) && (o is PSObject))
            {
                return(_TrueObject);
            }
            if (type.Equals(typeof(PSObject)) && (left is PSObject))
            {
                return(_TrueObject);
            }
            return(BoolToObject(type.IsInstanceOfType(o)));
        }
Exemple #3
0
        /// <summary>
        /// Get a Hashtable object out of a PowerShell data file (.psd1)
        /// </summary>
        /// <param name="parameterName">
        /// Name of the parameter that takes the specified .psd1 file as a value
        /// </param>
        /// <param name="psDataFilePath">
        /// Path to the powershell data file
        /// </param>
        /// <param name="context">
        /// ExecutionContext to use
        /// </param>
        /// <param name="allowedCommands">
        /// Set of command names that are allowed to use in the .psd1 file
        /// </param>
        /// <param name="allowedVariables">
        /// Set of variable names that are allowed to use in the .psd1 file
        /// </param>
        /// <param name="allowEnvironmentVariables">
        /// If true, allow to use environment variables in the .psd1 file
        /// </param>
        /// <param name="skipPathValidation">
        /// If true, caller guarantees the path is valid
        /// </param>
        /// <returns></returns>
        internal static Hashtable EvaluatePowerShellDataFile(
            string parameterName,
            string psDataFilePath,
            ExecutionContext context,
            IEnumerable <string> allowedCommands,
            IEnumerable <string> allowedVariables,
            bool allowEnvironmentVariables,
            bool skipPathValidation)
        {
            if (!skipPathValidation && string.IsNullOrEmpty(parameterName))
            {
                throw PSTraceSource.NewArgumentNullException("parameterName");
            }

            if (string.IsNullOrEmpty(psDataFilePath))
            {
                throw PSTraceSource.NewArgumentNullException("psDataFilePath");
            }

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

            string resolvedPath;

            if (skipPathValidation)
            {
                resolvedPath = psDataFilePath;
            }
            else
            {
                #region "ValidatePowerShellDataFilePath"

                bool isPathValid = true;

                // File extension needs to be .psd1
                string pathExt = Path.GetExtension(psDataFilePath);
                if (string.IsNullOrEmpty(pathExt) ||
                    !StringLiterals.PowerShellDataFileExtension.Equals(pathExt, StringComparison.OrdinalIgnoreCase))
                {
                    isPathValid = false;
                }

                ProviderInfo provider;
                var          resolvedPaths = context.SessionState.Path.GetResolvedProviderPathFromPSPath(psDataFilePath, out provider);

                // ConfigPath should be resolved as FileSystem provider
                if (provider == null || !Microsoft.PowerShell.Commands.FileSystemProvider.ProviderName.Equals(provider.Name, StringComparison.OrdinalIgnoreCase))
                {
                    isPathValid = false;
                }

                // ConfigPath should be resolved to a single path
                if (resolvedPaths.Count != 1)
                {
                    isPathValid = false;
                }

                if (!isPathValid)
                {
                    throw PSTraceSource.NewArgumentException(
                              parameterName,
                              ParserStrings.CannotResolvePowerShellDataFilePath,
                              psDataFilePath);
                }

                resolvedPath = resolvedPaths[0];

                #endregion "ValidatePowerShellDataFilePath"
            }

            #region "LoadAndEvaluatePowerShellDataFile"

            object evaluationResult;
            try
            {
                // Create the scriptInfo for the .psd1 file
                string      dataFileName       = Path.GetFileName(resolvedPath);
                var         dataFileScriptInfo = new ExternalScriptInfo(dataFileName, resolvedPath, context);
                ScriptBlock scriptBlock        = dataFileScriptInfo.ScriptBlock;

                // Validate the scriptblock
                scriptBlock.CheckRestrictedLanguage(allowedCommands, allowedVariables, allowEnvironmentVariables);

                // Evaluate the scriptblock
                object oldPsScriptRoot = context.GetVariableValue(SpecialVariables.PSScriptRootVarPath);
                try
                {
                    // Set the $PSScriptRoot before the evaluation
                    context.SetVariable(SpecialVariables.PSScriptRootVarPath, Path.GetDirectoryName(resolvedPath));
                    evaluationResult = PSObject.Base(scriptBlock.InvokeReturnAsIs());
                }
                finally
                {
                    context.SetVariable(SpecialVariables.PSScriptRootVarPath, oldPsScriptRoot);
                }
            }
            catch (RuntimeException ex)
            {
                throw PSTraceSource.NewInvalidOperationException(
                          ex,
                          ParserStrings.CannotLoadPowerShellDataFile,
                          psDataFilePath,
                          ex.Message);
            }

            var retResult = evaluationResult as Hashtable;
            if (retResult == null)
            {
                throw PSTraceSource.NewInvalidOperationException(
                          ParserStrings.InvalidPowerShellDataFile,
                          psDataFilePath);
            }

            #endregion "LoadAndEvaluatePowerShellDataFile"

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

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

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

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

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

                        i += 1;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            return(s_emptyReturnCollection);
        } // BindParameters
        internal object Transform(EngineIntrinsics engineIntrinsics, object inputData, bool bindingParameters, bool bindingScriptCmdlet)
        {
            if (_convertTypes == null)
            {
                return(inputData);
            }

            object result = inputData;

            try
            {
                for (int i = 0; i < _convertTypes.Length; i++)
                {
                    if (bindingParameters)
                    {
                        // We should not be doing a conversion here if [ref] is the last type.
                        // When [ref] appears in an argument list, it is used for checking only.
                        // No Conversion should be done.
                        if (_convertTypes[i].Equals(typeof(System.Management.Automation.PSReference)))
                        {
                            object   temp;
                            PSObject mshObject = result as PSObject;
                            if (mshObject != null)
                            {
                                temp = mshObject.BaseObject;
                            }
                            else
                            {
                                temp = result;
                            }

                            PSReference reference = temp as PSReference;

                            if (reference == null)
                            {
                                throw new PSInvalidCastException("InvalidCastExceptionReferenceTypeExpected", null,
                                                                 ExtendedTypeSystem.ReferenceTypeExpected);
                            }
                        }
                        else
                        {
                            object   temp;
                            PSObject mshObject = result as PSObject;
                            if (mshObject != null)
                            {
                                temp = mshObject.BaseObject;
                            }
                            else
                            {
                                temp = result;
                            }

                            // If a non-ref type is expected but currently passed in is a ref, do an implicit dereference.
                            PSReference reference = temp as PSReference;

                            if (reference != null)
                            {
                                result = reference.Value;
                            }

                            if (bindingScriptCmdlet && _convertTypes[i] == typeof(string))
                            {
                                // Don't allow conversion from array to string in script w/ cmdlet binding.  Allow
                                // the conversion for ordinary script parameter binding for V1 compatibility.
                                temp = PSObject.Base(result);
                                if (temp != null && temp.GetType().IsArray)
                                {
                                    throw new PSInvalidCastException("InvalidCastFromAnyTypeToString", null,
                                                                     ExtendedTypeSystem.InvalidCastCannotRetrieveString);
                                }
                            }
                        }
                    }

                    //BUGBUG
                    //NTRAID#Windows Out of Band Releases - 930116 - 03/14/06
                    //handling special case for boolean, switchparameter and Nullable<bool>
                    //These parameter types will not be converted if the incoming value types are not
                    //one of the accepted categories - $true/$false or numbers (0 or otherwise)
                    if (LanguagePrimitives.IsBoolOrSwitchParameterType(_convertTypes[i]))
                    {
                        CheckBoolValue(result, _convertTypes[i]);
                    }

                    if (bindingScriptCmdlet)
                    {
                        // Check for conversion to something like bool[] or ICollection<bool>, but only for cmdlet binding
                        // to stay compatible with V1.
                        ParameterCollectionTypeInformation collectionTypeInfo = new ParameterCollectionTypeInformation(_convertTypes[i]);
                        if (collectionTypeInfo.ParameterCollectionType != ParameterCollectionType.NotCollection &&
                            LanguagePrimitives.IsBoolOrSwitchParameterType(collectionTypeInfo.ElementType))
                        {
                            IList currentValueAsIList = ParameterBinderBase.GetIList(result);
                            if (currentValueAsIList != null)
                            {
                                foreach (object val in currentValueAsIList)
                                {
                                    CheckBoolValue(val, collectionTypeInfo.ElementType);
                                }
                            }
                            else
                            {
                                CheckBoolValue(result, collectionTypeInfo.ElementType);
                            }
                        }
                    }

                    result = LanguagePrimitives.ConvertTo(result, _convertTypes[i], CultureInfo.InvariantCulture);

                    // Do validation of invalid direct variable assignments which are allowed to
                    // be used for parameters.
                    //
                    // Note - this is duplicated in ExecutionContext.cs as parameter binding for script cmdlets can avoid this code path.
                    if ((!bindingScriptCmdlet) && (!bindingParameters))
                    {
                        // ActionPreference of Suspend is not supported as a preference variable. We can only block "Suspend"
                        // during variable assignment (here) - "Ignore" is blocked during variable retrieval.
                        if (_convertTypes[i] == typeof(ActionPreference))
                        {
                            ActionPreference resultPreference = (ActionPreference)result;

                            if (resultPreference == ActionPreference.Suspend)
                            {
                                throw new PSInvalidCastException("InvalidActionPreference", null, ErrorPackage.UnsupportedPreferenceVariable, resultPreference);
                            }
                        }
                    }
                }
            }
            catch (PSInvalidCastException e)
            {
                throw new ArgumentTransformationMetadataException(e.Message, e);
            }

            return(result);
        }
Exemple #6
0
        private static CommandProcessorBase AddCommand(PipelineProcessor pipe, CommandParameterInternal[] commandElements, CommandBaseAst commandBaseAst, CommandRedirection[] redirections, System.Management.Automation.ExecutionContext context)
        {
            object               parameterText;
            IScriptExtent        parameterExtent;
            CommandProcessorBase base2;
            InternalCommand      command;
            string               str3;
            HelpCategory         category;
            CommandAst           ast          = commandBaseAst as CommandAst;
            TokenKind            kind         = (ast != null) ? ast.InvocationOperator : TokenKind.Unknown;
            bool dotSource                    = kind == TokenKind.Dot;
            SessionStateInternal sessionState = null;
            int          index                = 0;
            PSModuleInfo info                 = PSObject.Base(commandElements[0].ArgumentValue) as PSModuleInfo;

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

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

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

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

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

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

                    case RedirectionStream.Error:
                        flag3 = true;
                        break;

                    case RedirectionStream.Warning:
                        flag4 = true;
                        break;

                    case RedirectionStream.Verbose:
                        flag5 = true;
                        break;

                    case RedirectionStream.Debug:
                        flag6 = true;
                        break;
                    }
                }
            }
            if (!flag3)
            {
                if (context.ShellFunctionErrorOutputPipe != null)
                {
                    base2.CommandRuntime.ErrorOutputPipe = context.ShellFunctionErrorOutputPipe;
                }
                else
                {
                    base2.CommandRuntime.ErrorOutputPipe.ExternalWriter = context.ExternalErrorOutput;
                }
            }
            if (!flag4 && (context.ExpressionWarningOutputPipe != null))
            {
                base2.CommandRuntime.WarningOutputPipe = context.ExpressionWarningOutputPipe;
                flag4 = true;
            }
            if (!flag5 && (context.ExpressionVerboseOutputPipe != null))
            {
                base2.CommandRuntime.VerboseOutputPipe = context.ExpressionVerboseOutputPipe;
                flag5 = true;
            }
            if (!flag6 && (context.ExpressionDebugOutputPipe != null))
            {
                base2.CommandRuntime.DebugOutputPipe = context.ExpressionDebugOutputPipe;
                flag6 = true;
            }
            if ((context.CurrentCommandProcessor != null) && (context.CurrentCommandProcessor.CommandRuntime != null))
            {
                if (!flag4 && (context.CurrentCommandProcessor.CommandRuntime.WarningOutputPipe != null))
                {
                    base2.CommandRuntime.WarningOutputPipe = context.CurrentCommandProcessor.CommandRuntime.WarningOutputPipe;
                }
                if (!flag5 && (context.CurrentCommandProcessor.CommandRuntime.VerboseOutputPipe != null))
                {
                    base2.CommandRuntime.VerboseOutputPipe = context.CurrentCommandProcessor.CommandRuntime.VerboseOutputPipe;
                }
                if (!flag6 && (context.CurrentCommandProcessor.CommandRuntime.DebugOutputPipe != null))
                {
                    base2.CommandRuntime.DebugOutputPipe = context.CurrentCommandProcessor.CommandRuntime.DebugOutputPipe;
                }
            }
            return(base2);
        }
Exemple #7
0
 internal void SetImplicitUsingParameters(object obj)
 {
     this._dictionary.ImplicitUsingParameters = PSObject.Base(obj) as IList;
 }
Exemple #8
0
        internal static ConversionRank GetArgumentConversionRank(
            object argument,
            Type parameterType)
        {
            ConversionRank conversionRank = LanguagePrimitives.GetConversionRank(Adapter.GetArgumentType(argument), parameterType);

            if (conversionRank == ConversionRank.None)
            {
                conversionRank = LanguagePrimitives.GetConversionRank(Adapter.GetArgumentType(PSObject.Base(argument)), parameterType);
            }
            return(conversionRank);
        }
        internal object Transform(EngineIntrinsics engineIntrinsics, object inputData, bool bindingParameters, bool bindingScriptCmdlet)
        {
            if (this._convertTypes == null)
            {
                return(inputData);
            }
            object obj2 = inputData;

            try
            {
                for (int i = 0; i < this._convertTypes.Length; i++)
                {
                    if (bindingParameters)
                    {
                        if (this._convertTypes[i].Equals(typeof(PSReference)))
                        {
                            object   baseObject;
                            PSObject obj4 = obj2 as PSObject;
                            if (obj4 != null)
                            {
                                baseObject = obj4.BaseObject;
                            }
                            else
                            {
                                baseObject = obj2;
                            }
                            if (!(baseObject is PSReference))
                            {
                                throw new PSInvalidCastException("InvalidCastExceptionReferenceTypeExpected", null, ExtendedTypeSystem.ReferenceTypeExpected, new object[0]);
                            }
                        }
                        else
                        {
                            object   obj5;
                            PSObject obj6 = obj2 as PSObject;
                            if (obj6 != null)
                            {
                                obj5 = obj6.BaseObject;
                            }
                            else
                            {
                                obj5 = obj2;
                            }
                            PSReference reference2 = obj5 as PSReference;
                            if (reference2 != null)
                            {
                                obj2 = reference2.Value;
                            }
                            if (bindingScriptCmdlet && (this._convertTypes[i] == typeof(string)))
                            {
                                obj5 = PSObject.Base(obj2);
                                if ((obj5 != null) && obj5.GetType().IsArray)
                                {
                                    throw new PSInvalidCastException("InvalidCastFromAnyTypeToString", null, ExtendedTypeSystem.InvalidCastCannotRetrieveString, new object[0]);
                                }
                            }
                        }
                    }
                    if (LanguagePrimitives.IsBoolOrSwitchParameterType(this._convertTypes[i]))
                    {
                        CheckBoolValue(obj2, this._convertTypes[i]);
                    }
                    if (bindingScriptCmdlet)
                    {
                        ParameterCollectionTypeInformation information = new ParameterCollectionTypeInformation(this._convertTypes[i]);
                        if ((information.ParameterCollectionType != ParameterCollectionType.NotCollection) && LanguagePrimitives.IsBoolOrSwitchParameterType(information.ElementType))
                        {
                            IList iList = ParameterBinderBase.GetIList(obj2);
                            if (iList != null)
                            {
                                foreach (object obj7 in iList)
                                {
                                    CheckBoolValue(obj7, information.ElementType);
                                }
                            }
                            else
                            {
                                CheckBoolValue(obj2, information.ElementType);
                            }
                        }
                    }
                    obj2 = LanguagePrimitives.ConvertTo(obj2, this._convertTypes[i], CultureInfo.InvariantCulture);
                }
            }
            catch (PSInvalidCastException exception)
            {
                throw new ArgumentTransformationMetadataException(exception.Message, exception);
            }
            return(obj2);
        }
Exemple #10
0
        internal static object ReplaceOperator(System.Management.Automation.ExecutionContext context, IScriptExtent errorPosition, object lval, object rval, bool ignoreCase)
        {
            string replacement = "";
            object obj2        = "";

            rval = PSObject.Base(rval);
            IList list = rval as IList;

            if (list != null)
            {
                if (list.Count > 2)
                {
                    throw InterpreterError.NewInterpreterException(rval, typeof(RuntimeException), errorPosition, "BadReplaceArgument", ParserStrings.BadReplaceArgument, new object[] { ignoreCase ? "-ireplace" : "-replace", list.Count });
                }
                if (list.Count > 0)
                {
                    obj2 = list[0];
                    if (list.Count > 1)
                    {
                        replacement = PSObject.ToStringParser(context, list[1]);
                    }
                }
            }
            else
            {
                obj2 = rval;
            }
            RegexOptions none = RegexOptions.None;

            if (ignoreCase)
            {
                none = RegexOptions.IgnoreCase;
            }
            Regex regex = obj2 as Regex;

            if (regex == null)
            {
                try
                {
                    regex = NewRegex(PSObject.ToStringParser(context, obj2), none);
                }
                catch (ArgumentException exception)
                {
                    throw InterpreterError.NewInterpreterExceptionWithInnerException(obj2, typeof(RuntimeException), null, "InvalidRegularExpression", ParserStrings.InvalidRegularExpression, exception, new object[] { obj2 });
                }
            }
            IEnumerator enumerator = LanguagePrimitives.GetEnumerator(lval);

            if (enumerator == null)
            {
                string input = ((lval == null) ? string.Empty : lval).ToString();
                return(regex.Replace(input, replacement));
            }
            ArrayList list2 = new ArrayList();

            while (MoveNext(context, errorPosition, enumerator))
            {
                string str3 = PSObject.ToStringParser(context, Current(errorPosition, enumerator));
                list2.Add(regex.Replace(str3, replacement));
            }
            return(list2.ToArray());
        }
Exemple #11
0
        internal static object MatchOperator(System.Management.Automation.ExecutionContext context, IScriptExtent errorPosition, object lval, object rval, bool notMatch, bool ignoreCase)
        {
            object       obj3;
            RegexOptions options = ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None;
            Regex        regex   = PSObject.Base(rval) as Regex;

            if (regex == null)
            {
                regex = NewRegex(PSObject.ToStringParser(context, rval), options);
            }
            IEnumerator targetObject = LanguagePrimitives.GetEnumerator(lval);

            if (targetObject == null)
            {
                string input = (lval == null) ? string.Empty : PSObject.ToStringParser(context, lval);
                Match  match = regex.Match(input);
                if (match.Success)
                {
                    GroupCollection groups = match.Groups;
                    if (groups.Count > 0)
                    {
                        Hashtable newValue = new Hashtable(StringComparer.CurrentCultureIgnoreCase);
                        foreach (string str2 in regex.GetGroupNames())
                        {
                            Group group = groups[str2];
                            if (group.Success)
                            {
                                int num;
                                if (int.TryParse(str2, out num))
                                {
                                    newValue.Add(num, group.ToString());
                                }
                                else
                                {
                                    newValue.Add(str2, group.ToString());
                                }
                            }
                        }
                        context.SetVariable(SpecialVariables.MatchesVarPath, newValue);
                    }
                }
                return(BoolToObject(match.Success ^ notMatch));
            }
            ArrayList list = new ArrayList();
            int       num2 = 0;

            try
            {
                while (targetObject.MoveNext())
                {
                    object current = targetObject.Current;
                    string str3    = (current == null) ? string.Empty : PSObject.ToStringParser(context, current);
                    if (regex.Match(str3).Success ^ notMatch)
                    {
                        list.Add(current);
                    }
                    if (num2++ > 0x3e8)
                    {
                        if ((context != null) && context.CurrentPipelineStopping)
                        {
                            throw new PipelineStoppedException();
                        }
                        num2 = 0;
                    }
                }
                obj3 = list.ToArray();
            }
            catch (RuntimeException)
            {
                throw;
            }
            catch (FlowControlException)
            {
                throw;
            }
            catch (ScriptCallDepthException)
            {
                throw;
            }
            catch (Exception exception)
            {
                CommandProcessorBase.CheckForSevereException(exception);
                throw InterpreterError.NewInterpreterExceptionWithInnerException(targetObject, typeof(RuntimeException), errorPosition, "BadEnumeration", ParserStrings.BadEnumeration, exception, new object[] { exception.Message });
            }
            return(obj3);
        }
Exemple #12
0
        internal static object CallMethod(IScriptExtent errorPosition, object target, string methodName, PSMethodInvocationConstraints invocationConstraints, object[] paramArray, bool callStatic, object valueToSet)
        {
            PSMethodInfo      staticCLRMember   = null;
            MethodInformation methodInformation = null;
            object            obj2 = null;
            PSObject          obj3 = null;
            Type   type;
            object obj4;

            if (LanguagePrimitives.IsNull(target))
            {
                throw InterpreterError.NewInterpreterException(methodName, typeof(RuntimeException), errorPosition, "InvokeMethodOnNull", ParserStrings.InvokeMethodOnNull, new object[0]);
            }
            obj2 = PSObject.Base(target);
            obj3 = PSObject.AsPSObject(target);
            CallsiteCacheEntryFlags none = CallsiteCacheEntryFlags.None;

            if (callStatic)
            {
                none |= CallsiteCacheEntryFlags.Static;
                type  = (Type)obj2;
            }
            else
            {
                type = obj2.GetType();
            }
            if (valueToSet != AutomationNull.Value)
            {
                none |= CallsiteCacheEntryFlags.ParameterizedSetter;
            }
            if (!obj3.isDeserialized)
            {
                methodInformation = Adapter.FindCachedMethod(type, methodName, invocationConstraints, paramArray, none);
            }
            if (methodInformation == null)
            {
                if (callStatic)
                {
                    staticCLRMember = PSObject.GetStaticCLRMember(target, methodName) as PSMethod;
                }
                else
                {
                    staticCLRMember = obj3.Members[methodName] as PSMethodInfo;
                }
                if (staticCLRMember == null)
                {
                    string fullName = null;
                    if (callStatic)
                    {
                        fullName = type.FullName;
                    }
                    else
                    {
                        fullName = GetTypeFullName(target);
                    }
                    if (valueToSet == AutomationNull.Value)
                    {
                        throw InterpreterError.NewInterpreterException(methodName, typeof(RuntimeException), errorPosition, "MethodNotFound", ParserStrings.MethodNotFound, new object[] { fullName, methodName });
                    }
                    throw InterpreterError.NewInterpreterException(methodName, typeof(RuntimeException), errorPosition, "ParameterizedPropertyAssignmentFailed", ParserStrings.ParameterizedPropertyAssignmentFailed, new object[] { fullName, methodName });
                }
            }
            try
            {
                if (methodInformation != null)
                {
                    object[] objArray;
                    PSObject.memberResolution.WriteLine("cache hit, Calling Method: {0}", new object[] { methodInformation.methodDefinition });
                    if (valueToSet != AutomationNull.Value)
                    {
                        DotNetAdapter.ParameterizedPropertyInvokeSet(methodName, obj2, valueToSet, new MethodInformation[] { methodInformation }, paramArray, false);
                        return(valueToSet);
                    }
                    MethodInformation[] methods = new MethodInformation[] { methodInformation };
                    Adapter.GetBestMethodAndArguments(methodName, methods, paramArray, out objArray);
                    return(DotNetAdapter.AuxiliaryMethodInvoke(obj2, objArray, methodInformation, paramArray));
                }
                if (valueToSet != AutomationNull.Value)
                {
                    PSParameterizedProperty property = staticCLRMember as PSParameterizedProperty;
                    if (property == null)
                    {
                        throw InterpreterError.NewInterpreterException(methodName, typeof(RuntimeException), errorPosition, "ParameterizedPropertyAssignmentFailed", ParserStrings.ParameterizedPropertyAssignmentFailed, new object[] { GetTypeFullName(target), methodName });
                    }
                    property.InvokeSet(valueToSet, paramArray);
                    return(valueToSet);
                }
                PSMethod method = staticCLRMember as PSMethod;
                if (method != null)
                {
                    return(method.Invoke(invocationConstraints, paramArray));
                }
                obj4 = staticCLRMember.Invoke(paramArray);
            }
            catch (MethodInvocationException exception)
            {
                if (exception.ErrorRecord.InvocationInfo == null)
                {
                    exception.ErrorRecord.SetInvocationInfo(new InvocationInfo(null, errorPosition));
                }
                throw;
            }
            catch (RuntimeException exception2)
            {
                if (exception2.ErrorRecord.InvocationInfo == null)
                {
                    exception2.ErrorRecord.SetInvocationInfo(new InvocationInfo(null, errorPosition));
                }
                throw;
            }
            catch (FlowControlException)
            {
                throw;
            }
            catch (ScriptCallDepthException)
            {
                throw;
            }
            catch (Exception exception3)
            {
                CommandProcessorBase.CheckForSevereException(exception3);
                throw InterpreterError.NewInterpreterExceptionByMessage(typeof(RuntimeException), errorPosition, exception3.Message, "MethodInvocationException", exception3);
            }
            return(obj4);
        }
Exemple #13
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);
        }
Exemple #14
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);
        }
 private string VerifyKey(object key)
 {
     key = PSObject.Base(key);
     return(key is string str ? str : throw new ArgumentException(ResourceManagerCache.FormatResourceString("Serialization", "PrimitiveHashtableInvalidKey", (object)key.GetType().FullName)));
 }