Exemplo n.º 1
0
        private void AnalyzeObjectProperties(PSObject inObj)
        {
            MeasureObjectDictionary <object> dictionary = new MeasureObjectDictionary <object>();

            foreach (string str in this.Property)
            {
                MshExpression        expression = new MshExpression(str);
                List <MshExpression> list       = expression.ResolveNames(inObj);
                if ((list == null) || (list.Count == 0))
                {
                    if (!expression.HasWildCardCharacters)
                    {
                        string key = expression.ToString();
                        this.statistics.EnsureEntry(key);
                    }
                }
                else
                {
                    foreach (MshExpression expression2 in list)
                    {
                        string str3 = expression2.ToString();
                        if (!dictionary.ContainsKey(str3))
                        {
                            List <MshExpressionResult> values = expression2.GetValues(inObj);
                            if ((values != null) && (values.Count != 0))
                            {
                                this.AnalyzeValue(str3, values[0].Result);
                                dictionary[str3] = null;
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 2
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)
                {
                    MshExpression ex = (MshExpression)unexpandedParameter.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey);

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

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

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

                        expandedParameterList.Add(expandedParameter);
                    }
                }
            }
        }
        private static void EvaluateSortingExpression(MshParameter p, PSObject inputObject, List <ObjectCommandPropertyValue> orderValues, List <ErrorRecord> errors, out string propertyNotFoundMsg)
        {
            MshExpression entry             = p.GetEntry("expression") as MshExpression;
            List <MshExpressionResult> list = entry.GetValues(inputObject, false, true);

            if (list.Count == 0)
            {
                orderValues.Add(ObjectCommandPropertyValue.NonExistingProperty);
                propertyNotFoundMsg = StringUtil.Format(SortObjectStrings.PropertyNotFound, entry.ToString());
            }
            else
            {
                propertyNotFoundMsg = null;
                foreach (MshExpressionResult result in list)
                {
                    if (result.Exception == null)
                    {
                        orderValues.Add(new ObjectCommandPropertyValue(result.Result));
                    }
                    else
                    {
                        ErrorRecord item = new ErrorRecord(result.Exception, "ExpressionEvaluation", ErrorCategory.InvalidResult, inputObject);
                        errors.Add(item);
                        orderValues.Add(ObjectCommandPropertyValue.ExistingNullProperty);
                    }
                }
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Analyze an object on a property-by-property basis instead
        /// of as a simple value.
        /// Side effects: Updates statistics.
        /// <param name="inObj">The object to analyze.</param>
        /// </summary>
        private void AnalyzeObjectProperties(PSObject inObj)
        {
            // Keep track of which properties are counted for an
            // input object so that repeated properties won't be
            // counted twice.
            MeasureObjectDictionary <object> countedProperties = new MeasureObjectDictionary <object>();

            // First iterate over the user-specified list of
            // properties...
            foreach (string p in Property)
            {
                MshExpression        expression    = new MshExpression(p);
                List <MshExpression> resolvedNames = expression.ResolveNames(inObj);
                if (resolvedNames == null || resolvedNames.Count == 0)
                {
                    // Insert a blank entry so we can track
                    // property misses in EndProcessing.
                    if (!expression.HasWildCardCharacters)
                    {
                        string propertyName = expression.ToString();
                        _statistics.EnsureEntry(propertyName);
                    }

                    continue;
                }

                // Each property value can potentially refer
                // to multiple properties via globbing. Iterate over
                // the actual property names.
                foreach (MshExpression resolvedName in resolvedNames)
                {
                    string propertyName = resolvedName.ToString();
                    // skip duplicated properties
                    if (countedProperties.ContainsKey(propertyName))
                    {
                        continue;
                    }

                    List <MshExpressionResult> tempExprRes = resolvedName.GetValues(inObj);
                    if (tempExprRes == null || tempExprRes.Count == 0)
                    {
                        // Shouldn't happen - would somehow mean
                        // that the property went away between when
                        // we resolved it and when we tried to get its
                        // value.
                        continue;
                    }

                    AnalyzeValue(propertyName, tempExprRes[0].Result);

                    // Remember resolved propertyNames that have been counted
                    countedProperties[propertyName] = null;
                }
            }
        }
Exemplo n.º 5
0
 internal bool IsMatch(MshExpression expression)
 {
     for (int i = 0; i < this._wildcardPatterns.Length; i++)
     {
         if (this._wildcardPatterns[i].IsMatch(expression.ToString()))
         {
             return(true);
         }
     }
     return(false);
 }
Exemplo n.º 6
0
 /// <summary>
 /// try to match the expression against the array of wildcard patterns.
 /// the first match shortcircuits the search
 /// </summary>
 /// <param name="expression">MshExpression to test against</param>
 /// <returns>true if there is a match, else false</returns>
 internal bool IsMatch(MshExpression expression)
 {
     for (int k = 0; k < _wildcardPatterns.Length; k++)
     {
         if (_wildcardPatterns[k].IsMatch(expression.ToString()))
         {
             return(true);
         }
     }
     return(false);
 }
Exemplo n.º 7
0
        private void ProcessParameter(MshParameter p, PSObject inputObject, List <PSNoteProperty> result)
        {
            string        entry             = p.GetEntry("name") as string;
            MshExpression re                = p.GetEntry("expression") as MshExpression;
            List <MshExpressionResult> list = new List <MshExpressionResult>();

            foreach (MshExpression expression2 in re.ResolveNames(inputObject))
            {
                if ((this.exclusionFilter == null) || !this.exclusionFilter.IsMatch(expression2))
                {
                    List <MshExpressionResult> values = expression2.GetValues(inputObject);
                    if (values != null)
                    {
                        foreach (MshExpressionResult result2 in values)
                        {
                            list.Add(result2);
                        }
                    }
                }
            }
            if (list.Count == 0)
            {
                list.Add(new MshExpressionResult(null, re, null));
            }
            else if (!string.IsNullOrEmpty(entry) && (list.Count > 1))
            {
                ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(SelectObjectStrings.RenamingMultipleResults), "RenamingMultipleResults", ErrorCategory.InvalidOperation, inputObject);
                base.WriteError(errorRecord);
                return;
            }
            foreach (MshExpressionResult result3 in list)
            {
                if ((this.exclusionFilter == null) || !this.exclusionFilter.IsMatch(result3.ResolvedExpression))
                {
                    PSNoteProperty property;
                    if (string.IsNullOrEmpty(entry))
                    {
                        string str3 = result3.ResolvedExpression.ToString();
                        if (string.IsNullOrEmpty(str3))
                        {
                            PSArgumentException exception = PSTraceSource.NewArgumentException("Property", this.ResourcesBaseName, "EmptyScriptBlockAndNoName", new object[0]);
                            base.ThrowTerminatingError(new ErrorRecord(exception, "EmptyScriptBlockAndNoName", ErrorCategory.InvalidArgument, null));
                        }
                        property = new PSNoteProperty(str3, result3.Result);
                    }
                    else
                    {
                        property = new PSNoteProperty(entry, result3.Result);
                    }
                    result.Add(property);
                }
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// To write the Property name
        /// </summary>
        private 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
            {
                MshExpression ex = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as MshExpression;
                Listtag.Append(ex.ToString());
            }
        }
Exemplo n.º 9
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 List <MshParameter>();

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

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

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

                            expandedParameterList.Add(expandedParameter);
                        }
                    }
                }
            }

            return(expandedParameterList);
        }
