private static int ComputeDefaultAlignment(PSObject so, PSPropertyExpression ex)
        {
            List <PSPropertyExpressionResult> rList = ex.GetValues(so);

            if ((rList.Count == 0) || (rList[0].Exception != null))
            {
                return(TextAlignment.Left);
            }

            object val = rList[0].Result;

            if (val == null)
            {
                return(TextAlignment.Left);
            }

            PSObject soVal     = PSObject.AsPSObject(val);
            var      typeNames = soVal.InternalTypeNames;

            if (string.Equals(PSObjectHelper.PSObjectIsOfExactType(typeNames),
                              "System.String", StringComparison.OrdinalIgnoreCase))
            {
                return(TextAlignment.Left);
            }

            if (DefaultScalarTypes.IsTypeInList(typeNames))
            {
                return(TextAlignment.Right);
            }

            return(TextAlignment.Left);
        }
Пример #2
0
        private static PSPropertyExpression GetDefaultNameExpression(PSObject so)
        {
            PSPropertyExpression retVal = GetDefaultNameExpression(so.PSStandardMembers) ??
                                          GetDefaultNameExpression(MaskDeserializedAndGetStandardMembers(so));

            return(retVal);
        }
Пример #3
0
        protected FormatPropertyField GenerateFormatPropertyField(List <FormatToken> formatTokenList, PSObject so, int enumerationLimit, out PSPropertyExpressionResult result)
        {
            result = null;
            FormatPropertyField fpf = new FormatPropertyField();

            if (formatTokenList.Count != 0)
            {
                FormatToken        token = formatTokenList[0];
                FieldPropertyToken fpt   = token as FieldPropertyToken;
                if (fpt != null)
                {
                    PSPropertyExpression ex = this.expressionFactory.CreateFromExpressionToken(fpt.expression, this.dataBaseInfo.view.loadingInfo);
                    fpf.propertyValue = this.GetExpressionDisplayValue(so, enumerationLimit, ex, fpt.fieldFormattingDirective, out result);
                }
                else
                {
                    TextToken tt = token as TextToken;
                    if (tt != null)
                    {
                        fpf.propertyValue = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(tt);
                    }
                }
            }
            else
            {
                fpf.propertyValue = string.Empty;
            }

            return(fpf);
        }
Пример #4
0
        public DataTableRow CastObjectToDataTableRow(PSObject ps, List <DataTableColumn> dataColumns, int objectIndex)
        {
            Dictionary <string, IValue> valuePairs = new Dictionary <string, IValue>();

            foreach (var dataColumn in dataColumns)
            {
                var expression = new PSPropertyExpression(ScriptBlock.Create(dataColumn.PropertyScriptAccessor));

                var result = expression.GetValues(ps).FirstOrDefault().Result;

                var stringValue = result?.ToString() ?? String.Empty;

                var isDecimal = decimal.TryParse(stringValue, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var decimalValue);

                if (isDecimal)
                {
                    valuePairs[dataColumn.ToString()] = new DecimalValue {
                        DisplayValue = stringValue, SortValue = decimalValue
                    };
                }
                else
                {
                    valuePairs[dataColumn.ToString()] = new StringValue {
                        DisplayValue = stringValue
                    };
                }
            }

            return(new DataTableRow(valuePairs, objectIndex));
        }
Пример #5
0
        private int MatchTypeIndex(string typeName, PSObject currentObject, PSPropertyExpression ex)
        {
            if (string.IsNullOrEmpty(typeName))
            {
                return(BestMatchIndexUndefined);
            }
            int k = 0;

            foreach (string name in _typeNameHierarchy)
            {
                if (string.Equals(name, typeName, StringComparison.OrdinalIgnoreCase) &&
                    MatchCondition(currentObject, ex))
                {
                    return(k);
                }

                if (k == 0 && !_useInheritance)
                {
                    break;
                }
                k++;
            }

            return(BestMatchIndexUndefined);
        }
