1

Here is exam XML..

<?xml version="1.0" encoding="UTF-8"?>
<books>
    <book>
        <title>a book</title>
        <writer>Tom</writer>
    </book> 
    <book>
        <title>b book</title>
        <writer>John</writer>
    </book> 
    <book>
        <title>c book</title>
        <writer>Tom</writer>
    </book> 
</books>

I want to find a list of this writer is Tom. So my script is

[xml]$books = Get-Content C:\Users\Administrator\Documents\books.xml
$books.book| %{$_.book.writer -match 'Tom'}

But this script show only writer...

writer
Tom
Tom

I want to see like this

title      writer
a book     Tom
c book     Tom

help me plz.

3 Answers 3

2

You probably want to use ? , a.k.a. Where-Object instead of %:

$books.book| ?{$_.book.writer -match 'Tom'}

This is a filter on the previous pipeline element, restricting what comes out of it, while with ForEach-Object you're projecting, i.e. creating a new sequence of objects.

Your code and output don't make sense, though. First of all, $books shouldn't have a book property but instead books. You should have seen

True
False
True

instead of writer objects, unless there are multiple writer elements per book.

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

Comments

1

I meant to write

select-xml -Path C:\XML\doc2.txt -XPath "//book[writer='Tom']//ancestor::book"

title writer

a book Tom c book Tom

Ernest Brant

Comments

0

With Powershell 4 just use

$books.books.book

Comments

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.