internal override void BindArguments(PSObject obj) { if (obj != null) { var inputObject = obj.ToString(); _process.StandardInput.WriteLine(inputObject); } }
public IEnumerable<String> ProcessRecord(PSObject record) { if (record == null) { yield break; } if (_raw) { yield return record.ToString(); } else { if (_pipeline == null) { _pipeline = CreatePipeline(); _pipeline.InvokeAsync(); } _pipeline.Input.Write(record); foreach (PSObject result in _pipeline.Output.NonBlockingRead()) { yield return result.ToString(); } } }
private static string FormatCommandResult(PSObject psObject) { var result = string.Join(Environment.NewLine, psObject.ToString() .Split('\n') .Select(row => row.TrimEnd()) ); return result; }
internal static FormatEntryData GenerateOutOfBandObjectAsToString(PSObject so) { FormatEntryData data = new FormatEntryData { outOfBand = true }; RawTextFormatEntry entry = new RawTextFormatEntry { text = so.ToString() }; data.formatEntryInfo = entry; return data; }
/// <summary> /// Gets the string from PSObject using the information from /// types.ps1xml. This string is used for serializing the PSObject. /// </summary> /// /// <param name="source"> /// PSObject to be converted to string /// </param> /// /// <returns> /// string value to use for serializing this PSObject. /// </returns> private string GetStringFromPSObject(PSObject source) { Dbg.Assert(source != null, "caller should have validated the information"); // check if we have a well known string serialization source PSPropertyInfo serializationProperty = source.GetStringSerializationSource(null); string result = null; if (serializationProperty != null) { object val = serializationProperty.Value; if (val != null) { try { // if we have a string serialization value, return it result = val.ToString(); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); } } } else { try { // fall back value result = source.ToString(); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); } } return(result); }
/// <summary> /// Converts an object to a string safely... /// </summary> /// <param name="obj">The object to convert</param> /// <returns>The result of the conversion...</returns> internal static string SafeToString(object obj) { if (obj == null) { return(string.Empty); } try { PSObject pso = obj as PSObject; string result; if (pso != null) { object baseObject = pso.BaseObject; if (baseObject != null && !(baseObject is PSCustomObject)) { result = baseObject.ToString(); } else { result = pso.ToString(); } } else { result = obj.ToString(); } return(result); } catch (Exception e) { // We swallow all exceptions from command completion because we don't want the shell to crash CommandProcessorBase.CheckForSevereException(e); return(string.Empty); } }
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(); }
public virtual SimpleFormatEntryData GenerateSimpleFormatEntry(PSObject data) { return new SimpleFormatEntryData(Shape, data.ToString()) { WriteToErrorStream = data.WriteToErrorStream }; }
private string GetTerm() { if (_fullHelpObject == null) { return(""); } if (_fullHelpObject.Properties["Terms"] == null) { return(""); } if (_fullHelpObject.Properties["Terms"].Value == null) { return(""); } PSObject terms = (PSObject)_fullHelpObject.Properties["Terms"].Value; if (terms.Properties["Term"] == null) { return(""); } if (terms.Properties["Term"].Value == null) { return(""); } if (terms.Properties["Term"].Value.GetType().Equals(typeof(PSObject))) { PSObject term = (PSObject)terms.Properties["Term"].Value; return(term.ToString()); } if (terms.Properties["Term"].Value.GetType().Equals(typeof(PSObject[]))) { PSObject[] term = (PSObject[])terms.Properties["Term"].Value; StringBuilder result = new StringBuilder(); for (int i = 0; i < term.Length; i++) { string str = term[i].ToString(); if (str == null) { continue; } str = str.Trim(); if (String.IsNullOrEmpty(str)) { continue; } if (result.Length > 0) { result.Append(", "); } result.Append(str); } return(result.ToString()); } return(""); }
public static string GetHelpComments(PSObject help) { if (help == null) { throw new ArgumentNullException(nameof(help)); } bool flag = false; foreach (string typeName in help.TypeNames) { if (typeName.Contains("HelpInfo")) { flag = true; break; } } if (!flag) { throw new InvalidOperationException(ResourceManagerCache.GetResourceString("ProxyCommandStrings", "HelpInfoObjectRequired")); } StringBuilder sb = new StringBuilder(); ProxyCommand.AppendContent(sb, ".SYNOPSIS", (object)ProxyCommand.GetProperty <string>(help, "Synopsis")); ProxyCommand.AppendContent(sb, ".DESCRIPTION", ProxyCommand.GetProperty <PSObject[]>(help, "Description")); PSObject[] property1 = ProxyCommand.GetProperty <PSObject[]>(ProxyCommand.GetProperty <PSObject>(help, "Parameters"), "Parameter"); if (property1 != null) { foreach (PSObject psObject1 in property1) { PSObject property2 = ProxyCommand.GetProperty <PSObject>(psObject1, "Name"); PSObject[] property3 = ProxyCommand.GetProperty <PSObject[]>(psObject1, "Description"); sb.AppendFormat("\n.PARAMETER {0}\n\n", (object)property2); foreach (PSObject psObject2 in property3) { string str = ProxyCommand.GetProperty <string>(psObject2, "Text") ?? psObject2.ToString(); if (!string.IsNullOrEmpty(str)) { sb.Append(str); sb.Append("\n"); } } } } PSObject[] property4 = ProxyCommand.GetProperty <PSObject[]>(ProxyCommand.GetProperty <PSObject>(help, "examples"), "example"); if (property4 != null) { foreach (PSObject psObject1 in property4) { StringBuilder stringBuilder = new StringBuilder(); PSObject[] property2 = ProxyCommand.GetProperty <PSObject[]>(psObject1, "introduction"); if (property2 != null) { foreach (PSObject psObject2 in property2) { if (psObject2 != null) { stringBuilder.Append(ProxyCommand.GetObjText((object)psObject2)); } } } PSObject property3 = ProxyCommand.GetProperty <PSObject>(psObject1, "code"); if (property3 != null) { stringBuilder.Append(property3.ToString()); } PSObject[] property5 = ProxyCommand.GetProperty <PSObject[]>(psObject1, "remarks"); if (property5 != null) { stringBuilder.Append("\n"); foreach (PSObject psObject2 in property5) { string property6 = ProxyCommand.GetProperty <string>(psObject2, "text"); stringBuilder.Append(property6.ToString()); } } if (stringBuilder.Length > 0) { sb.Append("\n\n.EXAMPLE\n\n"); sb.Append(stringBuilder.ToString()); } } } PSObject property7 = ProxyCommand.GetProperty <PSObject>(help, "alertSet"); ProxyCommand.AppendContent(sb, ".NOTES", ProxyCommand.GetProperty <PSObject[]>(property7, "alert")); PSObject property8 = ProxyCommand.GetProperty <PSObject>(ProxyCommand.GetProperty <PSObject>(help, "inputTypes"), "inputType"); ProxyCommand.AppendType(sb, ".INPUTS", property8); PSObject property9 = ProxyCommand.GetProperty <PSObject>(ProxyCommand.GetProperty <PSObject>(help, "returnValues"), "returnValue"); ProxyCommand.AppendType(sb, ".OUTPUTS", property9); PSObject[] property10 = ProxyCommand.GetProperty <PSObject[]>(ProxyCommand.GetProperty <PSObject>(help, "relatedLinks"), "navigationLink"); if (property10 != null) { foreach (PSObject psObject in property10) { ProxyCommand.AppendContent(sb, ".LINK", (object)ProxyCommand.GetProperty <PSObject>(psObject, "uri")); ProxyCommand.AppendContent(sb, ".LINK", (object)ProxyCommand.GetProperty <PSObject>(psObject, "linkText")); } } ProxyCommand.AppendContent(sb, ".COMPONENT", (object)ProxyCommand.GetProperty <PSObject>(help, "Component")); ProxyCommand.AppendContent(sb, ".ROLE", (object)ProxyCommand.GetProperty <PSObject>(help, "Role")); ProxyCommand.AppendContent(sb, ".FUNCTIONALITY", (object)ProxyCommand.GetProperty <PSObject>(help, "Functionality")); return(sb.ToString()); }
public static string GetHelpComments(PSObject help) { if (help == null) { throw new ArgumentNullException("help"); } bool flag = false; foreach (string str in help.InternalTypeNames) { if (str.Contains("HelpInfo")) { flag = true; break; } } if (!flag) { throw new InvalidOperationException(ProxyCommandStrings.HelpInfoObjectRequired); } StringBuilder sb = new StringBuilder(); AppendContent(sb, ".SYNOPSIS", GetProperty <string>(help, "Synopsis")); AppendContent(sb, ".DESCRIPTION", GetProperty <PSObject[]>(help, "Description")); PSObject[] property = GetProperty <PSObject[]>(GetProperty <PSObject>(help, "Parameters"), "Parameter"); if (property != null) { foreach (PSObject obj3 in property) { PSObject obj4 = GetProperty <PSObject>(obj3, "Name"); PSObject[] objArray2 = GetProperty <PSObject[]>(obj3, "Description"); sb.AppendFormat("\n.PARAMETER {0}\n\n", obj4); foreach (PSObject obj5 in objArray2) { string str3 = GetProperty <string>(obj5, "Text"); if (str3 == null) { str3 = obj5.ToString(); } if (!string.IsNullOrEmpty(str3)) { sb.Append(str3); sb.Append("\n"); } } } } PSObject[] objArray3 = GetProperty <PSObject[]>(GetProperty <PSObject>(help, "examples"), "example"); if (objArray3 != null) { foreach (PSObject obj7 in objArray3) { StringBuilder builder2 = new StringBuilder(); PSObject[] objArray4 = GetProperty <PSObject[]>(obj7, "introduction"); if (objArray4 != null) { foreach (PSObject obj8 in objArray4) { if (obj8 != null) { builder2.Append(GetObjText(obj8)); } } } PSObject obj9 = GetProperty <PSObject>(obj7, "code"); if (obj9 != null) { builder2.Append(obj9.ToString()); } PSObject[] objArray5 = GetProperty <PSObject[]>(obj7, "remarks"); if (objArray5 != null) { builder2.Append("\n"); foreach (PSObject obj10 in objArray5) { builder2.Append(GetProperty <string>(obj10, "text").ToString()); } } if (builder2.Length > 0) { sb.Append("\n\n.EXAMPLE\n\n"); sb.Append(builder2.ToString()); } } } PSObject obj11 = GetProperty <PSObject>(help, "alertSet"); AppendContent(sb, ".NOTES", GetProperty <PSObject[]>(obj11, "alert")); PSObject parent = GetProperty <PSObject>(GetProperty <PSObject>(help, "inputTypes"), "inputType"); AppendType(sb, ".INPUTS", parent); PSObject obj15 = GetProperty <PSObject>(GetProperty <PSObject>(help, "returnValues"), "returnValue"); AppendType(sb, ".OUTPUTS", obj15); PSObject[] objArray6 = GetProperty <PSObject[]>(GetProperty <PSObject>(help, "relatedLinks"), "navigationLink"); if (objArray6 != null) { foreach (PSObject obj17 in objArray6) { AppendContent(sb, ".LINK", GetProperty <PSObject>(obj17, "uri")); AppendContent(sb, ".LINK", GetProperty <PSObject>(obj17, "linkText")); } } AppendContent(sb, ".COMPONENT", GetProperty <PSObject>(help, "Component")); AppendContent(sb, ".ROLE", GetProperty <PSObject>(help, "Role")); AppendContent(sb, ".FUNCTIONALITY", GetProperty <PSObject>(help, "Functionality")); return(sb.ToString()); }
/// <summary> /// helper to convert an PSObject into a string /// It takes into account enumerations (use display name) /// </summary> /// <param name="so">shell object to process</param> /// <param name="expressionFactory">expression factory to create MshExpression</param> /// <param name="enumerationLimit">limit on IEnumerable enumeration</param> /// <param name="formatErrorObject">stores errors during string conversion</param> /// <returns>string representation</returns> internal static string SmartToString(PSObject so, MshExpressionFactory expressionFactory, int enumerationLimit, StringFormatError formatErrorObject) { if (so == null) return ""; try { IEnumerable e = PSObjectHelper.GetEnumerable(so); if (e != null) { StringBuilder sb = new StringBuilder(); sb.Append("{"); bool first = true; int enumCount = 0; IEnumerator enumerator = e.GetEnumerator(); if (enumerator != null) { IBlockingEnumerator<object> be = enumerator as IBlockingEnumerator<object>; if (be != null) { while (be.MoveNext(false)) { if (LocalPipeline.GetExecutionContextFromTLS().CurrentPipelineStopping) { throw new PipelineStoppedException(); } if (enumerationLimit >= 0) { if (enumCount == enumerationLimit) { sb.Append(ellipses); break; } enumCount++; } if (!first) { sb.Append(", "); } sb.Append(GetObjectName(be.Current, expressionFactory)); if (first) first = false; } } else { foreach (object x in e) { if (LocalPipeline.GetExecutionContextFromTLS().CurrentPipelineStopping) { throw new PipelineStoppedException(); } if (enumerationLimit >= 0) { if (enumCount == enumerationLimit) { sb.Append(ellipses); break; } enumCount++; } if (!first) { sb.Append(", "); } sb.Append(GetObjectName(x, expressionFactory)); if (first) first = false; } } } sb.Append("}"); return sb.ToString(); } // take care of the case there is no base object return so.ToString(); } catch (ExtendedTypeSystemException e) { // NOTE: we catch all the exceptions, since we do not know // what the underlying object access would throw if (formatErrorObject != null) { formatErrorObject.sourceObject = so; formatErrorObject.exception = e; } return ""; } }
private string SerializePSObject(PSObject psObject) { // handle some trivial cases if ((psObject == null) || (psObject.BaseObject == null)) { return null; } // convert the base object to a string based on its type var baseType = psObject.BaseObject.GetType(); if (baseType == typeof(Hashtable)) { var value = new System.Text.StringBuilder(); foreach (DictionaryEntry dictionaryEntry in (Hashtable)psObject.BaseObject) { value.AppendFormat("{0} = {1}\n", dictionaryEntry.Key, dictionaryEntry.Value); } return value.ToString(); } else { return psObject.ToString(); } }
internal static string SmartToString(PSObject so, MshExpressionFactory expressionFactory, int enumerationLimit, StringFormatError formatErrorObject) { if (so == null) { return ""; } try { IEnumerable enumerable = GetEnumerable(so); if (enumerable != null) { StringBuilder builder = new StringBuilder(); builder.Append("{"); bool flag = true; int num = 0; IEnumerator enumerator = enumerable.GetEnumerator(); if (enumerator != null) { IBlockingEnumerator<object> enumerator2 = enumerator as IBlockingEnumerator<object>; if (enumerator2 != null) { while (enumerator2.MoveNext(false)) { if (LocalPipeline.GetExecutionContextFromTLS().CurrentPipelineStopping) { throw new PipelineStoppedException(); } if (enumerationLimit >= 0) { if (num == enumerationLimit) { builder.Append("..."); break; } num++; } if (!flag) { builder.Append(", "); } builder.Append(GetObjectName(enumerator2.Current, expressionFactory)); if (flag) { flag = false; } } } else { foreach (object obj2 in enumerable) { if (LocalPipeline.GetExecutionContextFromTLS().CurrentPipelineStopping) { throw new PipelineStoppedException(); } if (enumerationLimit >= 0) { if (num == enumerationLimit) { builder.Append("..."); break; } num++; } if (!flag) { builder.Append(", "); } builder.Append(GetObjectName(obj2, expressionFactory)); if (flag) { flag = false; } } } } builder.Append("}"); return builder.ToString(); } return so.ToString(); } catch (ExtendedTypeSystemException exception) { if (formatErrorObject != null) { formatErrorObject.sourceObject = so; formatErrorObject.exception = exception; } return ""; } }
/// <summary> /// Construct the text that can be used in a multi-line comment for get-help. /// </summary> /// <param name="help">A custom PSObject created by Get-Help.</param> /// <returns>A string that can be used as the help comment for script for the input HelpInfo object.</returns> /// <exception cref="System.ArgumentNullException">When the help argument is null.</exception> /// <exception cref="System.InvalidOperationException">When the help argument is not recognized as a HelpInfo object.</exception> public static string GetHelpComments(PSObject help) { if (help == null) { throw new ArgumentNullException(nameof(help)); } bool isHelpObject = false; foreach (string typeName in help.InternalTypeNames) { if (typeName.Contains("HelpInfo")) { isHelpObject = true; break; } } if (!isHelpObject) { string error = ProxyCommandStrings.HelpInfoObjectRequired; throw new InvalidOperationException(error); } StringBuilder sb = new StringBuilder(); AppendContent(sb, ".SYNOPSIS", GetProperty <string>(help, "Synopsis")); AppendContent(sb, ".DESCRIPTION", GetProperty <PSObject[]>(help, "Description")); PSObject parameters = GetProperty <PSObject>(help, "Parameters"); PSObject[] parameter = GetProperty <PSObject[]>(parameters, "Parameter"); if (parameter != null) { foreach (PSObject param in parameter) { PSObject name = GetProperty <PSObject>(param, "Name"); PSObject[] description = GetProperty <PSObject[]>(param, "Description"); sb.Append("\n.PARAMETER "); sb.Append(name); sb.Append("\n\n"); foreach (PSObject obj in description) { string text = GetProperty <string>(obj, "Text") ?? obj.ToString(); if (!string.IsNullOrEmpty(text)) { sb.Append(text); sb.Append('\n'); } } } } PSObject examples = GetProperty <PSObject>(help, "examples"); PSObject[] example = GetProperty <PSObject[]>(examples, "example"); if (example != null) { foreach (PSObject ex in example) { StringBuilder exsb = new StringBuilder(); PSObject[] introduction = GetProperty <PSObject[]>(ex, "introduction"); if (introduction != null) { foreach (PSObject intro in introduction) { if (intro != null) { exsb.Append(GetObjText(intro)); } } } PSObject code = GetProperty <PSObject>(ex, "code"); if (code != null) { exsb.Append(code.ToString()); } PSObject[] remarks = GetProperty <PSObject[]>(ex, "remarks"); if (remarks != null) { exsb.Append('\n'); foreach (PSObject remark in remarks) { string remarkText = GetProperty <string>(remark, "text"); exsb.Append(remarkText); } } if (exsb.Length > 0) { sb.Append("\n\n.EXAMPLE\n\n"); sb.Append(exsb); } } } PSObject alertSet = GetProperty <PSObject>(help, "alertSet"); AppendContent(sb, ".NOTES", GetProperty <PSObject[]>(alertSet, "alert")); PSObject inputtypes = GetProperty <PSObject>(help, "inputTypes"); PSObject inputtype = GetProperty <PSObject>(inputtypes, "inputType"); AppendType(sb, ".INPUTS", inputtype); PSObject returnValues = GetProperty <PSObject>(help, "returnValues"); PSObject returnValue = GetProperty <PSObject>(returnValues, "returnValue"); AppendType(sb, ".OUTPUTS", returnValue); PSObject relatedLinks = GetProperty <PSObject>(help, "relatedLinks"); PSObject[] navigationLink = GetProperty <PSObject[]>(relatedLinks, "navigationLink"); if (navigationLink != null) { foreach (PSObject link in navigationLink) { // Most likely only one of these will append anything, but it // isn't wrong to append them both. AppendContent(sb, ".LINK", GetProperty <PSObject>(link, "uri")); AppendContent(sb, ".LINK", GetProperty <PSObject>(link, "linkText")); } } AppendContent(sb, ".COMPONENT", GetProperty <PSObject>(help, "Component")); AppendContent(sb, ".ROLE", GetProperty <PSObject>(help, "Role")); AppendContent(sb, ".FUNCTIONALITY", GetProperty <PSObject>(help, "Functionality")); return(sb.ToString()); }
private string GetStringFromPSObject(PSObject source) { PSPropertyInfo stringSerializationSource = source.GetStringSerializationSource(null); string str = null; if (stringSerializationSource != null) { object obj2 = stringSerializationSource.Value; if (obj2 != null) { try { str = obj2.ToString(); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); } } return str; } try { str = source.ToString(); } catch (Exception exception2) { CommandProcessorBase.CheckForSevereException(exception2); } return str; }
/// <summary> /// Gets the string from PSObject using the information from /// types.ps1xml. This string is used for serializing the PSObject. /// </summary> /// /// <param name="source"> /// PSObject to be converted to string /// </param> /// /// <returns> /// string value to use for serializing this PSObject. /// </returns> private string GetStringFromPSObject(PSObject source) { Dbg.Assert(source != null, "caller should have validated the information"); // check if we have a well known string serialization source PSPropertyInfo serializationProperty = source.GetStringSerializationSource(null); string result = null; if (serializationProperty != null) { object val = serializationProperty.Value; if (val != null) { try { // if we have a string serialization value, return it result = val.ToString(); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); } } } else { try { // fall back value result = source.ToString(); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); } } return result; }
internal static FormatEntryData GenerateOutOfBandObjectAsToString(PSObject so) { FormatEntryData fed = new FormatEntryData(); fed.outOfBand = true; RawTextFormatEntry rawTextEntry = new RawTextFormatEntry(); rawTextEntry.text = so.ToString(); fed.formatEntryInfo = rawTextEntry; return fed; }
private PSObject GetSingle(string caption, string message, string prompt, string help, PSObject psDefault, Type type) { if (null != type && type.Equals(typeof(PSCredential))) { return PSObject.AsPSObject(((IPSConsole)this).PromptForCredential(caption, message, String.Empty, prompt)); } while(true) { // TODO: Only show the help message if they type '?' as their entry something, in which case show help and re-prompt. if (!String.IsNullOrEmpty(help)) ((IPSConsole) this).WriteLine(_brushes.ConsoleColorFromBrush(_brushes.VerboseForeground), _brushes.ConsoleColorFromBrush(_brushes.VerboseBackground), help); ((IPSConsole) this).Write(String.Format("{0}: ", prompt)); if (null != type && typeof(SecureString).Equals(type)) { var userData = ((IPSConsole) this).ReadLineAsSecureString() ?? new SecureString(); return PSObject.AsPSObject(userData); } // Note: This doesn't look the way it does in PowerShell, but it should work :) else { if (psDefault != null && psDefault.ToString().Length > 0) { if (Dispatcher.CheckAccess()) { CurrentCommand = psDefault.ToString(); _commandBox.SelectAll(); } else { Dispatcher.BeginInvoke(DispatcherPriority.Input, (Action<string>) (def => { CurrentCommand = def; _commandBox.SelectAll(); }), psDefault.ToString()); } } var userData = ((IPSConsole) this).ReadLine(); if (type != null && userData.Length > 0) { object output; var ice = TryConvertTo(type, userData, out output); // Special exceptions that happen when casting to numbers and such ... if (ice == null) { return PSObject.AsPSObject(output); } if ((ice.InnerException is FormatException) || (ice.InnerException is OverflowException)) { ((IPSConsole)this).WriteErrorLine( String.Format( @"Cannot recognize ""{0}"" as a {1} due to a format error.", userData, type.FullName ) ); } else { return PSObject.AsPSObject(String.Empty); } } else if (userData.Length == 0) { return PSObject.AsPSObject(String.Empty); } else return PSObject.AsPSObject(userData); } } }