Пример #6
0
        internal static List <MshResolvedExpressionParameterAssociation> ExpandAll(PSObject target)
        {
            List <string> adaptedProperties  = GetPropertyNamesFromView(target, PSMemberViewTypes.Adapted);
            List <string> baseProperties     = GetPropertyNamesFromView(target, PSMemberViewTypes.Base);
            List <string> extendedProperties = GetPropertyNamesFromView(target, PSMemberViewTypes.Extended);

            var displayedProperties = adaptedProperties.Count != 0 ? adaptedProperties : baseProperties;

            displayedProperties.AddRange(extendedProperties);

            Dictionary <string, object> duplicatesFinder            = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);
            List <MshResolvedExpressionParameterAssociation> retVal = new List <MshResolvedExpressionParameterAssociation>();

            foreach (string property in displayedProperties)
            {
                if (!duplicatesFinder.ContainsKey(property))
                {
                    duplicatesFinder.Add(property, null);
                    PSPropertyExpression expr = new PSPropertyExpression(property, true);
                    retVal.Add(new MshResolvedExpressionParameterAssociation(null, expr));
                }
            }

            return(retVal);
        }
Пример #7
0
        /// <summary>
        /// helper to retrieve the value of an PSPropertyExpression and to format it
        /// </summary>
        /// <param name="so">shell object to process</param>
        /// <param name="enumerationLimit">limit on IEnumerable enumeration</param>
        /// <param name="ex">expression to use for retrieval</param>
        /// <param name="directive">format directive to use for formatting</param>
        /// <param name="formatErrorObject"></param>
        /// <param name="expressionFactory">expression factory to create PSPropertyExpression</param>
        /// <param name="result"> not null if an error condition arose</param>
        /// <returns>formatted string</returns>
        internal static string GetExpressionDisplayValue(
            PSObject so,
            int enumerationLimit,
            PSPropertyExpression ex,
            FieldFormattingDirective directive,
            StringFormatError formatErrorObject,
            PSPropertyExpressionFactory expressionFactory,
            out PSPropertyExpressionResult result)
        {
            result = null;
            List <PSPropertyExpressionResult> resList = ex.GetValues(so);

            if (resList.Count == 0)
            {
                return(string.Empty);
            }

            result = resList[0];
            if (result.Exception != null)
            {
                return(string.Empty);
            }

            return(PSObjectHelper.FormatField(directive, result.Result, enumerationLimit, formatErrorObject, expressionFactory));
        }
Пример #8
0
        // Expand a list of (possibly wildcarded) expressions into resolved expressions that
        // match property names on the incoming objects.
        private static void ExpandExpressions(PSObject inputObject, List <MshParameter> UnexpandedParametersWithWildCardPattern, List <MshParameter> expandedParameterList)
        {
            if (UnexpandedParametersWithWildCardPattern != null)
            {
                foreach (MshParameter unexpandedParameter in UnexpandedParametersWithWildCardPattern)
                {
                    PSPropertyExpression ex = (PSPropertyExpression)unexpandedParameter.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey);

                    SortedDictionary <string, PSPropertyExpression> expandedPropertyNames = new(StringComparer.OrdinalIgnoreCase);
                    if (inputObject == null)
                    {
                        continue;
                    }

                    foreach (PSPropertyExpression resolvedName in ex.ResolveNames(PSObject.AsPSObject(inputObject)))
                    {
                        expandedPropertyNames[resolvedName.ToString()] = resolvedName;
                    }

                    foreach (PSPropertyExpression expandedExpression in expandedPropertyNames.Values)
                    {
                        MshParameter expandedParameter = new();
                        expandedParameter.hash = (Hashtable)unexpandedParameter.hash.Clone();
                        expandedParameter.hash[FormatParameterDefinitionKeys.ExpressionEntryKey] = expandedExpression;

                        expandedParameterList.Add(expandedParameter);
                    }
                }
            }
        }
Пример #9
0
        /// <summary>
        /// Resolve all wildcards in user input Property into resolvedNameMshParameters.
        /// </summary>
        private void InitializeResolvedNameMshParameters()
        {
            // temp list of properties with wildcards resolved
            var resolvedNameProperty = new List <object>();

            foreach (MshParameter p in _propertyMshParameterList)
            {
                string label     = p.GetEntry(ConvertHTMLParameterDefinitionKeys.LabelEntryKey) as string;
                string alignment = p.GetEntry(ConvertHTMLParameterDefinitionKeys.AlignmentEntryKey) as string;

                // Accept the width both as a string and as an int.
                string width;
                int?   widthNum = p.GetEntry(ConvertHTMLParameterDefinitionKeys.WidthEntryKey) as int?;
                width = widthNum != null?widthNum.Value.ToString() : p.GetEntry(ConvertHTMLParameterDefinitionKeys.WidthEntryKey) as string;

                PSPropertyExpression        ex            = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as PSPropertyExpression;
                List <PSPropertyExpression> resolvedNames = ex.ResolveNames(_inputObject);
                foreach (PSPropertyExpression resolvedName in resolvedNames)
                {
                    Hashtable ht = CreateAuxPropertyHT(label, alignment, width);
                    if (resolvedName.Script != null)
                    {
                        // The argument is a calculated property whose value is calculated by a script block.
                        ht.Add(FormatParameterDefinitionKeys.ExpressionEntryKey, resolvedName.Script);
                    }
                    else
                    {
                        ht.Add(FormatParameterDefinitionKeys.ExpressionEntryKey, resolvedName.ToString());
                    }
                    resolvedNameProperty.Add(ht);
                }
            }

            _resolvedNameMshParameters = ProcessParameter(resolvedNameProperty.ToArray());
        }
Пример #10
0
        private ListViewEntry GenerateListViewEntryFromDataBaseInfo(PSObject so, int enumerationLimit)
        {
            ListViewEntry lve = new ListViewEntry();

            ListControlEntryDefinition activeListControlEntryDefinition =
                GetActiveListControlEntryDefinition(_listBody, so);

            foreach (ListControlItemDefinition listItem in activeListControlEntryDefinition.itemDefinitionList)
            {
                if (!EvaluateDisplayCondition(so, listItem.conditionToken))
                {
                    continue;
                }

                ListViewField lvf = new ListViewField();
                PSPropertyExpressionResult result;
                lvf.formatPropertyField = GenerateFormatPropertyField(listItem.formatTokenList, so, enumerationLimit, out result);

                // we need now to provide a label
                if (listItem.label != null)
                {
                    // if the directive provides one, we use it
                    lvf.label = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(listItem.label);
                }
                else if (result != null)
                {
                    // if we got a valid match from the Mshexpression, use it as a label
                    lvf.label = result.ResolvedExpression.ToString();
                }
                else
                {
                    // we did fail getting a result (i.e. property does not exist on the object)

                    // we try to fall back and see if we have an un-resolved PSPropertyExpression
                    FormatToken        token = listItem.formatTokenList[0];
                    FieldPropertyToken fpt   = token as FieldPropertyToken;
                    if (fpt != null)
                    {
                        PSPropertyExpression ex = this.expressionFactory.CreateFromExpressionToken(fpt.expression, this.dataBaseInfo.view.loadingInfo);

                        // use the un-resolved PSPropertyExpression string as a label
                        lvf.label = ex.ToString();
                    }
                    else
                    {
                        TextToken tt = token as TextToken;
                        if (tt != null)
                        {
                            // we had a text token, use it as a label (last resort...)
                            lvf.label = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(tt);
                        }
                    }
                }

                lve.listViewFieldList.Add(lvf);
            }

            return(lve);
        }
Пример #11
0
        internal MshResolvedExpressionParameterAssociation(MshParameter parameter, PSPropertyExpression expression)
        {
            if (expression == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(expression));
            }

            OriginatingParameter = parameter;
            ResolvedExpression   = expression;
        }
        private bool MatchCondition(PSObject currentObject, PSPropertyExpression ex)
        {
            if (ex == null)
            {
                return(true);
            }

            PSPropertyExpressionResult expressionResult;
            bool retVal = DisplayCondition.Evaluate(currentObject, ex, out expressionResult);

            return(retVal);
        }
Пример #13
0
        /// <summary>
        /// Try to match the expression against the array of wildcard patterns.
        /// The first match shortcircuits the search.
        /// </summary>
        /// <param name="expression">PSPropertyExpression to test against.</param>
        /// <returns>True if there is a match, else false.</returns>
        internal bool IsMatch(PSPropertyExpression expression)
        {
            for (int k = 0; k < _wildcardPatterns.Length; k++)
            {
                if (_wildcardPatterns[k].IsMatch(expression.ToString()))
                {
                    return(true);
                }
            }

            return(false);
        }
Пример #14
0
        /// <summary>
        /// To write the Property name.
        /// </summary>
        private static void WritePropertyName(StringBuilder Listtag, MshParameter p)
        {
            // for writing the property name
            string label = p.GetEntry(ConvertHTMLParameterDefinitionKeys.LabelEntryKey) as string;

            if (label != null)
            {
                Listtag.Append(label);
            }
            else
            {
                PSPropertyExpression ex = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as PSPropertyExpression;
                Listtag.Append(ex.ToString());
            }
        }
Пример #15
0
        private int ComputeBestMatch(AppliesTo appliesTo, PSObject currentObject)
        {
            int best = BestMatchIndexUndefined;

            foreach (TypeOrGroupReference r in appliesTo.referenceList)
            {
                PSPropertyExpression ex = null;
                if (r.conditionToken != null)
                {
                    ex = _expressionFactory.CreateFromExpressionToken(r.conditionToken);
                }

                int           currentMatch = BestMatchIndexUndefined;
                TypeReference tr           = r as TypeReference;

                if (tr != null)
                {
                    // we have a type
                    currentMatch = MatchTypeIndex(tr.name, currentObject, ex);
                }
                else
                {
                    // we have a type group reference
                    TypeGroupReference tgr = r as TypeGroupReference;

                    // find the type group definition the reference points to
                    TypeGroupDefinition tgd = DisplayDataQuery.FindGroupDefinition(_db, tgr.name);

                    if (tgd != null)
                    {
                        // we found the group, see if the group has the type
                        currentMatch = ComputeBestMatchInGroup(tgd, currentObject, ex);
                    }
                }

                if (currentMatch == BestMatchIndexPerfect)
                {
                    return(currentMatch);
                }

                if (best == BestMatchIndexUndefined || best < currentMatch)
                {
                    best = currentMatch;
                }
            }

            return(best);
        }
Пример #16
0
        private bool MatchCondition(PSObject currentObject, PSPropertyExpression ex)
        {
            if (ex == null)
            {
                return(true);
            }

            PSPropertyExpressionResult expressionResult;
            bool retVal = DisplayCondition.Evaluate(currentObject, ex, out expressionResult);

            if (expressionResult != null && expressionResult.Exception != null)
            {
                _failedResultsList.Add(expressionResult);
            }
            return(retVal);
        }
Пример #17
0
        internal static bool Evaluate(PSObject obj, PSPropertyExpression ex, out PSPropertyExpressionResult expressionResult)
        {
            expressionResult = null;
            List <PSPropertyExpressionResult> res = ex.GetValues(obj);

            if (res.Count == 0)
            {
                return(false);
            }
            if (res[0].Exception != null)
            {
                expressionResult = res[0];
                return(false);
            }
            return(LanguagePrimitives.IsTrue(res[0].Result));
        }
        private bool EvaluateDisplayCondition(PSObject so, ExpressionToken conditionToken)
        {
            if (conditionToken == null)
                return true;

            PSPropertyExpression ex = _expressionFactory.CreateFromExpressionToken(conditionToken, _loadingInfo);
            PSPropertyExpressionResult expressionResult;
            bool retVal = DisplayCondition.Evaluate(so, ex, out expressionResult);

            if (expressionResult != null && expressionResult.Exception != null)
            {
                _errorManager.LogPSPropertyExpressionFailedResult(expressionResult, so);
            }

            return retVal;
        }
Пример #19
0
        internal static List <MshResolvedExpressionParameterAssociation> ExpandParameters(List <MshParameter> parameters, PSObject target)
        {
            List <MshResolvedExpressionParameterAssociation> retVal = new List <MshResolvedExpressionParameterAssociation>();

            foreach (MshParameter par in parameters)
            {
                PSPropertyExpression        expression             = par.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as PSPropertyExpression;
                List <PSPropertyExpression> expandedExpressionList = expression.ResolveNames(target);

                foreach (PSPropertyExpression ex in expandedExpressionList)
                {
                    retVal.Add(new MshResolvedExpressionParameterAssociation(par, ex));
                }
            }

            return(retVal);
        }
Пример #20
0
        protected bool EvaluateDisplayCondition(PSObject so, ExpressionToken conditionToken)
        {
            if (conditionToken == null)
            {
                return(true);
            }

            PSPropertyExpression       ex = this.expressionFactory.CreateFromExpressionToken(conditionToken, this.dataBaseInfo.view.loadingInfo);
            PSPropertyExpressionResult expressionResult;
            bool retVal = DisplayCondition.Evaluate(so, ex, out expressionResult);

            if (expressionResult != null && expressionResult.Exception != null)
            {
                _errorManager.LogPSPropertyExpressionFailedResult(expressionResult, so);
            }
            return(retVal);
        }
Пример #21
0
        // Expand a list of (possibly wildcarded) expressions into resolved expressions that
        // match property names on the incoming objects.
        private static List <MshParameter> ExpandExpressions(List <PSObject> inputObjects, List <MshParameter> unexpandedParameterList)
        {
            List <MshParameter> expandedParameterList = new();

            if (unexpandedParameterList != null)
            {
                foreach (MshParameter unexpandedParameter in unexpandedParameterList)
                {
                    PSPropertyExpression ex = (PSPropertyExpression)unexpandedParameter.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey);
                    if (!ex.HasWildCardCharacters) // this special cases 1) script blocks and 2) wildcard-less strings
                    {
                        expandedParameterList.Add(unexpandedParameter);
                    }
                    else
                    {
                        SortedDictionary <string, PSPropertyExpression> expandedPropertyNames = new(StringComparer.OrdinalIgnoreCase);
                        if (inputObjects != null)
                        {
                            foreach (object inputObject in inputObjects)
                            {
                                if (inputObject == null)
                                {
                                    continue;
                                }

                                foreach (PSPropertyExpression resolvedName in ex.ResolveNames(PSObject.AsPSObject(inputObject)))
                                {
                                    expandedPropertyNames[resolvedName.ToString()] = resolvedName;
                                }
                            }
                        }

                        foreach (PSPropertyExpression expandedExpression in expandedPropertyNames.Values)
                        {
                            MshParameter expandedParameter = new();
                            expandedParameter.hash = (Hashtable)unexpandedParameter.hash.Clone();
                            expandedParameter.hash[FormatParameterDefinitionKeys.ExpressionEntryKey] = expandedExpression;

                            expandedParameterList.Add(expandedParameter);
                        }
                    }
                }
            }

            return(expandedParameterList);
        }
Пример #22
0
        /// <summary>
        /// create an expression from an expression token
        /// </summary>
        /// <param name="et">expression token to use</param>
        /// <param name="loadingInfo">The context from which the file was loaded</param>
        /// <returns>constructed expression</returns>
        /// <exception cref="ParseException"></exception>
        internal PSPropertyExpression CreateFromExpressionToken(ExpressionToken et, DatabaseLoadingInfo loadingInfo)
        {
            if (et.isScriptBlock)
            {
                // we cache script blocks from expression tokens
                if (_expressionCache != null)
                {
                    PSPropertyExpression value;
                    if (_expressionCache.TryGetValue(et, out value))
                    {
                        // got a hit on the cache, just return
                        return(value);
                    }
                }
                else
                {
                    _expressionCache = new Dictionary <ExpressionToken, PSPropertyExpression>();
                }

                bool isFullyTrusted = false;
                bool isProductCode  = false;
                if (loadingInfo != null)
                {
                    isFullyTrusted = loadingInfo.isFullyTrusted;
                    isProductCode  = loadingInfo.isProductCode;
                }

                // no hit, we build one and we cache
                ScriptBlock sb = ScriptBlock.CreateDelayParsedScriptBlock(et.expressionValue, isProductCode: isProductCode);
                sb.DebuggerStepThrough = true;

                if (isFullyTrusted)
                {
                    sb.LanguageMode = PSLanguageMode.FullLanguage;
                }

                PSPropertyExpression ex = new PSPropertyExpression(sb);

                _expressionCache.Add(et, ex);

                return(ex);
            }

            // we do not cache if it is just a property name
            return(new PSPropertyExpression(et.expressionValue));
        }
Пример #23
0
        private static void EvaluateSortingExpression(
            MshParameter p,
            PSObject inputObject,
            List <ObjectCommandPropertyValue> orderValues,
            List <ErrorRecord> errors,
            out string propertyNotFoundMsg,
            ref bool comparable)
        {
            // NOTE: we assume globbing was not allowed in input
            PSPropertyExpression ex = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as PSPropertyExpression;

            // get the values, but do not expand aliases
            List <PSPropertyExpressionResult> expressionResults = ex.GetValues(inputObject, false, true);

            if (expressionResults.Count == 0)
            {
                // we did not get any result out of the expression:
                // we enter a null as a place holder
                orderValues.Add(ObjectCommandPropertyValue.NonExistingProperty);
                propertyNotFoundMsg = StringUtil.Format(SortObjectStrings.PropertyNotFound, ex.ToString());
                return;
            }

            propertyNotFoundMsg = null;
            // we obtained some results, enter them into the list
            foreach (PSPropertyExpressionResult r in expressionResults)
            {
                if (r.Exception == null)
                {
                    orderValues.Add(new ObjectCommandPropertyValue(r.Result));
                }
                else
                {
                    ErrorRecord errorRecord = new(
                        r.Exception,
                        "ExpressionEvaluation",
                        ErrorCategory.InvalidResult,
                        inputObject);
                    errors.Add(errorRecord);
                    orderValues.Add(ObjectCommandPropertyValue.ExistingNullProperty);
                }

                comparable = true;
            }
        }
Пример #24
0
        /// <summary>
        /// Retrieve the display name. It looks for a well known property and,
        /// if not found, it uses some heuristics to get a "close" match
        /// </summary>
        /// <param name="target">shell object to process</param>
        /// <param name="expressionFactory">expression factory to create PSPropertyExpression</param>
        /// <returns>resolved PSPropertyExpression; null if no match was found</returns>
        internal static PSPropertyExpression GetDisplayNameExpression(PSObject target, PSPropertyExpressionFactory expressionFactory)
        {
            // first try to get the expression from the object (types.ps1xml data)
            PSPropertyExpression expressionFromObject = GetDefaultNameExpression(target);

            if (expressionFromObject != null)
            {
                return(expressionFromObject);
            }

            // we failed the default display name, let's try some well known names
            // trying to get something potentially useful
            string[] knownPatterns = new string[] {
                "name", "id", "key", "*key", "*name", "*id",
            };

            // go over the patterns, looking for the first match
            foreach (string pattern in knownPatterns)
            {
                PSPropertyExpression        ex       = new PSPropertyExpression(pattern);
                List <PSPropertyExpression> exprList = ex.ResolveNames(target);

                while ((exprList.Count > 0) && (
                           exprList[0].ToString().Equals(RemotingConstants.ComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase) ||
                           exprList[0].ToString().Equals(RemotingConstants.ShowComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase) ||
                           exprList[0].ToString().Equals(RemotingConstants.RunspaceIdNoteProperty, StringComparison.OrdinalIgnoreCase) ||
                           exprList[0].ToString().Equals(RemotingConstants.SourceJobInstanceId, StringComparison.OrdinalIgnoreCase)))
                {
                    exprList.RemoveAt(0);
                }

                if (exprList.Count == 0)
                {
                    continue;
                }

                // if more than one match, just return the first one
                return(exprList[0]);
            }

            // we did not find anything
            return(null);
        }
Пример #25
0
        internal override object Verify(object val,
                                        TerminatingErrorContext invocationContext,
                                        bool originalParameterWasHashTable)
        {
            if (val == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(val));
            }

            // need to check the type:
            // it can be a string or a script block
            ScriptBlock sb = val as ScriptBlock;

            if (sb != null)
            {
                PSPropertyExpression ex = new PSPropertyExpression(sb);
                return(ex);
            }

            string s = val as string;

            if (s != null)
            {
                if (string.IsNullOrEmpty(s))
                {
                    ProcessEmptyStringError(originalParameterWasHashTable, invocationContext);
                }

                PSPropertyExpression ex = new PSPropertyExpression(s);
                if (_noGlobbing)
                {
                    if (ex.HasWildCardCharacters)
                    {
                        ProcessGlobbingCharactersError(originalParameterWasHashTable, s, invocationContext);
                    }
                }

                return(ex);
            }

            PSTraceSource.NewArgumentException(nameof(val));
            return(null);
        }
Пример #26
0
        private void InitializeGroupBy()
        {
            // first check if there is an override from the command line
            if (parameters != null && parameters.groupByParameter != null)
            {
                // get the expression to use
                PSPropertyExpression groupingKeyExpression = parameters.groupByParameter.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as PSPropertyExpression;

                // set the label
                string label    = null;
                object labelKey = parameters.groupByParameter.GetEntry(FormatParameterDefinitionKeys.LabelEntryKey);
                if (labelKey != AutomationNull.Value)
                {
                    label = labelKey as string;
                }

                _groupingManager = new GroupingInfoManager();
                _groupingManager.Initialize(groupingKeyExpression, label);
                return;
            }

            // check if we have a view to initialize from
            if (this.dataBaseInfo.view != null)
            {
                GroupBy gb = this.dataBaseInfo.view.groupBy;
                if (gb is null)
                {
                    return;
                }

                if (gb.startGroup is null || gb.startGroup.expression is null)
                {
                    return;
                }

                PSPropertyExpression ex = this.expressionFactory.CreateFromExpressionToken(gb.startGroup.expression, this.dataBaseInfo.view.loadingInfo);

                _groupingManager = new GroupingInfoManager();
                _groupingManager.Initialize(ex, null);
            }
        }
