【发布时间】:2013-07-15 09:45:25
【问题描述】:
在 PowerShell 中,当我在表格(或列表)中查看我的自定义 MyStuff.Document 类型时,它的 Content 属性不会使用我的 ToString() 函数显示。相反,PowerShell 会迭代集合并显示其中的项目。我希望它使用我的ToString() 函数。
例子:
$doc = New-Object MyStuff.Document
$doc.Content.Add("Segment 1")
$doc.Content.Add("Segment 2")
$doc | select Content
目前显示:
Content
-------
{Segment 1, Segment 2}
当我希望它显示时:
Content
-------
something custom
“自定义的东西”是我的 ToString() 函数的输出。
我已经深入研究了*.format.ps1xml 文件,我认为这些文件是我需要使用的,但我不知道如何做我想做的事。 Update-TypeData 看起来也很有希望,但我也没有运气。
任何帮助将不胜感激。
这些是我正在使用的自定义类型:
namespace MyStuff
{
public class Document
{
public string Name { get; set; }
public FormattedTextBlock Content { get; set; }
}
public class FormattedTextBlock : ICollection<FormattedTextSegment>
{
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;
}
}
}
更新
需要明确的是,我知道像 $doc | select @{ Expression = { $_.Content.ToString() }; Label = "Content" } 这样的策略。我正在寻找告诉 PowerShell 默认情况下如何格式化我的属性。
【问题讨论】:
标签: powershell