20

I'm going through an array of objects and I can display the objects fine.

$obj

displays each object in my foreach loop fine. I'm trying to access the object fields and their values. This code also works fine:

$obj.psobject.properties

To just see the names of each object's fields, I do this:

$obj.psobject.properties | % {$_.name}

which also works fine.

When I try to access the values of those field by doing this:

$obj.psobject.properties | % {$obj.$_.name}

nothing is returned or displayed.

This is done for diagnostic purposes to see whether I can access the values of the fields. The main dilemma is that I cannot access a specific field's value. I.e.

$obj."some field"

does not return a value even though I have confirmed that "some field" has a value.

This has baffled me. Does anyone know what I'm doing wrong?

starcodex
  • 2,198
  • 4
  • 22
  • 34

3 Answers3

24

Once you iterate over the properties inside the foreach, they become available via $_ (current object symbol). Just like you printed the names of the properties with $_.Name, using $_.Value will print their values:

$obj.psobject.properties | % {$_.Value}
Shay Levy
  • 121,444
  • 32
  • 184
  • 206
  • 1
    +1. I suspected something as obvious as this, so went ahead to check, but you posted your answer by the time I came back. As a side note to OP - you could have discovered the `Value` property by doing this: `$obj.psobject.properties | gm`. – Victor Zakharov Jul 29 '13 at 15:12
  • I did that for diagnostic purposes to see whether I could access the values of the fields. However when I try to access the value of a certain field that I know exists, like $obj."certain field", nothing is returned – starcodex Jul 29 '13 at 15:14
9

Operator precedence interprets that in the following way:

($obj.$_).Name

which leads to nothing because you want

$obj.($_.Name)

which will first evaluate the name of a property and then access it on $obj.

Joey
  • 344,408
  • 85
  • 689
  • 683
  • I thought of that as I usually incorporate parentheses for this exact reason. Still does not yield what I want. – starcodex Jul 29 '13 at 15:33
  • That's weird. A simple test for me was `$a = gci | select -f 1; $a.psobject.properties|%{$_.Name + "`t`t" + $a.($_.Name)}` which works just fine. – Joey Jul 29 '13 at 15:35
  • Another way is with quotes: `$obj."$($_.name)"` – x0n Jul 29 '13 at 18:13
  • @x0n: That's a little overkill, though, to use a double-quoted string with a sub-expression when you can just use parentheses (or the sub-expression without the surrounding string). – Joey Jul 29 '13 at 18:34
9

You don't have to iterate over all properties if you just need the value of one of them:

$obj.psobject.properties["foo"].value
seg
  • 1,398
  • 1
  • 11
  • 18