Reputation: 33
Is there a way of summing similar property names in an array rather than doing this?
foreach ($row in $ExpenseData)
{
if ($row.refuel1_cost + $row.refuel2_cost + $row.refuel3_cost -gt 0)
{
}
}
Upvotes: 2
Views: 220
Reputation: 33
Key to understanding my issue was dealing with a System.Data object - this post highlights some of the issues.
Sage's line of code $CostsProperties = $ExpenseData | get-member | where -like -Property Name -Value 'refuel*_cost' | select -ExpandProperty Name
simplifies the script no end - thank you for that.
Below is the shell of my script
$ExpenseData = Get-MIS-Data -query $ExpensesQuery
# Get all the wildcard columns
$RefuelCols = $ExpenseData | get-member | where -like -Property Name -Value 'refuel*_cost' | select -ExpandProperty Name
#Check if any rows were returned
if ($ExpenseData.count -gt 0)
{
#Loop each returned row
foreach ($row in $ExpenseData)
{
foreach ($c in $RefuelCols)
{
$Total += $row.$c
}
if ($Total -gt 0)
{
#Knowing we have values do some useful stuff here
}
#Reset $Total before next loop
$Total = 0
}
}
Upvotes: 0
Reputation: 10323
If you want that sum for each rows, calculated properties are the perfect fit.
$ExpenseData | Select Name,@{'name'='Total refuel cost';'expression'={$_.refuel1_cost + $_.refuel2_cost + $_.refuel3_cost}}
I used the sample below to generate my expense data.
function CreateSamplePump($Name,$cost1,$cost2,$cost3){
$Props = @{'Name'='';'refuel1_cost'='';'refuel2_cost'='';'refuel3_cost'=''}
$Obj = New-Object psobject -Property $props
$obj.Name = $Name
$obj.refuel1_cost = $cost1
$obj.refuel2_cost = $cost2
$obj.refuel3_cost = $cost3
return $Obj
}
# Generating a sample for test purposes
$ExpenseData = New-Object System.Collections.ArrayList
$ExpenseData.Add((CreateSamplePump -Name 'Pump1' -cost1 10 -cost2 13 -cost3 4))
$ExpenseData.Add((CreateSamplePump -Name 'Pump2' -cost1 4 -cost2 2 -cost3 3))
$ExpenseData.Add((CreateSamplePump -Name 'Pump3' -cost1 3 -cost2 2 -cost3 1))
$ExpenseData.Add((CreateSamplePump -Name 'Pump4' -cost1 4 -cost2 8 -cost3 2))
$ExpenseData.Add((CreateSamplePump -Name 'Pump6' -cost1 6 -cost2 5 -cost3 1))
Edit:
In the event less likely event you would like to sum similar property names without knowing the number of refuel costs column in your dataset prior obtaining it, you could use something like that instead to get all similar names.
(Although if you have the names, use the name instead. It will be more efficient)
$CostsProperties = $ExpenseData | get-member | where -like -Property Name -Value 'refuel*_cost' | select -ExpandProperty Name
$ExpenseData | Select Name, @{'name'='Total refuel cost';'expression'={$Total = 0;Foreach ($c in $CostsProperties) {$Total += $_."$c"};return $Total }}
Upvotes: 1
Reputation: 26150
try this
$a=@{"refuel1_cost"=1;"refuel2_cost"=2;"refuel3_cost"=3;"something"=10}
$a.GetEnumerator() | ?{$_.name -match "refuel" } | select -expand value |measure -Sum |select -expand sum
Upvotes: 0