Пример #27
0
        /// <summary>
        /// it gets the display name value
        /// </summary>
        /// <param name="target">shell object to process</param>
        /// <param name="expressionFactory">expression factory to create PSPropertyExpression</param>
        /// <returns>PSPropertyExpressionResult if successful; null otherwise</returns>
        internal static PSPropertyExpressionResult GetDisplayName(PSObject target, PSPropertyExpressionFactory expressionFactory)
        {
            // get the expression to evaluate
            PSPropertyExpression ex = GetDisplayNameExpression(target, expressionFactory);

            if (ex == null)
            {
                return(null);
            }

            // evaluate the expression
            List <PSPropertyExpressionResult> resList = ex.GetValues(target);

            if (resList.Count == 0 || resList[0].Exception != null)
            {
                // no results or the retrieval on the first one failed
                return(null);
            }
            // return something only if the first match was successful
            return(resList[0]);
        }
Пример #28
0
        private void SetUpActiveProperty(PSObject so)
        {
            List <MshParameter> rawMshParameterList = null;

            if (this.inputParameters != null)
            {
                rawMshParameterList = this.inputParameters.mshParameterList;
            }

            // check if we received properties from the command line
            if (rawMshParameterList != null && rawMshParameterList.Count > 0)
            {
                this.activeAssociationList = AssociationManager.ExpandParameters(rawMshParameterList, so);
                return;
            }

            // we did not get any properties:
            // try to get the display property of the object
            PSPropertyExpression displayNameExpression = PSObjectHelper.GetDisplayNameExpression(so, this.expressionFactory);

            if (displayNameExpression != null)
            {
                this.activeAssociationList = new List <MshResolvedExpressionParameterAssociation>();
                this.activeAssociationList.Add(new MshResolvedExpressionParameterAssociation(null, displayNameExpression));
                return;
            }

            // try to get the default property set (we will use the first property)
            this.activeAssociationList = AssociationManager.ExpandDefaultPropertySet(so, this.expressionFactory);
            if (this.activeAssociationList.Count > 0)
            {
                // we got a valid set of properties from the default property set
                return;
            }

            // we failed to get anything from the default property set
            // just get all the properties
            this.activeAssociationList = AssociationManager.ExpandAll(so);
        }
Пример #29
0
        internal static List <MshResolvedExpressionParameterAssociation> ExpandTableParameters(List <MshParameter> parameters, PSObject target)
        {
            List <MshResolvedExpressionParameterAssociation> retVal = new List <MshResolvedExpressionParameterAssociation>();

            foreach (MshParameter par in parameters)
            {
                PSPropertyExpression        expression             = par.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as PSPropertyExpression;
                List <PSPropertyExpression> expandedExpressionList = expression.ResolveNames(target);

                if (!expression.HasWildCardCharacters && expandedExpressionList.Count == 0)
                {
                    // we did not find anything, mark as unresolved
                    retVal.Add(new MshResolvedExpressionParameterAssociation(par, expression));
                }

                foreach (PSPropertyExpression ex in expandedExpressionList)
                {
                    retVal.Add(new MshResolvedExpressionParameterAssociation(par, ex));
                }
            }

            return(retVal);
        }
Пример #30
0
        /// <summary>
        /// To write the Property value.
        /// </summary>
        private void WritePropertyValue(StringBuilder Listtag, MshParameter p)
        {
            PSPropertyExpression exValue = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as PSPropertyExpression;

            // get the value of the property
            List <PSPropertyExpressionResult> resultList = exValue.GetValues(_inputObject);

            foreach (PSPropertyExpressionResult result in resultList)
            {
                // create comma sep list for multiple results
                if (result.Result != null)
                {
                    string htmlEncodedResult = WebUtility.HtmlEncode(SafeToString(result.Result));
                    Listtag.Append(htmlEncodedResult);
                }

                Listtag.Append(", ");
            }

            if (Listtag.ToString().EndsWith(", ", StringComparison.Ordinal))
            {
                Listtag.Remove(Listtag.Length - 2, 2);
            }
        }