ToString() Masquerade

by May 23, 2017

In the previous tip we explained that ToString() is a fuzzy way of describing an object, and that the object author can decide what ToString() returns. This is especially true for your PowerShell code. Have a look how easily you can overwrite ToString() for any object:

 
PS> $a = 1
PS> $a | Add-Member -MemberType ScriptMethod -Name toString -Value { 'go away' } -Force 
PS> $a 
go away
PS> $a.GetType().FullName 
System.Int32
PS> $a -eq 1
True
 

Twitter This Tip! ReTweet this Tip!