0

HI i'm new to Powershell and i'm trying to read an xml file with some conditions, here is the file

<file>
     <userlist>
         <user name="Martin" log="[email protected]"></user>
         <user name="Tec" log="[email protected]"></user>
         <user name="Obama" log="[email protected]"></user>
     </userlist>
</file> 

What i want to do is to get in a variable my name from a specific log. For exemple get name if log = [email protected] what i tried was this

$PathXML="Path\conf.xml"
 $xml = New-Object -TypeName XML
 $xml.Load($PathXML)
$name = $xml.file.userlist.user | Select-Object -Property name | where log -eq "[email protected]"

The problem is that it returns me my log instead of my name. Thanks in advance for the help.

EDIT it doesn't return me my log but this @{name=Martin}

EDIT V2

after more research i found that my result was an Hashtable so all i have to do get the name is :

$var = $name.name

1 Answer 1

1

I'd use XPath. This one get's the name attribute directly:

$name = $xml.SelectSingleNode('//user[@log = "[email protected]"]/@name')
Write-Host $name

This one gets the matching <user> element:

$name = $xml.SelectSingleNode('//user[@log = "[email protected]"]')
Write-Host $user.name

Your approach would work better without the Select:

$user = $xml.file.userlist.user | where log -eq "[email protected]"
Write-Host $user.name

With simple queries like this, using PowerShell's tools will be roughly on par with XPath, but when things a little get more complex, XPath will quickly be in the lead. That's why I usually use XPath from the start. Also, XPath will be faster than a PowerShell pipeline, which could become relevant with larger XML files.

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

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.