Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

Extracting XML element values using PowerShell

$
0
0

For how simple this is, I have not been able to find a solution.

Take a simple XML file like the below where each element has a value and no attributes within the <> - 

<Objects><Event><ComputerName>Computer1</ComputerName><UserName>User1</UserName></Event><Event><ComputerName>Computer2</ComputerName><UserName>User2</UserName></Event></Objects>

I can easily extract this data into a table by using the following PowerShell command - 

$xml = Select-Xml -Xml ([XML]($File | Get-Content)) -XPath *; $xml.node.event

And I get the following output - 

ComputerName UserName
------------ --------
Computer1    User1
Computer2    User2

All well and good.  Well, I have some log files I want to parse where each element has both attributes in the <> and values.

So for my example, let's modify the XML slightly so that the elements now also have an attribute inside the <> - 

<Objects><Event><ComputerName attribute="1">Computer1</ComputerName><UserName attribute2="1">User1</UserName></Event><Event><ComputerName attribute="2">Computer2</ComputerName><UserName attribute2="2">User2</UserName></Event></Objects>

I try running the same PowerShell command again -  

$xml = Select-Xml -Xml ([XML]($File | Get-Content)) -XPath *; $xml.node.event

And the output is now bizarre and quite meaningless - 

ComputerName UserName
------------ --------
ComputerName UserName
ComputerName UserName

So my question is quite simple (and hopefully the answer is too!).  How do I get the same output as I did in my first example, when the XML is formed as per my second example?


David



Viewing all articles
Browse latest Browse all 21975

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>