如何在本地创建的 PSObject 上设置默认 ToString()? [英] How to set the default ToString() on a locally created PSObject?

查看:29
本文介绍了如何在本地创建的 PSObject 上设置默认 ToString()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够设置我创建的 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()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