PowerShell And XML

PowerShell And XML

How to work with XML in PowerShell
PowerShell gives you a real advantage when it comes to working with XML based logs. And it is easy. As always this is because of objects.
Just as with other object there is methods and properties. You begin by creating an object of you XML data. It is done by casting the variable as a System.Xml.XmlDocument. Just like this.

[XML]$a = Get-Content C:\file.xml

For instance with a XML file like this.

<Books>
  <Book Name="Book One">
    <Genres>
      <Genre>Adventure</Genre>
    </Genres>
  </Book>
  <Book Name="Book Two">
    <Genres>
      <Genre>Science Fiction</Genre>
    </Genres>
  </Book>
</Books>

The output of $a.Books would yield this:

Book
----
{Book One, Book Two} 

As you can see navigation works like in any other object type, and you now have access to cmdlets like Sort-Object and Select-Object to filter your data.


Uncategorized

Leave a Reply

Your email address will not be published. Required fields are marked *