Calculating average in Powershell?

Soldato
Joined
14 Mar 2004
Posts
8,040
Location
Brit in the USA
Using the Param cmdlt, what could I do to take 3 numbers and average them into an output? I want user to type:

whatever.ps1 Bob 23 56 17

And the output to read:

The average for Bob is 32

Is that even possible?

Cheers!
 
Think you can just go:

$Name = $arg[0]
$Average = ($arg[1] + $arg[2] + $arg[3]) / 3

Write-Host "The average for" $Name "is" $Average


Might be $args[x] rather than $arg[]
Can't quite remember!

Edit: It is $args! You will also need to say "$Average = ([int]$args[1] + [int]$args[2] + [int]$args[3]) / 3" to let it know these are numbers. Other wise it'll treat them as a string and just join them all up so the number would be 235617/3 which you don't want

You could also amend the above to take more than three numbers. $Args is an array powershell uses for each separate parameter passed.

$Name = $args[0]

For ($i = 1; $i -lt $args.Count; $i++) # Start at postition 1 rather than 0 so the name is ignored
{
$Average += [int]$args[$i] # Add each of the numbers up: += same as '$Average = $Average + ...'
}

$Average = $Average / ($args.count - 1) # Divide by number of arguements passed, -1 to exclude the name

Write-Host "The average for" $Name "is" $Average
 
Last edited:
Back
Top Bottom