Search notes:

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.

classWithToString

The following class explicitly defines a ToString() method:
class classWithToString {

   [int   ] $num
   [string] $text

   classWithToString ($n, $t) {
       $this.num    = $n
       $this.text   = $t
   }

   [string] ToString() {
      return "num = $($this.num), text = $($this.text)"
   }
}
Github repository about-PowerShell, path: /language/class/ToString/classWithToString.ps1

classWithoutToString

This class does not have an explicit Tostring() method:
class classWithoutToString {

   [int   ] $num
   [string] $text

   classWithoutToString ($n, $t) {
       $this.num    = $n
       $this.text   = $t
   }
}
Github repository about-PowerShell, path: /language/class/ToString/classWithoutToString.ps1

Calling ToString()

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
Github repository about-PowerShell, path: /language/class/ToString/callToString.ps1

ToString() is called in string interpolation

When a variable is embedded in a string («string interpolation»), the variable expands to the value that is returned by ToString():
write-host "$obj_with"
#
#  num = 42, text = hello world

write-host "$obj_without"
#
#  classWithoutToString
Github repository about-PowerShell, path: /language/class/ToString/stringInterpolation.ps1

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
Github repository about-PowerShell, path: /language/class/ToString/select-string.ps1

Index