PowerShell: Overriding the default ToString() method
Each PowerShell object derives from System.Object and therefore has a ToString() method that returns a string that is (typically) used to render an object in readable and understandable for humans
This page tries to demonstrate the usefulnes of overriding the default Tostring() method.
When calling ToString() on an instance of a class without an explicit definition, The (default) implementation of ToString() of System.Object is invoked. The default implementation simply prints the (fully qualified) class name:
$obj_with = new-object classWithToString 42, 'hello world'
$obj_without = new-object classWithoutToString 99, 'ninety-nine'
$obj_with.ToString()
#
# num = 42, text = hello world
$obj_without.ToString()
#
# classWithoutToString
ToString() is also called by the Select-String cmdlet
When objects are piped into the Select-String cmdlet, Select-String uses the value that is returned by the incoming object's ToString() method to perform the search. In the following examples, Select-String is used to find object that contain an o:
$obj_with, $obj_without | select-string o
#
# num = 42, text = hello world
# classWithoutToString