有没有办法在数组中总结类似的属性名而不是这样做?
foreach ($row in $ExpenseData)
{
if ($row.refuel1_cost + $row.refuel2_cost + $row.refuel3_cost -gt 0)
{
}
}
答案 0 :(得分:1)
如果您希望每行的总和,计算的属性是完美的。
$ExpenseData | Select Name,@{'name'='Total refuel cost';'expression'={$_.refuel1_cost + $_.refuel2_cost + $_.refuel3_cost}}
我使用下面的示例生成费用数据。
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))
编辑:
如果事件不太可能,您希望在获得数据集之前在不知道数据集中的加油成本列数的情况下对相似的属性名称进行求和,您可以使用类似的名称来获取所有相似的名称。
(虽然如果你有名字,请改用名字。它会更有效率)
$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 }}
答案 1 :(得分:0)
试试这个
$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
答案 2 :(得分:0)
理解我的问题的关键是处理System.Data对象 - this post突出了一些问题。
Sage的代码行$CostsProperties = $ExpenseData | get-member | where -like -Property Name -Value 'refuel*_cost' | select -ExpandProperty Name
简化了脚本的结束 - 谢谢你。
以下是我的脚本的外壳
$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
}
}