#requires -Version 5.0 classStopWatch { # 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
# 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-Seconds2 # output verbose info $stopWatch.TimeElapsed($true)
$a = Get-Service # output verbose info $stopWatch.TimeElapsed($true)
结果类似如下:
1 2 3 4 5
0 VERBOSE: Last step took 2018.1879 ms. 2018 VERBOSE: Last step took 68.8883 ms. 69