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?

3 Answers 3

25

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}
Sign up to request clarification or add additional context in comments.

2 Comments

+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.
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
10

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

$obj.psobject.properties["foo"].value

1 Comment

Whhat is "bla"?
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.

4 Comments

I thought of that as I usually incorporate parentheses for this exact reason. Still does not yield what I want.
That's weird. A simple test for me was $a = gci | select -f 1; $a.psobject.properties|%{$_.Name + "tt" + $a.($_.Name)} which works just fine.
Another way is with quotes: $obj."$($_.name)"
@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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.