Below you can see my code. I' trying to calculate the average line by line of my csv file. The only way I have been able to do this is by using it as an array. My question is, is there a way to pass each line through the function so that I don't have to create multiple functions?
The file looks like this:
V1 V2 V3
5 9 3
5 6 2
Script:
Function Average($a) {
Foreach ($line in $a) {
$total = [int]$a[0].V1 + [int]$a[0].V2 + [int]$a[0].V3
}
return "The Average is $($total / 3)"
}
#Variables
$a = (Import-Csv "Document.csv")
#Logic
Average
You can access the properties of each line (without knowing their names) through the psobject
reference:
function Get-CsvAverage
{
param(
[psobject[]]$Lines
)
# Loop through all lines of input
foreach($Line in $Lines){
# For each "line" object, loop through its properties
$Numbers = $Line.psobject.Properties |ForEach-Object {
# Attempt to cast the property's value as an integer
$_.Value -as [int]
}
# Output the average for the current line
Write-Output ($numbers | Measure-Object -Average).Average
}
}
Then use like:
$CsvLines = Import-Csv Document.csv
Get-CsvAverage $CsvLines
For your sample input this would produce:
5.66666666666667
4.33333333333333
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments