Beispiel #1
0
        private object DoGetValue(string str, object index, ExecutionContext context)
        {
            IEnumerator enumerator = LanguagePrimitives.GetEnumerator(index);

            if (enumerator != null)
            {
                ArrayList arrayList = new ArrayList();
                while (ParserOps.MoveNext(context, this.NodeToken, enumerator))
                {
                    int index1 = ParserOps.FixNum(ParserOps.Current(this.NodeToken, enumerator), this.NodeToken);
                    if (index1 < 0)
                    {
                        index1 += str.Length;
                    }
                    try
                    {
                        arrayList.Add((object)str[index1]);
                    }
                    catch (IndexOutOfRangeException ex)
                    {
                    }
                }
                return((object)arrayList.ToArray());
            }
            int index2 = ParserOps.FixNum(index, this.NodeToken);

            if (index2 < 0)
            {
                index2 += str.Length;
            }
            try
            {
                return((object)str[index2]);
            }
            catch (IndexOutOfRangeException ex)
            {
                return((object)null);
            }
        }
Beispiel #2
0
        private object GetItemPropertyValue(object obj, object index, ExecutionContext context)
        {
            IEnumerator enumerator = LanguagePrimitives.GetEnumerator(index);

            if (enumerator != null)
            {
                ArrayList arrayList = new ArrayList();
                while (ParserOps.MoveNext(context, this.NodeToken, enumerator))
                {
                    try
                    {
                        object obj1 = this.GetItem(obj, enumerator.Current);
                        arrayList.Add(obj1);
                    }
                    catch (Exception ex)
                    {
                        CommandProcessorBase.CheckForSevereException(ex);
                        if (this.IsMethodNotFoundException(ex))
                        {
                            throw InterpreterError.NewInterpreterExceptionWithInnerException(index, typeof(RuntimeException), this.NodeToken, "CannotIndex", ex, (object)obj.GetType().FullName);
                        }
                    }
                }
                return((object)arrayList.ToArray());
            }
            try
            {
                return(this.GetItem(obj, index));
            }
            catch (Exception ex)
            {
                CommandProcessorBase.CheckForSevereException(ex);
                if (this.IsMethodNotFoundException(ex))
                {
                    throw InterpreterError.NewInterpreterExceptionWithInnerException(index, typeof(RuntimeException), this.NodeToken, "CannotIndex", ex, (object)obj.GetType().FullName);
                }
                return((object)null);
            }
        }
        /// <summary>
        /// Stringize a non-IEnum argument to a native command, adding quotes
        /// and trailing spaces as appropriate. An array gets added as multiple arguments
        /// each of which will be stringized.
        /// </summary>
        /// <param name="context">Execution context instance.</param>
        /// <param name="parameter">The parameter associated with the operation.</param>
        /// <param name="obj">The object to append.</param>
        /// <param name="argArrayAst">If the argument was an array literal, the Ast, otherwise null.</param>
        /// <param name="sawVerbatimArgumentMarker">True if the argument occurs after --%.</param>
        /// <param name="stringConstantType">Bare, SingleQuoted, or DoubleQuoted.</param>
        private void AppendOneNativeArgument(ExecutionContext context, CommandParameterInternal parameter, object obj, ArrayLiteralAst argArrayAst, bool sawVerbatimArgumentMarker, StringConstantType stringConstantType)
        {
            IEnumerator list = LanguagePrimitives.GetEnumerator(obj);

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

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

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

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

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

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

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

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

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

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

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

                                break;
                            }
                            else
                            {
                                PossiblyGlobArg(arg, parameter, stringConstantType);
                            }
                        }
                    }
                }
                else if (UseArgumentList && currentObj != null)
                {
                    // add empty strings to arglist, but not nulls
                    AddToArgumentList(parameter, arg);
                }
            }while (list != null);
        }