Exemplo n.º 10
0
        private void WritePropertyValue(StringBuilder Listtag, MshParameter p)
        {
            MshExpression entry = p.GetEntry("expression") as MshExpression;

            foreach (MshExpressionResult result in entry.GetValues(this.inputObject))
            {
                if (result.Result != null)
                {
                    string str = WebUtility.HtmlEncode(SafeToString(result.Result));
                    Listtag.Append(str);
                }
                Listtag.Append(", ");
            }
            if (Listtag.ToString().EndsWith(", ", StringComparison.Ordinal))
            {
                Listtag.Remove(Listtag.Length - 2, 2);
            }
        }
Exemplo n.º 11
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
            MshExpression ex = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as MshExpression;

            // get the values, but do not expand aliases
            List <MshExpressionResult> 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 (MshExpressionResult r in expressionResults)
            {
                if (r.Exception == null)
                {
                    orderValues.Add(new ObjectCommandPropertyValue(r.Result));
                }
                else
                {
                    ErrorRecord errorRecord = new ErrorRecord(
                        r.Exception,
                        "ExpressionEvaluation",
                        ErrorCategory.InvalidResult,
                        inputObject);
                    errors.Add(errorRecord);
                    orderValues.Add(ObjectCommandPropertyValue.ExistingNullProperty);
                }
                comparable = true;
            }
        }
