Measure-CommandEx.ps1 – Runs Measure-Command several times

UPDATE: A newer version is available:


This script executes an expression specified number of times and returns its average duration as [System.TimeSpan]. It displays progress information and difference between two last average duration values. For performance reason progress is updated every second, not every iteration. If delta becomes relatively stable and small enough execution may be stopped by pressing escape: in this case the returned average duration is calculated for the current number of iterations.

Note that in contrast to cmdlet Measure-Command: *) expressions are executed in the inner scope; *) pipelined input is not supported.


## Author   : Roman Kuzmin
## Synopsis : Measure-Command with iteration count and progress
## Modified : 2006.11.06
## Returns averaged duration of -Expression as [timespan]
## -Expression: the expression being executed and timed
## -Count: execute -Count iterations of -Expression
## -NoProgress: don't show progress information
## -NoEscape: don't return on escape

    [scriptblock]$Expression_ = {},
    [int]$Count_ = 10000,

# title
$private:title = "Measuring: {$Expression_}"
if (!$NoEscape_) {
    $title = '[Escape] to return. ' + $title
if ($NoProgress_) {
    Write-Host $title

# iterations
[int64]$private:ticks = 0
$private:time = [datetime]::Now.Date
for($private:e = 1; $e -le $Count_; ++$e) {

    # update the sum
    $private:ticks0 = $ticks
    $ticks += &{(Measure-Command $Expression_).Ticks}

    # update progress each second
    if (!$NoProgress_ -and ([datetime]::Now - $time).TotalSeconds -gt 1) {
        $time = [datetime]::Now
        $private:diff = [int]([math]::Abs($ticks - $ticks0)/$ticks*10000)/100
        Write-Progress $title "Average delta: $diff%" -PercentComplete (100*$e/$Count_)

    # check for escape
    if (!$NoEscape_ -and $Host.UI.RawUI.KeyAvailable) {
        $private:key = $Host.UI.RawUI.ReadKey(14)
        if ($key.KeyDown -and $key.VirtualKeyCode -eq 27) {
            $Count_ = $e

# the result

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: