2

Say I have structures like:

[xml]$i = "
<root>
    <item>
        <id>1</id>
        <data>Content_Of_1</data>
    </item>
    <item>
        <id>2</id>
        <data>Content_Of_2</data>
<item>
    <id>5</id>
    <data>Content_Of_5</data>
</item>
    </item>
</root>
"

$foo = @(1,2,3)

And I want to select $i.root.item.data where $i.root.item.id is in $foo.

To select the nodes matching IDs in the array I can do:

($i.root.item | ? {$foo -contains $_.id})

But for some reason if I try to get at $_.data, I get nothing:

($i.root.item | ? {$foo -contains $_.id}).data

Why?

3
  • Are you sure about the xpath tag? Commented Oct 24, 2012 at 16:23
  • Original phrasing invited alternative xpath solutions. I have since got close w/o xpath, but xpath solutions stil welcome. Commented Oct 24, 2012 at 16:29
  • First of all replace you item tag by "items", as far as I remember it exists a problem linked with the fact that "item" is already used as an object property. Commented Oct 24, 2012 at 16:36

1 Answer 1

1

But for some reason if I try to get at $_.data, I get nothing:

($i.root.item | ? {$foo -contains $_.id}).data

The reason you get nothing is you are trying to access a property (data) on the whole collection where it does not exist. You need to do the following:

$i.root.item | ? {$foo -contains $_.id} | ForEach-Object { $_.data }

Which accesses the data property on each object. You could also select the values in the data property for each object:

$i.root.item | ? {$foo -contains $_.id} | Select-Object data

Which would produce an array of PSCustomObjects where each object would contain a single property named data (as opposed to a string array as the ForEach-Object example would).

Note that in Powershell 3.0, with the new property enumeration feature, your original syntax would produce the desired result as the enumeration would automatically be done.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Is there any way to do this without a foreach loop?
@Yevgeniy - updated answer with option of using Select-Object.

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.