Exemplo n.º 12
0
        private static List <MshParameter> ExpandExpressions(List <PSObject> inputObjects, List <MshParameter> unexpandedParameterList)
        {
            List <MshParameter> list = new List <MshParameter>();

            if (unexpandedParameterList != null)
            {
                foreach (MshParameter parameter in unexpandedParameterList)
                {
                    MshExpression entry = (MshExpression)parameter.GetEntry("expression");
                    if (!entry.HasWildCardCharacters)
                    {
                        list.Add(parameter);
                    }
                    else
                    {
                        SortedDictionary <string, MshExpression> dictionary = new SortedDictionary <string, MshExpression>(StringComparer.OrdinalIgnoreCase);
                        if (inputObjects != null)
                        {
                            foreach (object obj2 in inputObjects)
                            {
                                if (obj2 != null)
                                {
                                    foreach (MshExpression expression2 in entry.ResolveNames(PSObject.AsPSObject(obj2)))
                                    {
                                        dictionary[expression2.ToString()] = expression2;
                                    }
                                }
                            }
                        }
                        foreach (MshExpression expression3 in dictionary.Values)
                        {
                            MshParameter item = new MshParameter {
                                hash = (Hashtable)parameter.hash.Clone()
                            };
                            item.hash["expression"] = expression3;
                            list.Add(item);
                        }
                    }
                }
            }
            return(list);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Resolve all wildcards in user input Property into resolvedNameMshParameters
        /// </summary>
        private void InitializeResolvedNameMshParameters()
        {
            // temp list of properties with wildcards resolved
            ArrayList resolvedNameProperty = new ArrayList();

            foreach (MshParameter p in _propertyMshParameterList)
            {
                string               label         = p.GetEntry(ConvertHTMLParameterDefinitionKeys.LabelEntryKey) as string;
                string               alignment     = p.GetEntry(ConvertHTMLParameterDefinitionKeys.AlignmentEntryKey) as string;
                string               width         = p.GetEntry(ConvertHTMLParameterDefinitionKeys.WidthEntryKey) as string;
                MshExpression        ex            = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as MshExpression;
                List <MshExpression> resolvedNames = ex.ResolveNames(_inputObject);
                foreach (MshExpression resolvedName in resolvedNames)
                {
                    Hashtable ht = CreateAuxPropertyHT(label, alignment, width);
                    ht.Add(FormatParameterDefinitionKeys.ExpressionEntryKey, resolvedName.ToString());
                    resolvedNameProperty.Add(ht);
                }
            }
            _resolvedNameMshParameters = ProcessParameter(resolvedNameProperty.ToArray());
        }
Exemplo n.º 14
0
        /// <summary>
        /// To write the Property value
        /// </summary>
        private void WritePropertyValue(StringBuilder Listtag, MshParameter p)
        {
            MshExpression exValue = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as MshExpression;

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

            foreach (MshExpressionResult 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);
            }
        }
Exemplo n.º 15
0
        private void InitializeResolvedNameMshParameters()
        {
            ArrayList list = new ArrayList();

            foreach (MshParameter parameter in this.propertyMshParameterList)
            {
                string               entry      = parameter.GetEntry("label") as string;
                string               alignment  = parameter.GetEntry("alignment") as string;
                string               width      = parameter.GetEntry("width") as string;
                MshExpression        expression = parameter.GetEntry("expression") as MshExpression;
                List <MshExpression> list2      = expression.ResolveNames(this.inputObject);
                if (list2.Count == 1)
                {
                    Hashtable hashtable = CreateAuxPropertyHT(entry, alignment, width);
                    if (expression.Script != null)
                    {
                        hashtable.Add("expression", expression.Script);
                    }
                    else
                    {
                        hashtable.Add("expression", expression.ToString());
                    }
                    list.Add(hashtable);
                }
                else
                {
                    foreach (MshExpression expression2 in list2)
                    {
                        Hashtable hashtable2 = CreateAuxPropertyHT(entry, alignment, width);
                        hashtable2.Add("expression", expression2.ToString());
                        list.Add(hashtable2);
                    }
                }
            }
            this.resolvedNameMshParameters = this.ProcessParameter(list.ToArray());
        }
Exemplo n.º 16
0
        internal void ProcessExpressionParameter(
            PSCmdlet cmdlet,
            object[] expr)
        {
            TerminatingErrorContext invocationContext = new TerminatingErrorContext(cmdlet);
            // compare-object and group-object use the same definition here
            ParameterProcessor processor = cmdlet is SortObjectCommand ?
                                           new ParameterProcessor(new SortObjectExpressionParameterDefinition()) :
                                           new ParameterProcessor(new GroupObjectExpressionParameterDefinition());

            if (expr != null)
            {
                if (_unexpandedParameterList == null)
                {
                    _unexpandedParameterList = processor.ProcessParameters(expr, invocationContext);

                    foreach (MshParameter unexpandedParameter in _unexpandedParameterList)
                    {
                        MshExpression mshExpression = (MshExpression)unexpandedParameter.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey);
                        if (!mshExpression.HasWildCardCharacters) // this special cases 1) script blocks and 2) wildcard-less strings
                        {
                            _mshParameterList.Add(unexpandedParameter);
                        }
                        else
                        {
                            if (_unExpandedParametersWithWildCardPattern == null)
                            {
                                _unExpandedParametersWithWildCardPattern = new List <MshParameter>();
                            }

                            _unExpandedParametersWithWildCardPattern.Add(unexpandedParameter);
                        }
                    }
                }
            }
        }
Exemplo n.º 17
0
        internal HeaderInfo GenerateHeaderInfo(PSObject input, TableControlBody tableBody, OutGridViewCommand parentCmdlet)
        {
            HeaderInfo info = new HeaderInfo();
            bool       flag = typeof(FileSystemInfo).IsInstanceOfType(input.BaseObject);

            if (tableBody != null)
            {
                List <TableRowItemDefinition> activeTableRowDefinition = this.GetActiveTableRowDefinition(tableBody, input);
                int num = 0;
                foreach (TableRowItemDefinition definition in activeTableRowDefinition)
                {
                    Microsoft.PowerShell.Commands.ColumnInfo col = null;
                    string staleObjectPropertyName          = null;
                    TableColumnHeaderDefinition definition2 = null;
                    if (tableBody.header.columnHeaderDefinitionList.Count >= (num - 1))
                    {
                        definition2 = tableBody.header.columnHeaderDefinitionList[num];
                    }
                    if ((definition2 != null) && (definition2.label != null))
                    {
                        staleObjectPropertyName = this.typeInfoDatabase.displayResourceManagerCache.GetTextTokenString(definition2.label);
                    }
                    FormatToken token = null;
                    if (definition.formatTokenList.Count > 0)
                    {
                        token = definition.formatTokenList[0];
                    }
                    if (token != null)
                    {
                        FieldPropertyToken token2 = token as FieldPropertyToken;
                        if (token2 != null)
                        {
                            if (staleObjectPropertyName == null)
                            {
                                staleObjectPropertyName = token2.expression.expressionValue;
                            }
                            if (token2.expression.isScriptBlock)
                            {
                                MshExpression expression = this.expressionFactory.CreateFromExpressionToken(token2.expression);
                                if (flag && staleObjectPropertyName.Equals("LastWriteTime", StringComparison.OrdinalIgnoreCase))
                                {
                                    col = new OriginalColumnInfo(staleObjectPropertyName, staleObjectPropertyName, "LastWriteTime", parentCmdlet);
                                }
                                else
                                {
                                    col = new ExpressionColumnInfo(staleObjectPropertyName, staleObjectPropertyName, expression);
                                }
                            }
                            else
                            {
                                col = new OriginalColumnInfo(token2.expression.expressionValue, staleObjectPropertyName, token2.expression.expressionValue, parentCmdlet);
                            }
                        }
                        else
                        {
                            TextToken tt = token as TextToken;
                            if (tt != null)
                            {
                                staleObjectPropertyName = this.typeInfoDatabase.displayResourceManagerCache.GetTextTokenString(tt);
                                col = new OriginalColumnInfo(tt.text, staleObjectPropertyName, tt.text, parentCmdlet);
                            }
                        }
                    }
                    if (col != null)
                    {
                        info.AddColumn(col);
                    }
                    num++;
                }
            }
            return(info);
        }
