2012-03-28 60 views
7

我希望能够设置我创建的PSObject的默认文本渲染。例如,我想这样的代码:如何在本地创建的PSObject上设置默认的ToString()?

new-object psobject -property @{ name = 'bob'; job = 'janitor' } 

目前输出该:

name job 
---- --- 
bob janitor 

,而不是输出此:

name job 
---- --- 
bob he is a janitor, he is 

即附加脚本块到PSObject的ToString(),仅仅做到这一点:

{ 'he is a {0}, he is' -f $job } 

我不需要为类型做了一些C#的add-type,是吧?我希望不是。我制作了大量本地psobjects,并希望将它们分散到字符串上,以帮助使它们的输出更加美观,但如果它有很多代码,它可能不值得。

回答

14

使用Add-Member cmdlet来替代默认ToString方法:

$pso = new-object psobject -property @{ name = 'bob'; job = 'janitor' } 
$pso | add-member scriptmethod tostring { 'he is a {0}, he is' -f $this.job } -force 
$pso.tostring() 
+0

哇它真的就是这么简单。谢谢。 – scobi 2012-03-28 19:09:06

相关问题