Using Classes (Adding Methods – Part 3)

by Feb 8, 2017

One of the great advantages of classes vs. [PSCustomObject] is their ability to also define methods (commands). Here is an example that implements a stop watch. The stop watch can be used to measure how long code takes to execute:

#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)

  [int] TimeElapsed()
  {
    # 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
    # use "return" to define the return value
    return $milliseconds
  }
  
  Reset()
  {
    $this.LastDate = Get-Date
  }
}

And this is how you would use the new stop watch:

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

$stopWatch.TimeElapsed()

Start-Sleep -Seconds 2
$stopWatch.TimeElapsed()

$a = Get-Service
$stopWatch.TimeElapsed()

The result would look similar to this:

 
0
2018
69
 

When you define methods inside a function, there are a couple of rules:

  • If a method has a return value, the return value type must be specified
  • The return value of a method must be specified using the keyword “return”
  • Methods cannot use unassigned variables or read variables from parent scopes
  • To reference a property or other method within the class, prepend “$this.”

Twitter This Tip! ReTweet this Tip!