问题描述
我希望能够设置我创建的 PSObject 的默认文本渲染.例如,我想要这个代码:
I'd like to be able to set the default text rendering of a PSObject I create. For example, I'd like this code:
new-object psobject -property @{ name = 'bob'; job = 'janitor' }
当前输出这个:
name job
---- ---
bob janitor
改为输出:
name job
---- ---
bob he is a janitor, he is
即将脚本块附加到 PSObject 的 ToString() 中:
I.e. attach script block to the PSObject's ToString() that just does this:
{ 'he is a {0}, he is' -f $job }
我不需要用一些 C# 来做一个 add-type
类型,是吗?我希望不是.我制作了很多本地 psobjects 并希望在它们上散布 to-strings 以帮助使它们的输出更好,但如果它有很多代码,它可能不值得.
I don't need to do an add-type
with some C# for the type, do I? I hope not. I make lots of local psobjects and would like to scatter to-strings on them to help make their output nicer, but if it's a lot of code it probably won't be worth it.
推荐答案
使用 Add-Member
cmdlet 覆盖默认的 ToString 方法:
Use the Add-Member
cmdlet to override the default ToString method:
$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()
这篇关于如何在本地创建的 PSObject 上设置默认 ToString()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!