Beispiel #4
0
        private void ConvertCommand(CommandAst commandAst, bool isTrustedInput)
        {
            // First need command name.
            var commandName = GetCommandName(commandAst.CommandElements[0], isTrustedInput);

            var command = new Command(commandName, isScript: false, useLocalScope: _createLocalScope);

            // Handle redirections, if any (there can really be just 0 or 1).
            if (commandAst.Redirections.Count > 0)
            {
                Diagnostics.Assert(commandAst.Redirections.Count == 1, "only 1 kind of redirection is supported");
                Diagnostics.Assert(commandAst.Redirections[0] is MergingRedirectionAst, "unexpected redirection type");

                PipelineResultTypes toType = PipelineResultTypes.Output;
                PipelineResultTypes fromType;
                switch (commandAst.Redirections[0].FromStream)
                {
                case RedirectionStream.Error:
                    fromType = PipelineResultTypes.Error;
                    break;

                case RedirectionStream.Warning:
                    fromType = PipelineResultTypes.Warning;
                    break;

                case RedirectionStream.Verbose:
                    fromType = PipelineResultTypes.Verbose;
                    break;

                case RedirectionStream.Debug:
                    fromType = PipelineResultTypes.Debug;
                    break;

                case RedirectionStream.Information:
                    fromType = PipelineResultTypes.Information;
                    break;

                case RedirectionStream.All:
                    fromType = PipelineResultTypes.All;
                    break;

                default:
                    // Default to Error->Output to be compatible with V2.
                    fromType = PipelineResultTypes.Error;
                    break;
                }

                command.MergeMyResults(fromType, toType);
            }

            _powershell.AddCommand(command);

            // Now the parameters and arguments.
            foreach (var ast in commandAst.CommandElements.Skip(1))
            {
                var exprAst = ast as ExpressionAst;
                if (exprAst != null)
                {
                    VariableExpressionAst variableAst = null;

                    var usingExprAst = ast as UsingExpressionAst;
                    if (usingExprAst != null)
                    {
                        string usingAstKey = PsUtils.GetUsingExpressionKey(usingExprAst);
                        object usingValue  = _usingValueMap[usingAstKey];
                        variableAst = usingExprAst.SubExpression as VariableExpressionAst;
                        if (variableAst != null && variableAst.Splatted)
                        {
                            // Support the splatting of a dictionary
                            var parameters = usingValue as System.Collections.IDictionary;
                            if (parameters != null)
                            {
                                _powershell.AddParameters(parameters);
                            }
                            else
                            {
                                // Support the splatting of an array
                                var arguments = usingValue as System.Collections.IEnumerable;
                                if (arguments != null)
                                {
                                    foreach (object argument in arguments)
                                    {
                                        _powershell.AddArgument(argument);
                                    }
                                }
                                else
                                {
                                    // Splat the object directly.
                                    _powershell.AddArgument(usingValue);
                                }
                            }
                        }
                        else
                        {
                            _powershell.AddArgument(usingValue);
                        }

                        continue;
                    }

                    variableAst = ast as VariableExpressionAst;
                    if (variableAst != null && variableAst.Splatted)
                    {
                        GetSplattedVariable(variableAst);
                    }
                    else
                    {
                        var    constantExprAst = ast as ConstantExpressionAst;
                        object argument;
                        if (constantExprAst != null && LanguagePrimitives.IsNumeric(LanguagePrimitives.GetTypeCode(constantExprAst.StaticType)))
                        {
                            var commandArgumentText = constantExprAst.Extent.Text;
                            argument = constantExprAst.Value;
                            if (!commandArgumentText.Equals(constantExprAst.Value.ToString(), StringComparison.Ordinal))
                            {
                                // The wrapped number will actually return a PSObject which could end holding a reference to
                                // a typetable, making the object runspace specific.  We should find a better way to avoid
                                // any possibility of sharing problems, though this is unlikely to cause problems.
                                argument = ParserOps.WrappedNumber(argument, commandArgumentText);
                            }
                        }
                        else
                        {
                            if (!isTrustedInput)
                            {
                                try
                                {
                                    argument = GetSafeValueVisitor.GetSafeValue(exprAst, _context, GetSafeValueVisitor.SafeValueContext.GetPowerShell);
                                }
                                catch (System.Exception)
                                {
                                    throw new ScriptBlockToPowerShellNotSupportedException(
                                              "CantConvertWithDynamicExpression",
                                              null,
                                              AutomationExceptions.CantConvertWithDynamicExpression,
                                              exprAst.Extent.Text);
                                }
                            }
                            else
                            {
                                argument = GetExpressionValue(exprAst, isTrustedInput);
                            }
                        }

                        _powershell.AddArgument(argument);
                    }
                }
                else
                {
                    AddParameter((CommandParameterAst)ast, isTrustedInput);
                }
            }
        }
Beispiel #5
0
        /// <summary>
        /// Stringize a non-IEnum argument to a native command, adding quotes
        /// and trailing spaces as appropriate. An array gets added as multiple arguments
        /// each of which will be stringized.
        /// </summary>
        /// <param name="context">Execution context instance</param>
        /// <param name="obj">The object to append</param>
        /// <param name="argArrayAst">If the argument was an array literal, the Ast, otherwise null</param>
        /// <param name="sawVerbatimArgumentMarker">true if the argument occurs after --%</param>
        /// <param name="usedQuotes">True if the argument was a quoted string (single or double)</param>
        private void appendOneNativeArgument(ExecutionContext context, object obj, ArrayLiteralAst argArrayAst, bool sawVerbatimArgumentMarker, bool usedQuotes)
        {
            IEnumerator list = LanguagePrimitives.GetEnumerator(obj);

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

            int    currentElement = -1;
            string separator      = "";

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

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

                if (!String.IsNullOrEmpty(arg))
                {
                    _arguments.Append(separator);

                    if (sawVerbatimArgumentMarker)
                    {
                        arg = Environment.ExpandEnvironmentVariables(arg);
                        _arguments.Append(arg);
                    }
                    else
                    {
                        // We need to add quotes if the argument has unquoted spaces.  The
                        // quotes could appear anywhere inside the string, not just at the start,
                        // e.g.
                        //    $a = 'a"b c"d'
                        //    echoargs $a 'a"b c"d' a"b c"d
                        //
                        // The above should see 3 identical arguments in argv (the command line will
                        // actually have quotes in different places, but the Win32 command line=>argv parser
                        // erases those differences.
                        //
                        // We need to check quotes that the win32 argument parser checks which is currently
                        // just the normal double quotes, no other special quotes.  Also note that mismatched
                        // quotes are supported
                        if (NeedQuotes(arg))
                        {
                            _arguments.Append('"');
                            // need to escape all trailing backslashes so the native command receives it correctly
                            // according to http://www.daviddeley.com/autohotkey/parameters/parameters.htm#WINCRULESDOC
                            _arguments.Append(arg);
                            for (int i = arg.Length - 1; i >= 0 && arg[i] == '\\'; i--)
                            {
                                _arguments.Append('\\');
                            }
                            _arguments.Append('"');
                        }
                        else
                        {
                            PossiblyGlobArg(arg, usedQuotes);
                        }
                    }
                }
            } while (list != null);
        }
