Using Classes (Overloading – Part 4)

by Feb 9, 2017

Methods in classes can be overloaded: you can define multiple methods with the same name but different parameters. This works similar to parameter sets in cmdlets. Have a look:

#requires -Version 5.0
class StopWatch 
  # property is marked "hidden" because it is used internally only
  # it is not shown by IntelliSense
  hidden [DateTime]$LastDate = (Get-Date)
  # when no parameter is specified, do not emit verbose info

  [int] TimeElapsed()
    return $this.TimeElapsedInternal($false)
  # user can decide whether to emit verbose info or not
  [int] TimeElapsed([bool]$Verbose)
    return $this.TimeElapsedInternal($Verbose)
  # this method is called by all public methods
  hidden [int] TimeElapsedInternal([bool]$Verbose)
    # get current date
    $now = Get-Date
    # and subtract last date, report back milliseconds
    $milliseconds =  ($now - $this.LastDate).TotalMilliseconds
    # use $this to access internal properties and methods
    # update the last date so that it now is the current date
    $this.LastDate = $now
    # output verbose information if requested
    if ($Verbose) { 
      $VerbosePreference = 'Continue'
      Write-Verbose "Last step took $milliseconds ms." }
    # use "return" to define the return value
    return $milliseconds
    $this.LastDate = Get-Date

# create instance
$stopWatch = [StopWatch]::new()

# do not output verbose info

Start-Sleep -Seconds 2
# output verbose info

$a = Get-Service
# output verbose info

The result would look similar to this:

VERBOSE: Last step took  2018.1879 ms.
VERBOSE: Last step took  68.8883 ms.

Twitter This Tip! ReTweet this Tip!