Saturday, 15 May 2010

Powershell looping through Object Variables returning values -



Powershell looping through Object Variables returning values -

suppose have object $foo many (500+) properties.

$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" ...

i want loop through properties in $foo , each value , process in way.

$quarters = @("1","2","3","4") foreach($quarter in $quarters) { if($foo.q$quarter_sales -gt $foo.q$quarter_expense) { #process info } }

how accomplish this? get-variable? get-member? combination? other way?

changing construction of $foo not option, unless can programmatically. sorry.

you can utilize subexpression evaluate property name, such as:

$quarters = @("1","2","3","4") foreach($quarter in $quarters) { if($foo.$("q"+$quarter+"_sales") -gt $foo.$("q"+$quarter+"_expense")) { #process info } }

that evaluate sub-expressions first, figures out "q"+$quarter+"_sales" , evaluates $foo.q1_sales result.

powershell

No comments:

Post a Comment