Beispiel #6
0
        /// <summary>
        /// Stringize a non-IEnum argument to a native command, adding quotes
        /// and trailing spaces as appropriate. An array gets added as multiple arguments
        /// each of which will be stringized.
        /// </summary>
        /// <param name="context">Execution context instance</param>
        /// <param name="obj">The object to append</param>
        /// <param name="separator">A space or comma used when obj is enumerable</param>
        /// <param name="sawVerbatimArgumentMarker">true if the argument occurs after --%</param>
        private void appendOneNativeArgument(ExecutionContext context, object obj, char separator, bool sawVerbatimArgumentMarker)
        {
            IEnumerator list          = LanguagePrimitives.GetEnumerator(obj);
            bool        needSeparator = false;

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

                if (!String.IsNullOrEmpty(arg))
                {
                    if (needSeparator)
                    {
                        _arguments.Append(separator);
                    }
                    else
                    {
                        needSeparator = true;
                    }

                    if (sawVerbatimArgumentMarker)
                    {
                        arg = Environment.ExpandEnvironmentVariables(arg);
                        _arguments.Append(arg);
                    }
                    else
                    {
                        // We need to add quotes if the argument has unquoted spaces.  The
                        // quotes could appear anywhere inside the string, not just at the start,
                        // e.g.
                        //    $a = 'a"b c"d'
                        //    echoargs $a 'a"b c"d' a"b c"d
                        //
                        // The above should see 3 identical arguments in argv (the command line will
                        // actually have quotes in different places, but the Win32 command line=>argv parser
                        // erases those differences.
                        //
                        // We need to check quotes that the win32 argument parser checks which is currently
                        // just the normal double quotes, no other special quotes.  Also note that mismatched
                        // quotes are supported
                        if (NeedQuotes(arg))
                        {
                            _arguments.Append('"');
                            _arguments.Append(arg);
                            _arguments.Append('"');
                        }
                        else
                        {
#if UNIX
                            // On UNIX systems, we expand arguments containing wildcard expressions against
                            // the file system just like bash, etc.
                            if (System.Management.Automation.WildcardPattern.ContainsWildcardCharacters(arg))
                            {
                                // See if the current working directory is a filesystem provider location
                                // We won't do the expansion if it isn't since native commands can only access the file system.
                                var cwdinfo = Context.EngineSessionState.CurrentLocation;

                                // If it's a filesystem location then expand the wildcards
                                if (string.Equals(cwdinfo.Provider.Name, Microsoft.PowerShell.Commands.FileSystemProvider.ProviderName,
                                                  StringComparison.OrdinalIgnoreCase))
                                {
                                    bool normalizePath = true;
                                    // On UNIX, paths starting with ~ are not normalized
                                    if (arg.Length > 0 && arg[0] == '~')
                                    {
                                        normalizePath = false;
                                    }

                                    // See if there are any matching paths otherwise just add the pattern as the argument
                                    var paths = Context.EngineSessionState.InvokeProvider.ChildItem.Get(arg, false);
                                    if (paths.Count > 0)
                                    {
                                        bool first = true;
                                        foreach (var path in paths)
                                        {
                                            object pbo = path.BaseObject;
                                            if (!first)
                                            {
                                                _arguments.Append(" ");
                                            }
                                            else
                                            {
                                                if (!(pbo is System.IO.FileSystemInfo))
                                                {
                                                    // If the object is not a filesystem object, then just append
                                                    // the pattern unchanged
                                                    _arguments.Append(arg);
                                                    break;
                                                }
                                                first = false;
                                            }
                                            var expandedPath = (pbo as System.IO.FileSystemInfo).FullName;
                                            if (normalizePath)
                                            {
                                                expandedPath = Context.SessionState.Path.NormalizeRelativePath(expandedPath, cwdinfo.ProviderPath);
                                            }
                                            // If the path contains spaces, then add quotes around it.
                                            if (NeedQuotes(expandedPath))
                                            {
                                                _arguments.Append("\"");
                                                _arguments.Append(expandedPath);
                                                _arguments.Append("\"");
                                            }
                                            else
                                            {
                                                _arguments.Append(expandedPath);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        _arguments.Append(arg);
                                    }
                                }
                                else
                                {
                                    _arguments.Append(arg);
                                }
                            }
                            else
                            {
                                // Even if there are no wildcards, we still need to possibly
                                // expand ~ into the filesystem provider home directory path
                                ProviderInfo fileSystemProvider = Context.EngineSessionState.GetSingleProvider(
                                    Microsoft.PowerShell.Commands.FileSystemProvider.ProviderName);
                                string home = fileSystemProvider.Home;
                                if (string.Equals(arg, "~"))
                                {
                                    _arguments.Append(home);
                                }
                                else if (arg.StartsWith("~/", StringComparison.OrdinalIgnoreCase))
                                {
                                    var replacementString = home + arg.Substring(1);
                                    _arguments.Append(replacementString);
                                }
                                else
                                {
                                    _arguments.Append(arg);
                                }
                            }
#else
                            _arguments.Append(arg);
#endif
                        }
                    }
                }
            } while (list != null);
        }
Beispiel #7
0
 private object GetItem(object target, object index) => ParserOps.CallMethod(this.NodeToken, target, "get_Item", new object[1]
 {
     index
 }, false, (object)AutomationNull.Value);
        /// <summary>
        /// Stringize a non-IEnum argument to a native command, adding quotes
        /// and trailing spaces as appropriate. An array gets added as multiple arguments
        /// each of which will be stringized.
        /// </summary>
        /// <param name="context">Execution context instance</param>
        /// <param name="obj">The object to append</param>
        /// <param name="separator">A space or comma used when obj is enumerable</param>
        /// <param name="sawVerbatimArgumentMarker">true if the argument occurs after --%</param>
        private void appendOneNativeArgument(ExecutionContext context, object obj, char separator, bool sawVerbatimArgumentMarker)
        {
            IEnumerator list          = LanguagePrimitives.GetEnumerator(obj);
            bool        needSeparator = false;

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

                if (!String.IsNullOrEmpty(arg))
                {
                    if (needSeparator)
                    {
                        _arguments.Append(separator);
                    }
                    else
                    {
                        needSeparator = true;
                    }

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

                        bool needQuotes = false;
                        int  quoteCount = 0;
                        for (int i = 0; i < arg.Length; i++)
                        {
                            if (arg[i] == '"')
                            {
                                quoteCount += 1;
                            }
                            else if (char.IsWhiteSpace(arg[i]) && (quoteCount % 2 == 0))
                            {
                                needQuotes = true;
                            }
                        }

                        if (needQuotes)
                        {
                            _arguments.Append('"');
                            _arguments.Append(arg);
                            _arguments.Append('"');
                        }
                        else
                        {
                            _arguments.Append(arg);
                        }
                    }
                }
            } while (list != null);
        }
