Thursday, February 15, 2007

PowerShell, creating statistics


# Creating statistics in PowerShell is very easy. There is no need to
# create several variables, it can all be combined into one!

# This is how it can be done


# Create hash-table a.k.a. associative array
# Note that you do not have to define the members before using them
$stats=@{}

# do something, here the distribution of random numbers are
# used as an example, but in the real world it could be the
# number of objects processed, number of updates succeeded
# and number of failed operations

$random=new-object system.random

1..1000 | % {
$n=$random.next(0,10)
switch ($n) {
# Increase the counters
0 { $stats.zeroes+=1; break }
1 { $stats.ones+=1; break }
2 { $stats.twos+=1; break }
default { $stats.others+=1 }
}
}

# report the results
$stats

# Output
Name Value
---- -----
twos 93
zeroes 108
ones 104
others 695



# this is almost too easy...

# Hint: If you want pretty-formatted names, use $stats."Pretty Name"+=1



Updated with missing vertical bar in code (it is hard getting pasted code to work)

3 comments:

  1. You missed the pipe sign, well known blogspot editor issue :)

    $hay
    http://scriptolog.blogspot.com

    ReplyDelete
  2. This is a little smaller code for almost the same thing

    $stats=@{}
    $random = New-Object System.Random
    1..1000 | % {
    $number = $random.Next(0,10)
    $stats.($number)++
    }
    $stats

    ReplyDelete