Compartilhar via


Reading or Importing or Parsing XML files with PowerShell

Unfortunately, a lot of the books that talk about XML files were written by and for programmers. So, you’ll see all sorts of frightening and confusing terms like XMLreader, streamreader, schema, XPath and other foreign terms. (I know they always give me pause -- way too complicated.) And a lot of the PowerShell books continue in this vein. This is truly unfortunate because, if you’re looking for a lightweight way to grovel through XML files, PowerShell will be your best friend. I know it became my best friend when I needed a quick way to view the contents of the help files and make sure all the fields were filled in for the help we generated for Windows Server 2008 R2.

So, I’m going to share a secret that I learned from reading chapter 8 of the “Windows PowerShell Cookbook” by Lee Holmes.

When reading an XML file into a PowerShell object using the Get-Content make sure you cast it as XML.

 

Yikes! What is this cast business and why can’t I speak English anymore? Is what I’m sure you’re asking. And how is this making anything easier.

Let’s take this one step at a time. Most PowerShell books will teach you to read in a file using the Get-Content cmdlet. The description of what Get-Content does is: 

The Get-Content cmdlet gets the content of the item at the location specified by the path, such as the text in a file. It reads the content one line at a time and returns an object for each line.

This definition tells me that Get-Content will read in the contents from a file as plain text.

Plenty of PowerShell books show you how to do this. However, if you read in the file as plain text, you are back to parsing through the text. And for XML files, I will be using my above secret to show you a much, much easier way. But before I can do that I have to find a file that all of us can look at together. That way you can follow along with me. And that’s what I’m going to do in the next blog post.

Stay tuned…

(Oh, and while you’re waiting, if you have suggestions of XML files from Windows Server that you’re wondering how to take them apart with PowerShell, please list the files in the comments section. Once I get going we’ll look at a number of suggestions.)

Comments

  • Anonymous
    January 24, 2012
    I have often needed to do work with xml files for Hyper-v VMs.