Beispiel #9
0
        private void ConvertCommand(CommandAst commandAst)
        {
            Command command = new Command(this.GetCommandName(commandAst.CommandElements[0]), false, this._createLocalScope);

            if (commandAst.Redirections.Count > 0)
            {
                PipelineResultTypes all;
                PipelineResultTypes output = PipelineResultTypes.Output;
                switch (commandAst.Redirections[0].FromStream)
                {
                case RedirectionStream.All:
                    all = PipelineResultTypes.All;
                    break;

                case RedirectionStream.Error:
                    all = PipelineResultTypes.Error;
                    break;

                case RedirectionStream.Warning:
                    all = PipelineResultTypes.Warning;
                    break;

                case RedirectionStream.Verbose:
                    all = PipelineResultTypes.Verbose;
                    break;

                case RedirectionStream.Debug:
                    all = PipelineResultTypes.Debug;
                    break;

                default:
                    all = PipelineResultTypes.Error;
                    break;
                }
                command.MergeMyResults(all, output);
            }
            this._powershell.AddCommand(command);
            foreach (CommandElementAst ast in commandAst.CommandElements.Skip <CommandElementAst>(1))
            {
                ExpressionAst exprAst = ast as ExpressionAst;
                if (exprAst != null)
                {
                    VariableExpressionAst variableAst = null;
                    UsingExpressionAst    ast4        = ast as UsingExpressionAst;
                    if (ast4 != null)
                    {
                        variableAst = ast4.SubExpression as VariableExpressionAst;
                        if ((variableAst != null) && variableAst.Splatted)
                        {
                            IDictionary parameters = this._usingValues[ast4.RuntimeUsingIndex] as IDictionary;
                            if (parameters != null)
                            {
                                this._powershell.AddParameters(parameters);
                            }
                            else
                            {
                                IEnumerable enumerable = this._usingValues[ast4.RuntimeUsingIndex] as IEnumerable;
                                if (enumerable != null)
                                {
                                    foreach (object obj2 in enumerable)
                                    {
                                        this._powershell.AddArgument(obj2);
                                    }
                                }
                                else
                                {
                                    this._powershell.AddArgument(this._usingValues[ast4.RuntimeUsingIndex]);
                                }
                            }
                        }
                        else
                        {
                            this._powershell.AddArgument(this._usingValues[ast4.RuntimeUsingIndex]);
                        }
                    }
                    else
                    {
                        variableAst = ast as VariableExpressionAst;
                        if ((variableAst != null) && variableAst.Splatted)
                        {
                            this.GetSplattedVariable(variableAst);
                        }
                        else
                        {
                            object expressionValue;
                            ConstantExpressionAst ast5 = ast as ConstantExpressionAst;
                            if ((ast5 != null) && LanguagePrimitives.IsNumeric(LanguagePrimitives.GetTypeCode(ast5.StaticType)))
                            {
                                string text = ast5.Extent.Text;
                                expressionValue = ast5.Value;
                                if (!text.Equals(ast5.Value.ToString(), StringComparison.Ordinal))
                                {
                                    expressionValue = ParserOps.WrappedNumber(expressionValue, text);
                                }
                            }
                            else
                            {
                                expressionValue = this.GetExpressionValue(exprAst);
                            }
                            this._powershell.AddArgument(expressionValue);
                        }
                    }
                }
                else
                {
                    this.AddParameter((CommandParameterAst)ast);
                }
            }
        }
Beispiel #10
0
        internal static object AddFakeEnumerable(NonEnumerableObjectEnumerator fakeEnumerator, object rhs)
        {
            NonEnumerableObjectEnumerator enumerator = rhs as NonEnumerableObjectEnumerator;

            return(ParserOps.ImplicitOp(fakeEnumerator.GetNonEnumerableObject(), (enumerator != null) ? enumerator.GetNonEnumerableObject() : rhs, "op_Addition", null, "+"));
        }
Beispiel #11
0
 internal object InvokeMethod(object target, object[] arguments, object value) => ParserOps.CallMethod(this.NodeToken, target, this.NodeToken.TokenText, arguments, this._isStatic, value);
Beispiel #12
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);
        }