Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the default ToString() on a locally created PSObject?

Tags:

powershell

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.

like image 321
scobi Avatar asked Mar 28 '12 17:03

scobi


1 Answers

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()
like image 121
Shay Levy Avatar answered Oct 18 '22 21:10

Shay Levy