protected override void ProcessRecord() { if (null == table) { //create table header PSMemberInfoCollection <PSPropertyInfo> props = InputObject[0].Properties; //I believe that the first object through the pipeline is null. others will have data. table = new PdfPTable((int)props.Count()); props.ToList().ForEach(x => { table.AddCell(x.Name); }); } //populate the rows with data. foreach (var item in InputObject) { PSMemberInfoCollection <PSPropertyInfo> props = item.Properties; props.ToList().ForEach(x => { if (null == x.Value) { table.AddCell(string.Empty); } else { table.AddCell(x.Value.ToString()); } }); } base.ProcessRecord(); }
public static void SafeAdd(this PSMemberInfoCollection <PSPropertyInfo> t, PSPropertyInfo item) { if (null == t[item.Name]) { t.Add(item); } }
public static T GetNestedProperty <T>(this PSMemberInfoCollection <PSPropertyInfo> properties, params string[] names) { var lastName = names.Last(); var nestedProperties = names.Take(names.Length - 1).Aggregate(properties, (p, n) => p?.GetProperty <PSObject>(n)?.Properties); return(nestedProperties != null?nestedProperties.GetProperty <T>(lastName) : default(T)); }
/// <summary> /// Append to a dictionary any properties that might have been added to an object (via PSObject) through the Add-Member cmdlet. /// If the passed in object is a custom object (not a simple object, not a dictionary, not a list, get processed in ProcessCustomObject method), /// we also take Adapted properties into account. Otherwise, we only consider the Extended properties. /// When the object is a pure PSObject, it also gets processed in "ProcessCustomObject" before reaching this method, so we will /// iterate both extended and adapted properties for it. Since it's a pure PSObject, there will be no adapted properties. /// </summary> /// <param name="psobj">The containing PSObject, or null if the base object was not contained in a PSObject</param> /// <param name="receiver">The dictionary to which any additional properties will be appended</param> /// <param name="depth">The current depth into the object graph</param> /// <param name="isCustomObject">The processed object is a custom object</param> private void AppendPsProperties(PSObject psobj, IDictionary receiver, int depth, bool isCustomObject) { var type = _psmemberInfoIntegrationCollection.MakeGenericType(typeof(PSPropertyInfo)); PSMemberInfoCollection <PSPropertyInfo> srcPropertiesToSearch = (PSMemberInfoCollection <PSPropertyInfo>)type.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)[0].Invoke(new[] { psobj, isCustomObject ? GetPropertyCollection(PSMemberViewTypes.Extended | PSMemberViewTypes.Adapted) : GetPropertyCollection(PSMemberViewTypes.Extended) }); foreach (PSPropertyInfo prop in srcPropertiesToSearch) { object value = null; try { value = prop.Value; } catch (Exception) { } var receiver2 = receiver as Dictionary <string, object>; if (receiver2 != null && receiver2.Any(m => m.Key.Equals(prop.Name, StringComparison.OrdinalIgnoreCase))) { return; } if (!receiver.Contains(prop.Name)) { receiver[prop.Name] = ProcessValue(value, depth + 1); } } }
private IEnumerable <PowerShellOutput> parseResults(PSObject obj) { PSMemberInfoCollection <PSPropertyInfo> retValueProperties = obj.Properties; foreach (PSPropertyInfo pInfo in retValueProperties) { yield return(new PowerShellOutput(pInfo)); } }
public static string GetPSObjectValue(this PSMemberInfoCollection <PSPropertyInfo> infoProperties, string propertyName) { var resultValue = string.Empty; if (infoProperties[propertyName] != null && infoProperties[propertyName].Value != null) { resultValue = infoProperties[propertyName].Value.ToString(); } return(resultValue); }
private string GetPSObjectValue(PSMemberInfoCollection <PSPropertyInfo> infoProperties, string propertyName) { var resultValue = string.Empty; if (infoProperties[propertyName] != null && infoProperties[propertyName].Value != null) { resultValue = infoProperties[propertyName].Value.ToString(); LogVerbose("{0}: {1}", propertyName, resultValue); } return(resultValue); }
internal static string TranslatePSObjectToString(PSObject pso, string format) { if (string.Equals(format, "xml", StringComparison.OrdinalIgnoreCase)) { PSMemberInfoCollection <PSPropertyInfo> properties = pso.Properties; PSPropertyInfo pSPropertyInfo = properties.FirstOrDefault <PSPropertyInfo>((PSPropertyInfo item) => string.Equals(item.Name, "InnerXml", StringComparison.OrdinalIgnoreCase)); if (pSPropertyInfo != null) { return(pSPropertyInfo.Value.ToString()); } } return(pso.ToString()); }
private void MergeProperties(IDictionary <string, string> target, PSMemberInfoCollection <PSPropertyInfo> source) { foreach (var info in source) { var name = info.Name; if (target.ContainsKey(name)) { target.Remove(name); } target.Add(name, info.Value.ToString()); } }
public static T GetProperty <T>(this PSMemberInfoCollection <PSPropertyInfo> properties, string name) { switch (properties[name]?.Value) { case PSObject psObject when psObject.BaseObject is PSCustomObject && psObject.ImmediateBaseObject.IsTypeOrArrayOfType <T>(): return(psObject.ImmediateBaseObject.NormalizeArrayType <T>()); case PSObject psObject when psObject.BaseObject.IsTypeOrArrayOfType <T>(): return(psObject.BaseObject.NormalizeArrayType <T>()); case object value when value.IsTypeOrArrayOfType <T>(): return(value.NormalizeArrayType <T>()); default: return(default(T)); } }
protected void AddMemberToCollection <T>(PSMemberInfoCollection <T> collection, T member, bool force) where T : PSMemberInfo { var existingValue = collection[member.Name]; if (existingValue != null) { if (force) { collection.Remove(member.Name); } else { var msg = String.Format("Member '{0}' already exists. Use force to overwrite.", member.Name); ThrowTerminatingError(new ErrorRecord(new ArgumentException(msg), "MemberAlreadyExists", ErrorCategory.InvalidArgument, member)); } } collection.Add(member); }
internal static void Add <T, TProp>(this PSMemberInfoCollection <PSPropertyInfo> props, T obj, Expression <Func <T, TProp> > memberExpression) { MemberInfo mi = null; if (memberExpression.Body is MemberExpression memEx) { mi = memEx.Member; } else if (memberExpression.Body is UnaryExpression unEx && unEx.Operand is MemberExpression unExMem) { mi = unExMem.Member; } if (mi != null) { Func <T, TProp> func = memberExpression.Compile(); props.Add(new PSNoteProperty(mi.Name, func(obj))); } }
private void Button_Click(object sender, RoutedEventArgs e) { string output = ""; PSMemberInfoCollection <PSPropertyInfo> props = adUser.Properties; PSPropertyInfo propMem = props["MemberOf"]; object propMemVal = propMem.Value; //ADPropertyValueCollection System.Collections.CollectionBase x = propMemVal as System.Collections.CollectionBase; //Type t = propMemVal.GetType(); //MessageBoxResult messageBoxResult1 = System.Windows.MessageBox.Show(this, t.ToString(), "Member Groups", System.Windows.MessageBoxButton.OK); //Array x = propMemVal as Array; foreach (var memberGroup in x) { string memberString = memberGroup as string; string memberStringReduced = memberString.Substring(memberString.IndexOf('=') + 1, memberString.IndexOf(',') - 3); output += memberStringReduced + "\n"; } MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show(this, output, "Member Groups", System.Windows.MessageBoxButton.OK); }
private void PsPart() { using (PowerShell PowerShellInstance = PowerShell.Create()) { PowerShellInstance.AddScript("Get-WmiObject -Class Win32_WinSAT"); Collection <PSObject> PSOutput = PowerShellInstance.Invoke(); PSMemberInfoCollection <PSMemberInfo> members = PSOutput[0].Members; foreach (PSMemberInfo member in members) { if (member != null) { if (member.Value != null) { if (member.Name == "CPUScore" | member.Name == "D3DScore" | member.Name == "DiskScore" | member.Name == "GraphicsScore" | member.Name == "MemoryScore") { this.interestingMembers.Add(member); } } } } } }
public static Manifest ToManifest(this PSObject pso) { if (pso == null) { return(null); } PSMemberInfo source; var manifest = new Manifest(); PSMemberInfoCollection <PSMemberInfo> members = pso.Members; var properties = from x in typeof(Manifest).GetMembers() where x.MemberType == MemberTypes.Property select(x as PropertyInfo); foreach (PropertyInfo p in properties) { source = (members[p.Name] ?? members[ToCamelCase(p.Name)]); if (source == null) { continue; } switch (p.Name) { default: p.SetValue(manifest, source.Value); break; case nameof(Manifest.Version): manifest.Version = ToSemanticVersion(PSObject.AsPSObject(source.Value)); break; case nameof(Manifest.BranchVersionMap): manifest.BranchVersionMap = (source.Value is Dictionary <string, string> dic ? dic : null); break; } } return(manifest); }
static IEnumerable <string> CmdletDirGlobbing(string basePath, string glob) { Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); // cd to basePath if (basePath != null) { Pipeline cdPipeline = runspace.CreatePipeline(); Command cdCommand = new Command("cd"); cdCommand.Parameters.Add("Path", basePath); cdPipeline.Commands.Add(cdCommand); cdPipeline.Invoke(); // run the cmdlet } // run the "dir" cmdlet (e.g. "dir C:\*\*\*.txt" ) Pipeline dirPipeline = runspace.CreatePipeline(); Command dirCommand = new Command("dir"); dirCommand.Parameters.Add("Path", glob); dirPipeline.Commands.Add(dirCommand); Collection <PSObject> dirOutput = dirPipeline.Invoke(); // for each found file foreach (PSObject psObject in dirOutput) { PSMemberInfoCollection <PSPropertyInfo> a = psObject.Properties; // look for the full path ("FullName") foreach (PSPropertyInfo psPropertyInfo in psObject.Properties) { if (psPropertyInfo.Name == "FullName") { yield return(psPropertyInfo.Value.ToString()); // yield it } } } }
/// <summary> /// Append to a dictionary any properties that might have been added to an object (via PSObject) through the Add-Member cmdlet. /// If the passed in object is a custom object (not a simple object, not a dictionary, not a list, get processed in ProcessCustomObject method), /// we also take Adapted properties into account. Otherwise, we only consider the Extended properties. /// When the object is a pure PSObject, it also gets processed in "ProcessCustomObject" before reaching this method, so we will /// iterate both extended and adapted properties for it. Since it's a pure PSObject, there will be no adapted properties. /// </summary> /// <param name="psobj">The containing PSObject, or null if the base object was not contained in a PSObject</param> /// <param name="receiver">The dictionary to which any additional properties will be appended</param> /// <param name="depth">The current depth into the object graph</param> /// <param name="isCustomObject">The processed object is a custom object</param> private static void AppendPsProperties(PSObject psobj, IDictionary receiver, int depth, bool isCustomObject) { // serialize only Extended and Adapted properties.. PSMemberInfoCollection <PSPropertyInfo> srcPropertiesToSearch = psobj.Properties; foreach (PSPropertyInfo prop in srcPropertiesToSearch) { object value = null; try { value = prop.Value; } catch (Exception) { } if (!receiver.Contains(prop.Name)) { receiver[prop.Name] = ProcessValue(value, depth + 1); } } }
private object GetPSOValue(List <string> already, string name, PSMemberInfoCollection <PSPropertyInfo> pso) { try { if (pso[name] != null) { if (already.Where(x => x == name).FirstOrDefault() == null) { already.Add(name); return(pso[name].Value); } else { return(Constants.Messages.NoneFound); } } return(Constants.Messages.NoneFound); } catch (Exception ex) { return(Constants.Messages.NoneFound); } }
private static PSGetMemberBinder Get(string memberName, bool @static, bool nonEnumerating) { PSGetMemberBinder binder; Dictionary <string, PSGetMemberBinder> dictionary = @static ? _staticBinderCache : (nonEnumerating ? _binderCacheNonEnumerable : _binderCache); lock (dictionary) { if (dictionary.TryGetValue(memberName, out binder)) { return(binder); } if (PSMemberInfoCollection <PSMemberInfo> .IsReservedName(memberName)) { binder = dictionary[memberName.ToLowerInvariant()]; } else { binder = new PSGetMemberBinder(memberName, true, @static, nonEnumerating); if (!@static) { List <PSGetMemberBinder> orAdd = _binderCacheIgnoringCase.GetOrAdd(memberName, _ => new List <PSGetMemberBinder>()); lock (orAdd) { if (orAdd.Any <PSGetMemberBinder>()) { binder._hasInstanceMember = orAdd[0]._hasInstanceMember; binder._hasTypeTableMember = orAdd[0]._hasTypeTableMember; } orAdd.Add(binder); } } } dictionary.Add(memberName, binder); } return(binder); }
private void ReadMemberSet(PSMemberInfoCollection<PSMemberInfo> collection) { if (this.ReadStartElementAndHandleEmpty("MS")) { while (this._reader.NodeType == XmlNodeType.Element) { if (this.IsNextElement("MS")) { string name = this.ReadNameAttribute(); PSMemberSet member = new PSMemberSet(name); collection.Add(member); this.ReadMemberSet(member.Members); PSGetMemberBinder.SetHasInstanceMember(name); } else { PSNoteProperty property = this.ReadNoteProperty(); collection.Add(property); PSGetMemberBinder.SetHasInstanceMember(property.Name); } } this.ReadEndElement(); } }
/// <summary> /// Serialize member set. This method serializes without writing /// enclosing tags and attributes. /// </summary> /// <param name="me"> /// enumerable containing members /// </param> /// <param name="depth"></param> /// <param name="writeEnclosingMemberSetElementTag"> /// if this is true, write an enclosing "<memberset></memberset>" tag. /// </param> /// <returns></returns> private void WriteMemberInfoCollection( PSMemberInfoCollection<PSMemberInfo> me, int depth, bool writeEnclosingMemberSetElementTag) { Dbg.Assert(me != null, "caller should validate the parameter"); bool enclosingTagWritten = false; foreach (PSMemberInfo info in me) { if (!info.ShouldSerialize) { continue; } PSPropertyInfo property = info as PSPropertyInfo; if (property == null) { continue; } enclosingTagWritten = true; WriteStartElement(_writer, CustomSerializationStrings.Properties); WriteAttribute(_writer, CustomSerializationStrings.NameAttribute, info.Name); if (!_notypeinformation) WriteAttribute(_writer, CustomSerializationStrings.TypeAttribute, info.GetType().ToString()); _writer.WriteString(property.Value.ToString()); } if (enclosingTagWritten) { _writer.WriteEndElement(); } }
private void AddSecurityProperties( PSMemberInfoCollection<PSPropertyInfo> properties, StringBuilder sbValues) { sbValues.Append("<Security"); foreach (var prop in properties) { sbValues.Append(WSManStringLiterals.SingleWhiteSpace); if (IsValueOfParamList(prop.Name, WSManStringLiterals.NewItemSecurityParams)) { // Ensure SDDL, which can contain invalid XML characters such as '&', is escaped. string propValueStr = (prop.Name.Equals("SDDL", StringComparison.OrdinalIgnoreCase)) ? EscapeValuesForXML(prop.Value.ToString()) : prop.Value.ToString(); sbValues.Append(prop.Name); sbValues.Append(WSManStringLiterals.Equalto); sbValues.Append(WSManStringLiterals.EnclosingDoubleQuotes + propValueStr + WSManStringLiterals.EnclosingDoubleQuotes); } } sbValues.Append(WSManStringLiterals.GreaterThan); sbValues.Append("</Security>"); }
private void InitStaticMembers() { _staticMembers = new PSMemberInfoCollectionImplementation<PSMemberInfo>(this); GetMethods(false).ForEach(_staticMembers.Add); GetProperties(false).ForEach(_staticMembers.Add); }
private void InitProperties() { _properties = new PSMemberInfoCollectionImplementation<PSPropertyInfo>(this); var properties = GetProperties(true); properties.ForEach(_properties.Add); properties.ForEach(_members.Add); }
private void InitMethods() { _methods = new PSMemberInfoCollectionImplementation<PSMethodInfo>(this); var methods = GetMethods(true); methods.ForEach(_methods.Add); methods.ForEach(_members.Add); }
private static void Add(this PSMemberInfoCollection <PSPropertyInfo> props, string name, object value) { props.Add(new PSNoteProperty(name, value)); }
private void WriteMemberInfoCollection(PSMemberInfoCollection<PSMemberInfo> me, int depth, bool writeEnclosingMemberSetElementTag) { bool flag = false; foreach (PSMemberInfo info in me) { if (info.ShouldSerialize) { PSPropertyInfo info2 = info as PSPropertyInfo; if (info2 != null) { flag = true; WriteStartElement(this._writer, "Property"); WriteAttribute(this._writer, "Name", info.Name); if (!this._notypeinformation) { WriteAttribute(this._writer, "Type", info.GetType().ToString()); } this._writer.WriteString(info2.Value.ToString()); } } } if (flag) { this._writer.WriteEndElement(); } }
protected void Initialize(object obj) { _members = new PSMemberInfoCollectionImplementation<PSMemberInfo>(this); ImmediateBaseObject = obj; }
protected void Initialize(object obj) { if (obj == null) { throw new PSArgumentNullException("Argument \"obj\" is null"); } _members = new PSMemberInfoCollectionImplementation<PSMemberInfo>(this); ImmediateBaseObject = obj; }