Exemplo n.º 18
0
        private void ProcessExpandParameter(MshParameter p, PSObject inputObject,
                                            List <PSNoteProperty> matchedProperties)
        {
            MshExpression ex = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as MshExpression;
            List <MshExpressionResult> expressionResults = ex.GetValues(inputObject);


            if (expressionResults.Count == 0)
            {
                ErrorRecord errorRecord = new ErrorRecord(
                    PSTraceSource.NewArgumentException("ExpandProperty", SelectObjectStrings.PropertyNotFound, ExpandProperty),
                    "ExpandPropertyNotFound",
                    ErrorCategory.InvalidArgument,
                    inputObject);
                throw new SelectObjectException(errorRecord);
            }
            if (expressionResults.Count > 1)
            {
                ErrorRecord errorRecord = new ErrorRecord(
                    PSTraceSource.NewArgumentException("ExpandProperty", SelectObjectStrings.MutlipleExpandProperties, ExpandProperty),
                    "MutlipleExpandProperties",
                    ErrorCategory.InvalidArgument,
                    inputObject);
                throw new SelectObjectException(errorRecord);
            }

            MshExpressionResult r = expressionResults[0];

            if (r.Exception == null)
            {
                // ignore the property value if it's null
                if (r.Result == null)
                {
                    return;
                }

                System.Collections.IEnumerable results = LanguagePrimitives.GetEnumerable(r.Result);
                if (results == null)
                {
                    // add NoteProperties if there is any
                    // If r.Result is a base object, we don't want to associate the NoteProperty
                    // directly with it. We want the NoteProperty to be associated only with this
                    // particular PSObject, so that when the user uses the base object else where,
                    // its members remain the same as before the Select-Object command run.
                    PSObject expandedObject = PSObject.AsPSObject(r.Result, true);
                    AddNoteProperties(expandedObject, inputObject, matchedProperties);

                    FilteredWriteObject(expandedObject, matchedProperties);
                    return;
                }

                foreach (object expandedValue in results)
                {
                    // ignore the element if it's null
                    if (expandedValue == null)
                    {
                        continue;
                    }

                    // add NoteProperties if there is any
                    // If expandedValue is a base object, we don't want to associate the NoteProperty
                    // directly with it. We want the NoteProperty to be associated only with this
                    // particular PSObject, so that when the user uses the base object else where,
                    // its members remain the same as before the Select-Object command run.
                    PSObject expandedObject = PSObject.AsPSObject(expandedValue, true);
                    AddNoteProperties(expandedObject, inputObject, matchedProperties);

                    FilteredWriteObject(expandedObject, matchedProperties);
                }
            }
            else
            {
                ErrorRecord errorRecord = new ErrorRecord(
                    r.Exception,
                    "PropertyEvaluationExpand",
                    ErrorCategory.InvalidResult,
                    inputObject);
                throw new SelectObjectException(errorRecord);
            }
        }
Exemplo n.º 19
0
        internal HeaderInfo GenerateHeaderInfo(PSObject input, TableControlBody tableBody, OutGridViewCommand parentCmdlet)
        {
            HeaderInfo headerInfo = new HeaderInfo();

            // This verification is needed because the database returns "LastWriteTime" value for file system objects
            // as strings and it is used to detect this situation and use the actual field value.
            bool fileSystemObject = typeof(FileSystemInfo).IsInstanceOfType(input.BaseObject);

            if (tableBody != null) // If the tableBody is null, the TableControlBody info was not put into the database.
            {
                // Generate HeaderInfo from the type information database.
                List <TableRowItemDefinition> activeRowItemDefinitionList = GetActiveTableRowDefinition(tableBody, input);

                int col = 0;
                foreach (TableRowItemDefinition rowItem in activeRowItemDefinitionList)
                {
                    ColumnInfo columnInfo  = null;
                    string     displayName = null;
                    TableColumnHeaderDefinition colHeader = null;
                    // Retrieve a matching TableColumnHeaderDefinition
                    if (col < tableBody.header.columnHeaderDefinitionList.Count)
                    {
                        colHeader = tableBody.header.columnHeaderDefinitionList[col];
                    }

                    if (colHeader != null && colHeader.label != null)
                    {
                        displayName = _typeInfoDatabase.displayResourceManagerCache.GetTextTokenString(colHeader.label);
                    }

                    FormatToken token = null;
                    if (rowItem.formatTokenList.Count > 0)
                    {
                        token = rowItem.formatTokenList[0];
                    }

                    if (token != null)
                    {
                        FieldPropertyToken fpt = token as FieldPropertyToken;
                        if (fpt != null)
                        {
                            if (displayName == null)
                            {
                                // Database does not provide a label(DisplayName) for the current property, use the expression value instead.
                                displayName = fpt.expression.expressionValue;
                            }
                            if (fpt.expression.isScriptBlock)
                            {
                                MshExpression ex = _expressionFactory.CreateFromExpressionToken(fpt.expression);
                                // Using the displayName as a propertyName for a stale PSObject.
                                const string LastWriteTimePropertyName = "LastWriteTime";

                                // For FileSystem objects "LastWriteTime" property value should be used although the database indicates that a script should be executed to get the value.
                                if (fileSystemObject && displayName.Equals(LastWriteTimePropertyName, StringComparison.OrdinalIgnoreCase))
                                {
                                    columnInfo = new OriginalColumnInfo(displayName, displayName, LastWriteTimePropertyName, parentCmdlet);
                                }
                                else
                                {
                                    columnInfo = new ExpressionColumnInfo(displayName, displayName, ex);
                                }
                            }
                            else
                            {
                                columnInfo = new OriginalColumnInfo(fpt.expression.expressionValue, displayName, fpt.expression.expressionValue, parentCmdlet);
                            }
                        }
                        else
                        {
                            TextToken tt = token as TextToken;
                            if (tt != null)
                            {
                                displayName = _typeInfoDatabase.displayResourceManagerCache.GetTextTokenString(tt);
                                columnInfo  = new OriginalColumnInfo(tt.text, displayName, tt.text, parentCmdlet);
                            }
                        }
                    }
                    if (columnInfo != null)
                    {
                        headerInfo.AddColumn(columnInfo);
                    }
                    col++;
                }
            }

            return(headerInfo);
        }
Exemplo n.º 20
0
        private void ProcessParameter(MshParameter p, PSObject inputObject, List <PSNoteProperty> result)
        {
            string name = p.GetEntry(NameEntryDefinition.NameEntryKey) as string;

            MshExpression ex = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as MshExpression;
            List <MshExpressionResult> expressionResults = new List <MshExpressionResult>();

            foreach (MshExpression resolvedName in ex.ResolveNames(inputObject))
            {
                if (_exclusionFilter == null || !_exclusionFilter.IsMatch(resolvedName))
                {
                    List <MshExpressionResult> tempExprResults = resolvedName.GetValues(inputObject);
                    if (tempExprResults == null)
                    {
                        continue;
                    }
                    foreach (MshExpressionResult mshExpRes in tempExprResults)
                    {
                        expressionResults.Add(mshExpRes);
                    }
                }
            }

            // allow 'Select-Object -Property noexist-name' to return a PSObject with property noexist-name,
            // unless noexist-name itself contains wildcards
            if (expressionResults.Count == 0 && !ex.HasWildCardCharacters)
            {
                expressionResults.Add(new MshExpressionResult(null, ex, null));
            }

            // if we have an expansion, renaming is not acceptable
            else if (!string.IsNullOrEmpty(name) && expressionResults.Count > 1)
            {
                string      errorMsg    = SelectObjectStrings.RenamingMultipleResults;
                ErrorRecord errorRecord = new ErrorRecord(
                    new InvalidOperationException(errorMsg),
                    "RenamingMultipleResults",
                    ErrorCategory.InvalidOperation,
                    inputObject);
                WriteError(errorRecord);
                return;
            }

            foreach (MshExpressionResult r in expressionResults)
            {
                // filter the exclusions, if any
                if (_exclusionFilter != null && _exclusionFilter.IsMatch(r.ResolvedExpression))
                {
                    continue;
                }

                PSNoteProperty mshProp;
                if (string.IsNullOrEmpty(name))
                {
                    string resolvedExpressionName = r.ResolvedExpression.ToString();
                    if (string.IsNullOrEmpty(resolvedExpressionName))
                    {
                        PSArgumentException mshArgE = PSTraceSource.NewArgumentException(
                            "Property",
                            SelectObjectStrings.EmptyScriptBlockAndNoName);
                        ThrowTerminatingError(
                            new ErrorRecord(
                                mshArgE,
                                "EmptyScriptBlockAndNoName",
                                ErrorCategory.InvalidArgument, null));
                    }
                    mshProp = new PSNoteProperty(resolvedExpressionName, r.Result);
                }
                else
                {
                    mshProp = new PSNoteProperty(name, r.Result);
                }
                result.Add(mshProp);
            }
        }
Exemplo n.º 21
0
 internal ExpressionColumnInfo(string staleObjectPropertyName, string displayName, MshExpression expression)
     : base(staleObjectPropertyName, displayName)
 {
     _expression = expression;
 }