Ask the Expert

Steps to read XML files with PowerShell

Can PowerShell handle XML files?

Requires Free Membership to View

Extensible Markup Language is just text, so PowerShell can certainly load the contents of an XML file into a variable:

$xml = Get-Content MyXML.xml

But that doesn't tell PowerShell to actually understand the XML; it's just a big wodge of text. To have PowerShell read the XML, you can force it to parse the XML:

[xml]$xml = Get-Content MyXML.xml

Doing so will run the XML through the .NET Framework's XmlDocument class, meaning it will examine the XML and build a document object model from it. If the XML doesn't parse or validate, then you'll get an error.

The resulting XML object essentially turns XML nodes such as <computer></computer> into objects and collections, and it lets you access attributes like<tag attribute="value"> as object properties. It can get fairly complicated quickly. You also obtain ways to add nodes and attributes, remove them and write the modified bit back to a text file.

There are also methods for executing XPath queries. XPath is a XML query language that lets you search an XML file for specified nodes, attributes and so on.

There's a good tutorial here, if you want to start using XML in PowerShell. Be patient and be prepared to experiment a bit. Learning XPath can be extraordinarily helpful.

About the author
Don Jones is a well-known and respected PowerShell expert and educator. He's co-author of three books on PowerShell (see PowerShellBooks.com for a list). You can find his content online, including his PowerShell Q&A forums, by visiting DonJones.com.

This was first published in April 2013

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: