DevilWAH - 2 months ago 5

PowerShell Question

Hi I am trying to return the average for part of an array, when the array is set out like

`$multi = New-Object 'object[,]' $nucount,($readings + 2 )`

and contains "1,4,2,6,3,4,5,nameofitem, cost of item"

I want to get an average for the first 7 elements which I know will always be the first 7 and always be a number. In the case above the number of elements containing a number will be held in a variable called $readings. So the sum I want to do is add up the elements in the array up to the $readings value. and then device by $readings.

I know of ways like this for the whole array

`$Avg = ($array | Measure-Object -Average);`

$Avg.Average;

or simple looping through and calculating the average buy adding and deviding.

But is there any short hand way to do this. I was going to used the ... operator

$multi[2,0..$readings] but i get an error of

Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Int32".

Any help with this would be great if it can provide a short code to replace the

`for (x=1 ; $x -eq $readings ; $X++)`

{

$sum = $sum + $multi[2,$x]

{

$avg= $sum/$readings

Answer

maybe it works like this:

```
0..$readings | % { $sum += $multi[$_] }
```

or if not:

```
0..[int]$readings | % { $sum += $multi[$_] }
```

and first you have to initate $sum

```
$sum = 0
0..$readings | % { $sum += $multi[$_] }
$avg = $sum/$readings
```

here is another eample of what will work:

```
$arr = 1..50
$readings = 15
$arr[2..$readings]
```

regards Eldo.Ob

Source (Stackoverflow)

Comments