11

Here is my code:

clear-host

function isNumeric ($x) {
try {
    0 + $x | Out-Null
    return $true
} catch {
    return $false
}
}

function output-file ($ave, $high, $low, $date)
{
write-output "Programer: Oday Sawaqed"
write-output "Class: CIS 124"
write-output "PowerShell Assignmnent"
write-output ""
Write-output ""
write-output " Current Date                    Average               Highest                        Lowest"
write-output " $date                $ave                   $high                 $low "
}


$array = @()
$hold
$n = 1

do {
$hold = read-host "number $n"
if (isNumeric $hold -eq $true){
if (999 -ne $hold) {
$array += $hold
$n = $n + 1
}
else
{
clear-host
write-host "Thank you."
write-host "The numbers you entered are:" $array
write-host "Please select a file name to save the output:"
$fileName = Read-host

$date = get-date -format "dddd, MMMM d, yyyy"
$array = $array | Sort-Object 
$ave = 
$high = $array | Select-Object -last 1
$low = $array | Select-Object -first 1

output-file $ave $high $low $date | Out-File c:\$fileName.txt
}
}
else {
write-host "Please enter a numeric value"
}
}
while (999 -ne $hold)

Now the code works perfectly, i just can't figure out how to add up the values in my array to calculate the average. can someone please help me or give me a hint! i know that i need to add the values together and then divide be $n, i just don't know how to add the values.

2 Answers 2

29

To compute average you can use Measure-Object Cmdlet:

($array | Measure-Object -Average).average
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much :) i knew you can do it this way except that i was put .ave instead of .average and thats why it never worked . I'm still a noob. but yeah, thank you!
+1, I was looking for how to sum an array. And you reminded me that measure-object would also do many of the maths type tasks.
3

One way I found to do the addition would be something like this:


$sum = $array -join '+'
Invoke-Expression $sum

Your output of $sum is simply going to add the "+" and then invoke-expression will actually do the math for you. So your output would look something like:


$sum
1+2+3+4+5+6+7+8+9
Invoke-Expression $sum
45

2 Comments

What about the first method listed in the link which uses "measure-object" to calculate the sum?
Mike Shepard, you are correct. User847990, thanks, that just happened to be what I was looking for! 10 years later and this is still findable, I LOVE THIS SITE!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.