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' }
which currently outputs this:
name job
---- ---
bob janitor
to instead output this:
name job
---- ---
bob he is a janitor, he is
I.e. attach script block to the PSObject's ToString() that just does this:
{ 'he is a {0}, he is' -f $job }
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With