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

I would like to be able to set the default text rendering for the created PSObject. For example, I would like to get this code:

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

which currently outputs this:

 name job ---- --- bob janitor 

output this instead:

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

those. attach a script block to the PSObject ToString () object, which just does this:

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

I don't need to do an add-type with some C # for a type, right? I hope not. I do a lot of local psobjects and would like to scatter lines on them to make their output more enjoyable, but if it has a lot of code, then it probably won't be worth it.

+7
source share
1 answer

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() 
+14
source

All Articles