Powershell循环通过Object Variables返回值

时间:2014-10-14 21:31:49

标签: powershell

假设我有多个(500+)属性的对象$foo

$foo.q1_sales = "1000"
$foo.q1_expense = "800"
$foo.q2_sales = "1325"
$foo.q2_expense = "1168"
$foo.q3_sales = "895"
$foo.q3_expense = "980"
$foo.q4_sales = "900"
$foo.q4_expense = "875"
...

我想遍历$foo中的所有属性并获取每个值并以某种方式处理它。

$quarters = @("1","2","3","4")

foreach($quarter in $quarters) {
  if($foo.q$quarter_sales -gt $foo.q$quarter_expense) {
    #process data
  }
}

我如何做到这一点?获取变量?获得会员?一些组合?其他一些方式?

更改$foo的结构不是一种选择,除非我们可以通过编程方式进行。遗憾。

3 个答案:

答案 0 :(得分:2)

您可以使用子表达式来评估属性名称,例如:

$quarters = @("1","2","3","4")

foreach($quarter in $quarters) {
  if($foo.$("q"+$quarter+"_sales") -gt $foo.$("q"+$quarter+"_expense")) {
    #process data
  }
}

这将首先评估子表达式,因此它会计算出"q"+$quarter+"_sales",然后只评估$foo.q1_sales

答案 1 :(得分:0)

Get-Member是个好主意。这是对此进行扩展的一般尝试,以便您可以看到可以完成的方式。对于我的例子,我的对象将是DateTime:

# Define our object
$object = (Get-Date)

# Get the property names
$properties = $object | Get-Member -MemberType "Property" | % { $_.Name }

# Get our collection of values by iterating the collection of properties
# and for each property getting the value.
$values = $properties | % { $object."$_" }

然后输出将只是DateTime的每个属性的值:

$values

Tuesday, October 14, 2014 12:00:00 AM
14
Tuesday
287
17
Local
972
44
10
45
635489054859729996

Ticks             : 638859729996
Days              : 0
Hours             : 17
Milliseconds      : 972
Minutes           : 44
Seconds           : 45
TotalDays         : 0.739420983791667
TotalHours        : 17.746103611
TotalMilliseconds : 63885972.9996
TotalMinutes      : 1064.76621666
TotalSeconds      : 63885.9729996

2014

这假设您只需要"属性"的MemberTypes,所以如果您也在NoteProperty membertypes之后,这可能还不够。也许" *物业"为了那个原因?

否则,这适用于任何具有属性的任意类型。只需将$object换成你的。{/ p>

答案 2 :(得分:0)

@TheMadTechnician已经提供了最简单的答案。这是另一种方式:

#Sampledata
$foo = New-Object psobject -Property @{
    q1_sales = "1000"
    q1_expense = "800"
    q2_sales = "1325"
    q2_expense = "1168"
    q3_sales = "895"
    q3_expense = "980"
    q4_sales = "900"
    q4_expense = "875"
}

#Convert to array
$array = $foo.psobject.Properties |
#Group by quarter id(number) so we can create an object per quarter
Group-Object { $_.Name -replace 'q(\d+)_.*', '$1' } |
ForEach-Object {
    New-Object psobject -Property @{
        Quarter = $_.Name
        Sales = [int]($_.Group | Where-Object { $_.Name -match 'sales' } | Select-Object -ExpandProperty Value)
        Expense = [int]($_.Group | Where-Object { $_.Name -match 'expense' } | Select-Object -ExpandProperty Value)
    }
}

#Get quarters with positive result
$array | Where-Object { $_.Sales -gt $_.Expense } | ForEach-Object {
    #process data (sends object through in this sample)
    $_
}

输出:

Sales Expense Quarter
----- ------- -------
 1325    1168 2      
 1000     800 1      
  900     875 4