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
  }
  
  Reset()
  {
    $this.LastDate = Get-Date
  }
}

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

# do not output verbose info
$stopWatch.TimeElapsed()


Start-Sleep -Seconds 2
# output verbose info
$stopWatch.TimeElapsed($true)

$a = Get-Service
# output verbose info
$stopWatch.TimeElapsed($true)

The result would look similar to this:

 
0
VERBOSE: Last step took  2018.1879 ms.
2018
VERBOSE: Last step took  68.8883 ms.
69
 

Twitter This Tip! ReTweet this Tip!