Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I change how PowerShell displays a property of my custom type?
    text
    copied!<p>In PowerShell when I view my custom <code>MyStuff.Document</code> type in a table (or list) its <code>Content</code> property is not displayed using my <code>ToString()</code> function. Instead PowerShell iterates the collection and shows the items in it. I want it to use my <code>ToString()</code> function.</p> <p>Example:</p> <pre><code>$doc = New-Object MyStuff.Document $doc.Content.Add("Segment 1") $doc.Content.Add("Segment 2") $doc | select Content </code></pre> <p>It currently shows:</p> <pre><code>Content ------- {Segment 1, Segment 2} </code></pre> <p>When I want it to show:</p> <pre><code>Content ------- something custom </code></pre> <p>Where "something custom" is the output of my <code>ToString()</code> function.</p> <p>I've dug into <a href="http://technet.microsoft.com/en-us/library/hh847831.aspx" rel="nofollow"><code>*.format.ps1xml</code></a> files which I think are what I need use but I can't figure out how to do what I want. <a href="http://technet.microsoft.com/en-us/library/hh849908.aspx" rel="nofollow"><code>Update-TypeData</code></a> also looked promising but I haven't had luck with that either yet.</p> <p>Any help would be much appreciated.</p> <p>These are the custom types I'm working with:</p> <pre><code>namespace MyStuff { public class Document { public string Name { get; set; } public FormattedTextBlock Content { get; set; } } public class FormattedTextBlock : ICollection&lt;FormattedTextSegment&gt; { public void Add(string text) { this.Add(new FormattedTextSegment() { Text = text }); } // ... ICollection implementation clipped public override string ToString() { // ... reality is more complex return "something custom"; } } public class FormattedTextSegment { public string Text { get; set; } public override string ToString() { return Text; } } } </code></pre> <h2>Update</h2> <p>To be clear, I'm aware of strategies like <code>$doc | select @{ Expression = { $_.Content.ToString() }; Label = "Content" }</code>. I'm looking for away to tell PowerShell how to format my property by default.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload